forked from kubernetes/minikube
-
Notifications
You must be signed in to change notification settings - Fork 1
/
functional_test.go
1413 lines (1230 loc) · 49.2 KB
/
functional_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// +build integration
/*
Copyright 2016 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package integration
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"runtime"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"k8s.io/minikube/pkg/drivers/kic/oci"
"k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/localpath"
"k8s.io/minikube/pkg/minikube/reason"
"k8s.io/minikube/pkg/util/retry"
"github.com/elazarl/goproxy"
"github.com/hashicorp/go-retryablehttp"
"github.com/otiai10/copy"
"github.com/phayes/freeport"
"github.com/pkg/errors"
"golang.org/x/build/kubernetes/api"
)
// validateFunc are for subtests that share a single setup
type validateFunc func(context.Context, *testing.T, string)
// used in validateStartWithProxy and validateSoftStart
var apiPortTest = 8441
// TestFunctional are functionality tests which can safely share a profile in parallel
func TestFunctional(t *testing.T) {
profile := UniqueProfileName("functional")
ctx, cancel := context.WithTimeout(context.Background(), Minutes(40))
defer func() {
if !*cleanup {
return
}
p := localSyncTestPath()
if err := os.Remove(p); err != nil {
t.Logf("unable to remove %q: %v", p, err)
}
Cleanup(t, profile, cancel)
}()
// Serial tests
t.Run("serial", func(t *testing.T) {
tests := []struct {
name string
validator validateFunc
}{
{"CopySyncFile", setupFileSync}, // Set file for the file sync test case
{"StartWithProxy", validateStartWithProxy}, // Set everything else up for success
{"AuditLog", validateAuditAfterStart}, // check audit feature works
{"SoftStart", validateSoftStart}, // do a soft start. ensure config didnt change.
{"KubeContext", validateKubeContext}, // Racy: must come immediately after "minikube start"
{"KubectlGetPods", validateKubectlGetPods}, // Make sure apiserver is up
{"CacheCmd", validateCacheCmd}, // Caches images needed for subsequent tests because of proxy
{"MinikubeKubectlCmd", validateMinikubeKubectl}, // Make sure `minikube kubectl` works
{"MinikubeKubectlCmdDirectly", validateMinikubeKubectlDirectCall},
{"ExtraConfig", validateExtraConfig}, // Ensure extra cmdline config change is saved
{"ComponentHealth", validateComponentHealth},
}
for _, tc := range tests {
tc := tc
if ctx.Err() == context.DeadlineExceeded {
t.Fatalf("Unable to run more tests (deadline exceeded)")
}
t.Run(tc.name, func(t *testing.T) {
tc.validator(ctx, t, profile)
})
}
})
// Parallelized tests
t.Run("parallel", func(t *testing.T) {
tests := []struct {
name string
validator validateFunc
}{
{"ConfigCmd", validateConfigCmd},
{"DashboardCmd", validateDashboardCmd},
{"DryRun", validateDryRun},
{"StatusCmd", validateStatusCmd},
{"LogsCmd", validateLogsCmd},
{"MountCmd", validateMountCmd},
{"ProfileCmd", validateProfileCmd},
{"ServiceCmd", validateServiceCmd},
{"AddonsCmd", validateAddonsCmd},
{"PersistentVolumeClaim", validatePersistentVolumeClaim},
{"TunnelCmd", validateTunnelCmd},
{"SSHCmd", validateSSHCmd},
{"MySQL", validateMySQL},
{"FileSync", validateFileSync},
{"CertSync", validateCertSync},
{"UpdateContextCmd", validateUpdateContextCmd},
{"DockerEnv", validateDockerEnv},
{"NodeLabels", validateNodeLabels},
{"LoadImage", validateLoadImage},
}
for _, tc := range tests {
tc := tc
if ctx.Err() == context.DeadlineExceeded {
t.Fatalf("Unable to run more tests (deadline exceeded)")
}
t.Run(tc.name, func(t *testing.T) {
MaybeParallel(t)
tc.validator(ctx, t, profile)
})
}
})
}
// validateNodeLabels checks if minikube cluster is created with correct kubernetes's node label
func validateNodeLabels(ctx context.Context, t *testing.T, profile string) {
defer PostMortemLogs(t, profile)
rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "get", "nodes", "--output=go-template", "--template='{{range $k, $v := (index .items 0).metadata.labels}}{{$k}} {{end}}'"))
if err != nil {
t.Errorf("failed to 'kubectl get nodes' with args %q: %v", rr.Command(), err)
}
expectedLabels := []string{"minikube.k8s.io/commit", "minikube.k8s.io/version", "minikube.k8s.io/updated_at", "minikube.k8s.io/name"}
for _, el := range expectedLabels {
if !strings.Contains(rr.Output(), el) {
t.Errorf("expected to have label %q in node labels but got : %s", el, rr.Output())
}
}
}
// validateLoadImage makes sure that `minikube load image` works as expected
func validateLoadImage(ctx context.Context, t *testing.T, profile string) {
if NoneDriver() {
t.Skip("load image not available on none driver")
}
if GithubActionRunner() && runtime.GOOS == "darwin" {
t.Skip("skipping on github actions and darwin, as this test requires a running docker daemon")
}
defer PostMortemLogs(t, profile)
// pull busybox
busybox := "busybox:latest"
rr, err := Run(t, exec.CommandContext(ctx, "docker", "pull", busybox))
if err != nil {
t.Fatalf("failed to setup test (pull image): %v\n%s", err, rr.Output())
}
// tag busybox
newImage := fmt.Sprintf("busybox:%s", profile)
rr, err = Run(t, exec.CommandContext(ctx, "docker", "tag", busybox, newImage))
if err != nil {
t.Fatalf("failed to setup test (tag image) : %v\n%s", err, rr.Output())
}
// try to load the new image into minikube
rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "image", "load", newImage))
if err != nil {
t.Fatalf("loading image into minikube: %v\n%s", err, rr.Output())
}
// make sure the image was correctly loaded
var cmd *exec.Cmd
if ContainerRuntime() == "docker" {
cmd = exec.CommandContext(ctx, Target(), "ssh", "-p", profile, "--", "docker", "image", "inspect", newImage)
} else if ContainerRuntime() == "containerd" {
// crictl inspecti busybox:test-example
cmd = exec.CommandContext(ctx, Target(), "ssh", "-p", profile, "--", "sudo", "crictl", "inspecti", newImage)
} else {
// crio adds localhost prefix
// crictl inspecti localhost/busybox:test-example
cmd = exec.CommandContext(ctx, Target(), "ssh", "-p", profile, "--", "sudo", "crictl", "inspecti", "localhost/"+newImage)
}
rr, err = Run(t, cmd)
if err != nil {
t.Fatalf("listing images: %v\n%s", err, rr.Output())
}
if !strings.Contains(rr.Output(), newImage) {
t.Fatalf("expected %s to be loaded into minikube but the image is not there", newImage)
}
}
// check functionality of minikube after evaling docker-env
// TODO: Add validatePodmanEnv for crio runtime: #10231
func validateDockerEnv(ctx context.Context, t *testing.T, profile string) {
if cr := ContainerRuntime(); cr != "docker" {
t.Skipf("only validate docker env with docker container runtime, currently testing %s", cr)
}
defer PostMortemLogs(t, profile)
mctx, cancel := context.WithTimeout(ctx, Seconds(120))
defer cancel()
var rr *RunResult
var err error
if runtime.GOOS == "windows" {
c := exec.CommandContext(mctx, "powershell.exe", "-NoProfile", "-NonInteractive", Target()+" -p "+profile+" docker-env | Invoke-Expression ;"+Target()+" status -p "+profile)
rr, err = Run(t, c)
} else {
c := exec.CommandContext(mctx, "/bin/bash", "-c", "eval $("+Target()+" -p "+profile+" docker-env) && "+Target()+" status -p "+profile)
// we should be able to get minikube status with a bash which evaled docker-env
rr, err = Run(t, c)
}
if mctx.Err() == context.DeadlineExceeded {
t.Errorf("failed to run the command by deadline. exceeded timeout. %s", rr.Command())
}
if err != nil {
t.Fatalf("failed to do status after eval-ing docker-env. error: %v", err)
}
if !strings.Contains(rr.Output(), "Running") {
t.Fatalf("expected status output to include 'Running' after eval docker-env but got: *%s*", rr.Output())
}
mctx, cancel = context.WithTimeout(ctx, Seconds(60))
defer cancel()
// do a eval $(minikube -p profile docker-env) and check if we are point to docker inside minikube
if runtime.GOOS == "windows" { // testing docker-env eval in powershell
c := exec.CommandContext(mctx, "powershell.exe", "-NoProfile", "-NonInteractive", Target(), "-p "+profile+" docker-env | Invoke-Expression ; docker images")
rr, err = Run(t, c)
} else {
c := exec.CommandContext(mctx, "/bin/bash", "-c", "eval $("+Target()+" -p "+profile+" docker-env) && docker images")
rr, err = Run(t, c)
}
if mctx.Err() == context.DeadlineExceeded {
t.Errorf("failed to run the command in 30 seconds. exceeded 30s timeout. %s", rr.Command())
}
if err != nil {
t.Fatalf("failed to run minikube docker-env. args %q : %v ", rr.Command(), err)
}
expectedImgInside := "gcr.io/k8s-minikube/storage-provisioner"
if !strings.Contains(rr.Output(), expectedImgInside) {
t.Fatalf("expected 'docker images' to have %q inside minikube. but the output is: *%s*", expectedImgInside, rr.Output())
}
}
func validateStartWithProxy(ctx context.Context, t *testing.T, profile string) {
defer PostMortemLogs(t, profile)
srv, err := startHTTPProxy(t)
if err != nil {
t.Fatalf("failed to set up the test proxy: %s", err)
}
// Use more memory so that we may reliably fit MySQL and nginx
// changing api server so later in soft start we verify it didn't change
startArgs := append([]string{"start", "-p", profile, "--memory=4000", fmt.Sprintf("--apiserver-port=%d", apiPortTest), "--wait=all"}, StartArgs()...)
c := exec.CommandContext(ctx, Target(), startArgs...)
env := os.Environ()
env = append(env, fmt.Sprintf("HTTP_PROXY=%s", srv.Addr))
env = append(env, "NO_PROXY=")
c.Env = env
rr, err := Run(t, c)
if err != nil {
t.Errorf("failed minikube start. args %q: %v", rr.Command(), err)
}
want := "Found network options:"
if !strings.Contains(rr.Stdout.String(), want) {
t.Errorf("start stdout=%s, want: *%s*", rr.Stdout.String(), want)
}
want = "You appear to be using a proxy"
if !strings.Contains(rr.Stderr.String(), want) {
t.Errorf("start stderr=%s, want: *%s*", rr.Stderr.String(), want)
}
}
func validateAuditAfterStart(ctx context.Context, t *testing.T, profile string) {
got, err := auditContains(profile)
if err != nil {
t.Fatalf("failed to check audit log: %v", err)
}
if !got {
t.Errorf("audit.json does not contain the profile %q", profile)
}
}
// validateSoftStart validates that after minikube already started, a "minikube start" should not change the configs.
func validateSoftStart(ctx context.Context, t *testing.T, profile string) {
defer PostMortemLogs(t, profile)
start := time.Now()
// the test before this had been start with --apiserver-port=8441
beforeCfg, err := config.LoadProfile(profile)
if err != nil {
t.Fatalf("error reading cluster config before soft start: %v", err)
}
if beforeCfg.Config.KubernetesConfig.NodePort != apiPortTest {
t.Errorf("expected cluster config node port before soft start to be %d but got %d", apiPortTest, beforeCfg.Config.KubernetesConfig.NodePort)
}
softStartArgs := []string{"start", "-p", profile, "--alsologtostderr", "-v=8"}
c := exec.CommandContext(ctx, Target(), softStartArgs...)
rr, err := Run(t, c)
if err != nil {
t.Errorf("failed to soft start minikube. args %q: %v", rr.Command(), err)
}
t.Logf("soft start took %s for %q cluster.", time.Since(start), profile)
afterCfg, err := config.LoadProfile(profile)
if err != nil {
t.Errorf("error reading cluster config after soft start: %v", err)
}
if afterCfg.Config.KubernetesConfig.NodePort != apiPortTest {
t.Errorf("expected node port in the config not change after soft start. exepceted node port to be %d but got %d.", apiPortTest, afterCfg.Config.KubernetesConfig.NodePort)
}
}
// validateKubeContext asserts that kubectl is properly configured (race-condition prone!)
func validateKubeContext(ctx context.Context, t *testing.T, profile string) {
defer PostMortemLogs(t, profile)
rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "config", "current-context"))
if err != nil {
t.Errorf("failed to get current-context. args %q : %v", rr.Command(), err)
}
if !strings.Contains(rr.Stdout.String(), profile) {
t.Errorf("expected current-context = %q, but got *%q*", profile, rr.Stdout.String())
}
}
// validateKubectlGetPods asserts that `kubectl get pod -A` returns non-zero content
func validateKubectlGetPods(ctx context.Context, t *testing.T, profile string) {
defer PostMortemLogs(t, profile)
rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "get", "po", "-A"))
if err != nil {
t.Errorf("failed to get kubectl pods: args %q : %v", rr.Command(), err)
}
if rr.Stderr.String() != "" {
t.Errorf("expected stderr to be empty but got *%q*: args %q", rr.Stderr, rr.Command())
}
if !strings.Contains(rr.Stdout.String(), "kube-system") {
t.Errorf("expected stdout to include *kube-system* but got *%q*. args: %q", rr.Stdout, rr.Command())
}
}
// validateMinikubeKubectl validates that the `minikube kubectl` command returns content
func validateMinikubeKubectl(ctx context.Context, t *testing.T, profile string) {
defer PostMortemLogs(t, profile)
// Must set the profile so that it knows what version of Kubernetes to use
kubectlArgs := []string{"-p", profile, "kubectl", "--", "--context", profile, "get", "pods"}
rr, err := Run(t, exec.CommandContext(ctx, Target(), kubectlArgs...))
if err != nil {
t.Fatalf("failed to get pods. args %q: %v", rr.Command(), err)
}
}
// validateMinikubeKubectlDirectCall validates that calling minikube's kubectl
func validateMinikubeKubectlDirectCall(ctx context.Context, t *testing.T, profile string) {
defer PostMortemLogs(t, profile)
dir := filepath.Dir(Target())
dstfn := filepath.Join(dir, "kubectl")
err := os.Link(Target(), dstfn)
if err != nil {
t.Fatal(err)
}
defer os.Remove(dstfn) // clean up
kubectlArgs := []string{"--context", profile, "get", "pods"}
rr, err := Run(t, exec.CommandContext(ctx, dstfn, kubectlArgs...))
if err != nil {
t.Fatalf("failed to run kubectl directly. args %q: %v", rr.Command(), err)
}
}
func validateExtraConfig(ctx context.Context, t *testing.T, profile string) {
defer PostMortemLogs(t, profile)
start := time.Now()
// The tests before this already created a profile, starting minikube with different --extra-config cmdline option.
startArgs := []string{"start", "-p", profile, "--extra-config=apiserver.enable-admission-plugins=NamespaceAutoProvision", "--wait=all"}
c := exec.CommandContext(ctx, Target(), startArgs...)
rr, err := Run(t, c)
if err != nil {
t.Errorf("failed to restart minikube. args %q: %v", rr.Command(), err)
}
t.Logf("restart took %s for %q cluster.", time.Since(start), profile)
afterCfg, err := config.LoadProfile(profile)
if err != nil {
t.Errorf("error reading cluster config after soft start: %v", err)
}
expectedExtraOptions := "apiserver.enable-admission-plugins=NamespaceAutoProvision"
if !strings.Contains(afterCfg.Config.KubernetesConfig.ExtraOptions.String(), expectedExtraOptions) {
t.Errorf("expected ExtraOptions to contain %s but got %s", expectedExtraOptions, afterCfg.Config.KubernetesConfig.ExtraOptions.String())
}
}
// imageID returns a docker image id for image `image` and current architecture
// 'image' is supposed to be one commonly used in minikube integration tests,
// like k8s 'pause'
func imageID(image string) string {
ids := map[string]map[string]string{
"pause": {
"amd64": "0184c1613d929",
"arm64": "3d18732f8686c",
},
}
if imgIds, ok := ids[image]; ok {
if id, ok := imgIds[runtime.GOARCH]; ok {
return id
}
panic(fmt.Sprintf("unexpected architecture for image %q: %v", image, runtime.GOARCH))
}
panic("unexpected image name: " + image)
}
// validateComponentHealth asserts that all Kubernetes components are healthy
// note: it expects all components to be Ready, so it makes sense to run it close after only those tests that include '--wait=all' start flag (ie, with extra wait)
func validateComponentHealth(ctx context.Context, t *testing.T, profile string) {
defer PostMortemLogs(t, profile)
// The ComponentStatus API is deprecated in v1.19, so do the next closest thing.
found := map[string]bool{
"etcd": false,
"kube-apiserver": false,
"kube-controller-manager": false,
"kube-scheduler": false,
}
rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "get", "po", "-l", "tier=control-plane", "-n", "kube-system", "-o=json"))
if err != nil {
t.Fatalf("failed to get components. args %q: %v", rr.Command(), err)
}
cs := api.PodList{}
d := json.NewDecoder(bytes.NewReader(rr.Stdout.Bytes()))
if err := d.Decode(&cs); err != nil {
t.Fatalf("failed to decode kubectl json output: args %q : %v", rr.Command(), err)
}
for _, i := range cs.Items {
for _, l := range i.Labels {
if _, ok := found[l]; ok { // skip irrelevant (eg, repeating/redundant '"tier": "control-plane"') labels
found[l] = true
t.Logf("%s phase: %s", l, i.Status.Phase)
if i.Status.Phase != api.PodRunning {
t.Errorf("%s is not Running: %+v", l, i.Status)
continue
}
for _, c := range i.Status.Conditions {
if c.Type == api.PodReady {
if c.Status != api.ConditionTrue {
t.Errorf("%s is not Ready: %+v", l, i.Status)
} else {
t.Logf("%s status: %s", l, c.Type)
}
break
}
}
}
}
}
for k, v := range found {
if !v {
t.Errorf("expected component %q was not found", k)
}
}
}
func validateStatusCmd(ctx context.Context, t *testing.T, profile string) {
defer PostMortemLogs(t, profile)
rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status"))
if err != nil {
t.Errorf("failed to run minikube status. args %q : %v", rr.Command(), err)
}
// Custom format
rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "-f", "host:{{.Host}},kublet:{{.Kubelet}},apiserver:{{.APIServer}},kubeconfig:{{.Kubeconfig}}"))
if err != nil {
t.Errorf("failed to run minikube status with custom format: args %q: %v", rr.Command(), err)
}
re := `host:([A-z]+),kublet:([A-z]+),apiserver:([A-z]+),kubeconfig:([A-z]+)`
match, _ := regexp.MatchString(re, rr.Stdout.String())
if !match {
t.Errorf("failed to match regex %q for minikube status with custom format. args %q. output: %s", re, rr.Command(), rr.Output())
}
// Json output
rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "status", "-o", "json"))
if err != nil {
t.Errorf("failed to run minikube status with json output. args %q : %v", rr.Command(), err)
}
var jsonObject map[string]interface{}
err = json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
if err != nil {
t.Errorf("failed to decode json from minikube status. args %q. %v", rr.Command(), err)
}
if _, ok := jsonObject["Host"]; !ok {
t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "Host")
}
if _, ok := jsonObject["Kubelet"]; !ok {
t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "Kubelet")
}
if _, ok := jsonObject["APIServer"]; !ok {
t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "APIServer")
}
if _, ok := jsonObject["Kubeconfig"]; !ok {
t.Errorf("%q failed: %v. Missing key %s in json object", rr.Command(), err, "Kubeconfig")
}
}
// validateDashboardCmd asserts that the dashboard command works
func validateDashboardCmd(ctx context.Context, t *testing.T, profile string) {
defer PostMortemLogs(t, profile)
mctx, cancel := context.WithTimeout(ctx, Seconds(300))
defer cancel()
args := []string{"dashboard", "--url", "-p", profile, "--alsologtostderr", "-v=1"}
ss, err := Start(t, exec.CommandContext(mctx, Target(), args...))
if err != nil {
t.Errorf("failed to run minikube dashboard. args %q : %v", args, err)
}
defer func() {
ss.Stop(t)
}()
s, err := dashboardURL(ss.Stdout)
if err != nil {
if runtime.GOOS == "windows" {
t.Skip(err)
}
t.Fatal(err)
}
u, err := url.Parse(strings.TrimSpace(s))
if err != nil {
t.Fatalf("failed to parse %q: %v", s, err)
}
resp, err := retryablehttp.Get(u.String())
if err != nil {
t.Fatalf("failed to http get %q: %v\nresponse: %+v", u.String(), err, resp)
}
if resp.StatusCode != http.StatusOK {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Errorf("failed to read http response body from dashboard %q: %v", u.String(), err)
}
t.Errorf("%s returned status code %d, expected %d.\nbody:\n%s", u, resp.StatusCode, http.StatusOK, body)
}
}
// dashboardURL gets the dashboard URL from the command stdout.
func dashboardURL(b *bufio.Reader) (string, error) {
// match http://127.0.0.1:XXXXX/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/
dashURLRegexp := regexp.MustCompile(`^http:\/\/127\.0\.0\.1:[0-9]{5}\/api\/v1\/namespaces\/kubernetes-dashboard\/services\/http:kubernetes-dashboard:\/proxy\/$`)
s := bufio.NewScanner(b)
for s.Scan() {
t := s.Text()
if dashURLRegexp.MatchString(t) {
return t, nil
}
}
if err := s.Err(); err != nil {
return "", fmt.Errorf("failed reading input: %v", err)
}
return "", fmt.Errorf("output didn't produce a URL")
}
// validateDryRun asserts that the dry-run mode quickly exits with the right code
func validateDryRun(ctx context.Context, t *testing.T, profile string) {
// dry-run mode should always be able to finish quickly (<5s)
mctx, cancel := context.WithTimeout(ctx, Seconds(5))
defer cancel()
// Too little memory!
startArgs := append([]string{"start", "-p", profile, "--dry-run", "--memory", "250MB", "--alsologtostderr"}, StartArgs()...)
c := exec.CommandContext(mctx, Target(), startArgs...)
rr, err := Run(t, c)
wantCode := reason.ExInsufficientMemory
if rr.ExitCode != wantCode {
t.Errorf("dry-run(250MB) exit code = %d, wanted = %d: %v", rr.ExitCode, wantCode, err)
}
dctx, cancel := context.WithTimeout(ctx, Seconds(5))
defer cancel()
startArgs = append([]string{"start", "-p", profile, "--dry-run", "--alsologtostderr", "-v=1"}, StartArgs()...)
c = exec.CommandContext(dctx, Target(), startArgs...)
rr, err = Run(t, c)
if rr.ExitCode != 0 || err != nil {
t.Errorf("dry-run exit code = %d, wanted = %d: %v", rr.ExitCode, 0, err)
}
}
// validateCacheCmd tests functionality of cache command (cache add, delete, list)
func validateCacheCmd(ctx context.Context, t *testing.T, profile string) {
defer PostMortemLogs(t, profile)
if NoneDriver() {
t.Skipf("skipping: cache unsupported by none")
}
t.Run("cache", func(t *testing.T) {
t.Run("add_remote", func(t *testing.T) {
for _, img := range []string{"k8s.gcr.io/pause:3.1", "k8s.gcr.io/pause:3.3", "k8s.gcr.io/pause:latest"} {
rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "cache", "add", img))
if err != nil {
t.Errorf("failed to 'cache add' remote image %q. args %q err %v", img, rr.Command(), err)
}
}
})
t.Run("add_local", func(t *testing.T) {
if GithubActionRunner() && runtime.GOOS == "darwin" {
t.Skipf("skipping this test because Docker can not run in macos on github action free version. https://github.saobby.my.eu.orgmunity/t/is-it-possible-to-install-and-configure-docker-on-macos-runner/16981")
}
_, err := exec.LookPath(oci.Docker)
if err != nil {
t.Skipf("docker is not installed, skipping local image test")
}
dname, err := ioutil.TempDir("", profile)
if err != nil {
t.Fatalf("Cannot create temp dir: %v", err)
}
message := []byte("FROM scratch\nADD Dockerfile /x")
err = ioutil.WriteFile(filepath.Join(dname, "Dockerfile"), message, 0644)
if err != nil {
t.Fatalf("unable to write Dockerfile: %v", err)
}
img := "minikube-local-cache-test:" + profile
_, err = Run(t, exec.CommandContext(ctx, "docker", "build", "-t", img, dname))
if err != nil {
t.Skipf("failed to build docker image, skipping local test: %v", err)
}
rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "cache", "add", img))
if err != nil {
t.Errorf("failed to 'cache add' local image %q. args %q err %v", img, rr.Command(), err)
}
})
t.Run("delete_k8s.gcr.io/pause:3.3", func(t *testing.T) {
rr, err := Run(t, exec.CommandContext(ctx, Target(), "cache", "delete", "k8s.gcr.io/pause:3.3"))
if err != nil {
t.Errorf("failed to delete image k8s.gcr.io/pause:3.3 from cache. args %q: %v", rr.Command(), err)
}
})
t.Run("list", func(t *testing.T) {
rr, err := Run(t, exec.CommandContext(ctx, Target(), "cache", "list"))
if err != nil {
t.Errorf("failed to do cache list. args %q: %v", rr.Command(), err)
}
if !strings.Contains(rr.Output(), "k8s.gcr.io/pause") {
t.Errorf("expected 'cache list' output to include 'k8s.gcr.io/pause' but got: ***%s***", rr.Output())
}
if strings.Contains(rr.Output(), "k8s.gcr.io/pause:3.3") {
t.Errorf("expected 'cache list' output not to include k8s.gcr.io/pause:3.3 but got: ***%s***", rr.Output())
}
})
t.Run("verify_cache_inside_node", func(t *testing.T) {
rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", "crictl", "images"))
if err != nil {
t.Errorf("failed to get images by %q ssh %v", rr.Command(), err)
}
pauseID := imageID("pause")
if !strings.Contains(rr.Output(), pauseID) {
t.Errorf("expected sha for pause:3.3 %q to be in the output but got *%s*", pauseID, rr.Output())
}
})
t.Run("cache_reload", func(t *testing.T) { // deleting image inside minikube node manually and expecting reload to bring it back
img := "k8s.gcr.io/pause:latest"
// deleting image inside minikube node manually
var binary string
switch ContainerRuntime() {
case "docker":
binary = "docker"
case "containerd", "crio":
binary = "crictl"
}
rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", binary, "rmi", img))
if err != nil {
t.Errorf("failed to manually delete image %q : %v", rr.Command(), err)
}
// make sure the image is deleted.
rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", "crictl", "inspecti", img))
if err == nil {
t.Errorf("expected an error but got no error. image should not exist. ! cmd: %q", rr.Command())
}
// minikube cache reload.
rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "cache", "reload"))
if err != nil {
t.Errorf("expected %q to run successfully but got error: %v", rr.Command(), err)
}
// make sure 'cache reload' brought back the manually deleted image.
rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "sudo", "crictl", "inspecti", img))
if err != nil {
t.Errorf("expected %q to run successfully but got error: %v", rr.Command(), err)
}
})
// delete will clean up the cached images since they are global and all other tests will load it for no reason
t.Run("delete", func(t *testing.T) {
for _, img := range []string{"k8s.gcr.io/pause:3.1", "k8s.gcr.io/pause:latest"} {
rr, err := Run(t, exec.CommandContext(ctx, Target(), "cache", "delete", img))
if err != nil {
t.Errorf("failed to delete %s from cache. args %q: %v", img, rr.Command(), err)
}
}
})
})
}
// validateConfigCmd asserts basic "config" command functionality
func validateConfigCmd(ctx context.Context, t *testing.T, profile string) {
tests := []struct {
args []string
wantOut string
wantErr string
}{
{[]string{"unset", "cpus"}, "", ""},
{[]string{"get", "cpus"}, "", "Error: specified key could not be found in config"},
{[]string{"set", "cpus", "2"}, "", "! These changes will take effect upon a minikube delete and then a minikube start"},
{[]string{"get", "cpus"}, "2", ""},
{[]string{"unset", "cpus"}, "", ""},
{[]string{"get", "cpus"}, "", "Error: specified key could not be found in config"},
}
for _, tc := range tests {
args := append([]string{"-p", profile, "config"}, tc.args...)
rr, err := Run(t, exec.CommandContext(ctx, Target(), args...))
if err != nil && tc.wantErr == "" {
t.Errorf("failed to config minikube. args %q : %v", rr.Command(), err)
}
got := strings.TrimSpace(rr.Stdout.String())
if got != tc.wantOut {
t.Errorf("expected config output for %q to be -%q- but got *%q*", rr.Command(), tc.wantOut, got)
}
got = strings.TrimSpace(rr.Stderr.String())
if got != tc.wantErr {
t.Errorf("expected config error for %q to be -%q- but got *%q*", rr.Command(), tc.wantErr, got)
}
}
}
// validateLogsCmd asserts basic "logs" command functionality
func validateLogsCmd(ctx context.Context, t *testing.T, profile string) {
rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "logs"))
if err != nil {
t.Errorf("%s failed: %v", rr.Command(), err)
}
expectedWords := []string{"apiserver", "Linux", "kubelet", "Audit", "Last Start"}
switch ContainerRuntime() {
case "docker":
expectedWords = append(expectedWords, "Docker")
case "containerd":
expectedWords = append(expectedWords, "containerd")
case "crio":
expectedWords = append(expectedWords, "crio")
}
for _, word := range expectedWords {
if !strings.Contains(rr.Stdout.String(), word) {
t.Errorf("expected minikube logs to include word: -%q- but got \n***%s***\n", word, rr.Output())
}
}
}
// validateProfileCmd asserts "profile" command functionality
func validateProfileCmd(ctx context.Context, t *testing.T, profile string) {
t.Run("profile_not_create", func(t *testing.T) {
// Profile command should not create a nonexistent profile
nonexistentProfile := "lis"
rr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", nonexistentProfile))
if err != nil {
t.Errorf("%s failed: %v", rr.Command(), err)
}
rr, err = Run(t, exec.CommandContext(ctx, Target(), "profile", "list", "--output", "json"))
if err != nil {
t.Errorf("%s failed: %v", rr.Command(), err)
}
var profileJSON map[string][]map[string]interface{}
err = json.Unmarshal(rr.Stdout.Bytes(), &profileJSON)
if err != nil {
t.Errorf("%s failed: %v", rr.Command(), err)
}
for profileK := range profileJSON {
for _, p := range profileJSON[profileK] {
var name = p["Name"]
if name == nonexistentProfile {
t.Errorf("minikube profile %s should not exist", nonexistentProfile)
}
}
}
})
t.Run("profile_list", func(t *testing.T) {
// helper function to run command then, return target profile line from table output.
extractrofileListFunc := func(rr *RunResult) string {
listLines := strings.Split(strings.TrimSpace(rr.Stdout.String()), "\n")
for i := 3; i < (len(listLines) - 1); i++ {
profileLine := listLines[i]
if strings.Contains(profileLine, profile) {
return profileLine
}
}
return ""
}
// List profiles
start := time.Now()
rr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", "list"))
elapsed := time.Since(start)
if err != nil {
t.Errorf("failed to list profiles: args %q : %v", rr.Command(), err)
}
t.Logf("Took %q to run %q", elapsed, rr.Command())
profileLine := extractrofileListFunc(rr)
if profileLine == "" {
t.Errorf("expected 'profile list' output to include %q but got *%q*. args: %q", profile, rr.Stdout.String(), rr.Command())
}
// List profiles with light option.
start = time.Now()
lrr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", "list", "-l"))
lightElapsed := time.Since(start)
if err != nil {
t.Errorf("failed to list profiles: args %q : %v", lrr.Command(), err)
}
t.Logf("Took %q to run %q", lightElapsed, lrr.Command())
profileLine = extractrofileListFunc(lrr)
if profileLine == "" || !strings.Contains(profileLine, "Skipped") {
t.Errorf("expected 'profile list' output to include %q with 'Skipped' status but got *%q*. args: %q", profile, rr.Stdout.String(), rr.Command())
}
if lightElapsed > 3*time.Second {
t.Errorf("expected running time of '%q' is less than 3 seconds. Took %q ", lrr.Command(), lightElapsed)
}
})
t.Run("profile_json_output", func(t *testing.T) {
// helper function to run command then, return target profile object from json output.
extractProfileObjFunc := func(rr *RunResult) *config.Profile {
var jsonObject map[string][]config.Profile
err := json.Unmarshal(rr.Stdout.Bytes(), &jsonObject)
if err != nil {
t.Errorf("failed to decode json from profile list: args %q: %v", rr.Command(), err)
return nil
}
for _, profileObject := range jsonObject["valid"] {
if profileObject.Name == profile {
return &profileObject
}
}
return nil
}
start := time.Now()
rr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", "list", "-o", "json"))
elapsed := time.Since(start)
if err != nil {
t.Errorf("failed to list profiles with json format. args %q: %v", rr.Command(), err)
}
t.Logf("Took %q to run %q", elapsed, rr.Command())
pr := extractProfileObjFunc(rr)
if pr == nil {
t.Errorf("expected the json of 'profile list' to include %q but got *%q*. args: %q", profile, rr.Stdout.String(), rr.Command())
}
start = time.Now()
lrr, err := Run(t, exec.CommandContext(ctx, Target(), "profile", "list", "-o", "json", "--light"))
lightElapsed := time.Since(start)
if err != nil {
t.Errorf("failed to list profiles with json format. args %q: %v", lrr.Command(), err)
}
t.Logf("Took %q to run %q", lightElapsed, lrr.Command())
pr = extractProfileObjFunc(lrr)
if pr == nil || pr.Status != "Skipped" {
t.Errorf("expected the json of 'profile list' to include 'Skipped' status for %q but got *%q*. args: %q", profile, lrr.Stdout.String(), lrr.Command())
}
if lightElapsed > 3*time.Second {
t.Errorf("expected running time of '%q' is less than 3 seconds. Took %q ", lrr.Command(), lightElapsed)
}
})
}
// validateServiceCmd asserts basic "service" command functionality
func validateServiceCmd(ctx context.Context, t *testing.T, profile string) {
defer PostMortemLogs(t, profile)
defer func() {
if t.Failed() {
t.Logf("service test failed - dumping debug information")
t.Logf("-----------------------service failure post-mortem--------------------------------")
ctx, cancel := context.WithTimeout(context.Background(), Minutes(2))
defer cancel()
rr, err := Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "describe", "po", "hello-node"))
if err != nil {
t.Logf("%q failed: %v", rr.Command(), err)
}
t.Logf("hello-node pod describe:\n%s", rr.Stdout)
rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "logs", "-l", "app=hello-node"))
if err != nil {
t.Logf("%q failed: %v", rr.Command(), err)
}
t.Logf("hello-node logs:\n%s", rr.Stdout)
rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "describe", "svc", "hello-node"))
if err != nil {
t.Logf("%q failed: %v", rr.Command(), err)
}
t.Logf("hello-node svc describe:\n%s", rr.Stdout)
}
}()
var rr *RunResult
var err error
// k8s.gcr.io/echoserver is not multi-arch
if arm64Platform() {
rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "create", "deployment", "hello-node", "--image=k8s.gcr.io/echoserver-arm:1.8"))
} else {
rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "create", "deployment", "hello-node", "--image=k8s.gcr.io/echoserver:1.8"))
}
if err != nil {
t.Fatalf("failed to create hello-node deployment with this command %q: %v.", rr.Command(), err)
}
rr, err = Run(t, exec.CommandContext(ctx, "kubectl", "--context", profile, "expose", "deployment", "hello-node", "--type=NodePort", "--port=8080"))
if err != nil {
t.Fatalf("failed to expose hello-node deployment: %q : %v", rr.Command(), err)
}
if _, err := PodWait(ctx, t, profile, "default", "app=hello-node", Minutes(10)); err != nil {
t.Fatalf("failed waiting for hello-node pod: %v", err)
}
rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "service", "list"))
if err != nil {
t.Errorf("failed to do service list. args %q : %v", rr.Command(), err)
}
if !strings.Contains(rr.Stdout.String(), "hello-node") {
t.Errorf("expected 'service list' to contain *hello-node* but got -%q-", rr.Stdout.String())
}
if NeedsPortForward() {
t.Skipf("test is broken for port-forwarded drivers: https://github.com/kubernetes/minikube/issues/7383")
}