-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
functional_test.go
2339 lines (2030 loc) · 87.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
//go: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"
"net"
"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/detect"
"k8s.io/minikube/pkg/minikube/localpath"
"k8s.io/minikube/pkg/minikube/reason"
"k8s.io/minikube/pkg/minikube/service"
"k8s.io/minikube/pkg/util/retry"
"github.com/blang/semver/v4"
"github.com/elazarl/goproxy"
"github.com/hashicorp/go-retryablehttp"
cp "github.com/otiai10/copy"
"github.com/phayes/freeport"
"github.com/pkg/errors"
"golang.org/x/build/kubernetes/api"
"k8s.io/minikube/pkg/minikube/cruntime"
)
const echoServerImg = "kicbase/echo-server"
// 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
// Store the proxy session so we can clean it up at the end
var mitm *StartSession
var runCorpProxy = detect.GithubActionRunner() && runtime.GOOS == "linux" && !arm64Platform()
// 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 didn't 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},
{"LogsCmd", validateLogsCmd},
{"LogsFileCmd", validateLogsFileCmd},
{"InvalidService", validateInvalidService},
}
for _, tc := range tests {
tc := tc
if ctx.Err() == context.DeadlineExceeded {
t.Fatalf("Unable to run more tests (deadline exceeded)")
}
if tc.name == "StartWithProxy" && runCorpProxy {
tc.name = "StartWithCustomCerts"
tc.validator = validateStartWithCustomCerts
}
t.Run(tc.name, func(t *testing.T) {
tc.validator(ctx, t, profile)
})
}
})
defer func() {
cleanupUnwantedImages(ctx, t, profile)
if runCorpProxy {
mitm.Stop(t)
}
}()
// Parallelized tests
t.Run("parallel", func(t *testing.T) {
tests := []struct {
name string
validator validateFunc
}{
{"ConfigCmd", validateConfigCmd},
{"DashboardCmd", validateDashboardCmd},
{"DryRun", validateDryRun},
{"InternationalLanguage", validateInternationalLanguage},
{"StatusCmd", validateStatusCmd},
{"MountCmd", validateMountCmd},
{"ProfileCmd", validateProfileCmd},
{"ServiceCmd", validateServiceCmd},
{"ServiceCmdConnect", validateServiceCmdConnect},
{"AddonsCmd", validateAddonsCmd},
{"PersistentVolumeClaim", validatePersistentVolumeClaim},
{"TunnelCmd", validateTunnelCmd},
{"SSHCmd", validateSSHCmd},
{"CpCmd", validateCpCmd},
{"MySQL", validateMySQL},
{"FileSync", validateFileSync},
{"CertSync", validateCertSync},
{"UpdateContextCmd", validateUpdateContextCmd},
{"DockerEnv", validateDockerEnv},
{"PodmanEnv", validatePodmanEnv},
{"NodeLabels", validateNodeLabels},
{"ImageCommands", validateImageCommands},
{"NonActiveRuntimeDisabled", validateNotActiveRuntimeDisabled},
{"Version", validateVersionCmd},
{"License", validateLicenseCmd},
}
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)
})
}
})
}
func cleanupUnwantedImages(ctx context.Context, t *testing.T, profile string) {
_, err := exec.LookPath(oci.Docker)
if err != nil {
t.Skipf("docker is not installed, cannot delete docker images")
} else {
t.Run("delete echo-server images", func(t *testing.T) {
tags := []string{"1.0", profile}
for _, tag := range tags {
image := fmt.Sprintf("%s:%s", echoServerImg, tag)
rr, err := Run(t, exec.CommandContext(ctx, "docker", "rmi", "-f", image))
if err != nil {
t.Logf("failed to remove image %q from docker images. args %q: %v", image, rr.Command(), err)
}
}
})
t.Run("delete my-image image", func(t *testing.T) {
newImage := fmt.Sprintf("localhost/my-image:%s", profile)
rr, err := Run(t, exec.CommandContext(ctx, "docker", "rmi", "-f", newImage))
if err != nil {
t.Logf("failed to remove image my-image from docker images. args %q: %v", rr.Command(), err)
}
})
t.Run("delete minikube cached images", func(t *testing.T) {
img := "minikube-local-cache-test:" + profile
rr, err := Run(t, exec.CommandContext(ctx, "docker", "rmi", "-f", img))
if err != nil {
t.Logf("failed to remove image minikube local cache test images from docker. args %q: %v", rr.Command(), err)
}
})
}
}
// 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)
// docs: Get the node labels from the cluster with `kubectl get nodes`
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)
}
// docs: check if the node labels matches with the expected Minikube labels: `minikube.k8s.io/*`
expectedLabels := []string{"minikube.k8s.io/commit", "minikube.k8s.io/version", "minikube.k8s.io/updated_at", "minikube.k8s.io/name", "minikube.k8s.io/primary"}
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())
}
}
}
// tagAndLoadImage is a helper function to pull, tag, load image (decreases cyclomatic complexity for linter).
func tagAndLoadImage(ctx context.Context, t *testing.T, profile, taggedImage string) {
newPulledImage := fmt.Sprintf("%s:%s", echoServerImg, "latest")
rr, err := Run(t, exec.CommandContext(ctx, "docker", "pull", newPulledImage))
if err != nil {
t.Fatalf("failed to setup test (pull image): %v\n%s", err, rr.Output())
}
rr, err = Run(t, exec.CommandContext(ctx, "docker", "tag", newPulledImage, taggedImage))
if err != nil {
t.Fatalf("failed to setup test (tag image) : %v\n%s", err, rr.Output())
}
rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "image", "load", "--daemon", taggedImage, "--alsologtostderr"))
if err != nil {
t.Fatalf("loading image into minikube from daemon: %v\n%s", err, rr.Output())
}
checkImageExists(ctx, t, profile, taggedImage)
}
// runImageList is a helper function to run 'image ls' command test.
func runImageList(ctx context.Context, t *testing.T, profile, testName, format, expectedFormat string) {
expectedResult := expectedImageFormat(expectedFormat)
// docs: Make sure image listing works by `minikube image ls`
t.Run(testName, func(t *testing.T) {
MaybeParallel(t)
rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "image", "ls", "--format", format, "--alsologtostderr"))
if err != nil {
t.Fatalf("listing image with minikube: %v\n%s", err, rr.Output())
}
if rr.Stdout.Len() > 0 {
t.Logf("(dbg) Stdout: %s:\n%s", rr.Command(), rr.Stdout)
}
if rr.Stderr.Len() > 0 {
t.Logf("(dbg) Stderr: %s:\n%s", rr.Command(), rr.Stderr)
}
list := rr.Output()
for _, theImage := range expectedResult {
if !strings.Contains(list, theImage) {
t.Fatalf("expected %s to be listed with minikube but the image is not there", theImage)
}
}
})
}
func expectedImageFormat(format string) []string {
return []string{
fmt.Sprintf(format, "registry.k8s.io/pause"),
fmt.Sprintf(format, "registry.k8s.io/kube-apiserver"),
}
}
// validateImageCommands runs tests on all the `minikube image` commands, ex. `minikube image load`, `minikube image list`, etc.
func validateImageCommands(ctx context.Context, t *testing.T, profile string) {
// docs(skip): Skips on `none` driver as image loading is not supported
if NoneDriver() {
t.Skip("image commands are not available on the none driver")
}
// docs(skip): Skips on GitHub Actions and macOS as this test case requires a running docker daemon
if detect.GithubActionRunner() && runtime.GOOS == "darwin" {
t.Skip("skipping on darwin github action runners, as this test requires a running docker daemon")
}
runImageList(ctx, t, profile, "ImageListShort", "short", "%s")
runImageList(ctx, t, profile, "ImageListTable", "table", "| %s")
runImageList(ctx, t, profile, "ImageListJson", "json", "[\"%s")
runImageList(ctx, t, profile, "ImageListYaml", "yaml", "- %s")
// docs: Make sure image building works by `minikube image build`
t.Run("ImageBuild", func(t *testing.T) {
MaybeParallel(t)
if _, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "ssh", "pgrep", "buildkitd")); err == nil {
t.Errorf("buildkitd process is running, should not be running until `minikube image build` is ran")
}
newImage := fmt.Sprintf("localhost/my-image:%s", profile)
// try to build the new image with minikube
rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "image", "build", "-t", newImage, filepath.Join(*testdataDir, "build"), "--alsologtostderr"))
if err != nil {
t.Fatalf("building image with minikube: %v\n%s", err, rr.Output())
}
if rr.Stdout.Len() > 0 {
t.Logf("(dbg) Stdout: %s:\n%s", rr.Command(), rr.Stdout)
}
if rr.Stderr.Len() > 0 {
t.Logf("(dbg) Stderr: %s:\n%s", rr.Command(), rr.Stderr)
}
checkImageExists(ctx, t, profile, newImage)
})
taggedImage := fmt.Sprintf("%s:%s", echoServerImg, profile)
imageFile := "echo-server-save.tar"
var imagePath string
defer os.Remove(imageFile)
t.Run("Setup", func(t *testing.T) {
var err error
imagePath, err = filepath.Abs(imageFile)
if err != nil {
t.Fatalf("failed to get absolute path of file %q: %v", imageFile, err)
}
pulledImage := fmt.Sprintf("%s:%s", echoServerImg, "1.0")
rr, err := Run(t, exec.CommandContext(ctx, "docker", "pull", pulledImage))
if err != nil {
t.Fatalf("failed to setup test (pull image): %v\n%s", err, rr.Output())
}
rr, err = Run(t, exec.CommandContext(ctx, "docker", "tag", pulledImage, taggedImage))
if err != nil {
t.Fatalf("failed to setup test (tag image) : %v\n%s", err, rr.Output())
}
})
// docs: Make sure image loading from Docker daemon works by `minikube image load --daemon`
t.Run("ImageLoadDaemon", func(t *testing.T) {
rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "image", "load", "--daemon", taggedImage, "--alsologtostderr"))
if err != nil {
t.Fatalf("loading image into minikube from daemon: %v\n%s", err, rr.Output())
}
checkImageExists(ctx, t, profile, taggedImage)
})
// docs: Try to load image already loaded and make sure `minikube image load --daemon` works
t.Run("ImageReloadDaemon", func(t *testing.T) {
rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "image", "load", "--daemon", taggedImage, "--alsologtostderr"))
if err != nil {
t.Fatalf("loading image into minikube from daemon: %v\n%s", err, rr.Output())
}
checkImageExists(ctx, t, profile, taggedImage)
})
// docs: Make sure a new updated tag works by `minikube image load --daemon`
t.Run("ImageTagAndLoadDaemon", func(t *testing.T) {
tagAndLoadImage(ctx, t, profile, taggedImage)
})
// docs: Make sure image saving works by `minikube image load --daemon`
t.Run("ImageSaveToFile", func(t *testing.T) {
rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "image", "save", taggedImage, imagePath, "--alsologtostderr"))
if err != nil {
t.Fatalf("saving image from minikube to file: %v\n%s", err, rr.Output())
}
if _, err := os.Stat(imagePath); err != nil {
t.Fatalf("expected %q to exist after `image save`, but doesn't exist", imagePath)
}
})
// docs: Make sure image removal works by `minikube image rm`
t.Run("ImageRemove", func(t *testing.T) {
rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "image", "rm", taggedImage, "--alsologtostderr"))
if err != nil {
t.Fatalf("removing image from minikube: %v\n%s", err, rr.Output())
}
// make sure the image was removed
rr, err = listImages(ctx, t, profile)
if err != nil {
t.Fatalf("listing images: %v\n%s", err, rr.Output())
}
if strings.Contains(rr.Output(), taggedImage) {
t.Fatalf("expected %q to be removed from minikube but still exists", taggedImage)
}
})
// docs: Make sure image loading from file works by `minikube image load`
t.Run("ImageLoadFromFile", func(t *testing.T) {
rr, err := Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "image", "load", imagePath, "--alsologtostderr"))
if err != nil || strings.Contains(rr.Output(), "failed pushing to: functional") {
t.Fatalf("loading image into minikube from file: %v\n%s", err, rr.Output())
}
checkImageExists(ctx, t, profile, taggedImage)
})
// docs: Make sure image saving to Docker daemon works by `minikube image load`
t.Run("ImageSaveDaemon", func(t *testing.T) {
rr, err := Run(t, exec.CommandContext(ctx, "docker", "rmi", taggedImage))
if err != nil {
t.Fatalf("failed to remove image from docker: %v\n%s", err, rr.Output())
}
rr, err = Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "image", "save", "--daemon", taggedImage, "--alsologtostderr"))
if err != nil {
t.Fatalf("saving image from minikube to daemon: %v\n%s", err, rr.Output())
}
imageToDelete := taggedImage
if ContainerRuntime() == "crio" {
imageToDelete = cruntime.AddLocalhostPrefix(imageToDelete)
}
rr, err = Run(t, exec.CommandContext(ctx, "docker", "image", "inspect", imageToDelete))
if err != nil {
t.Fatalf("expected image to be loaded into Docker, but image was not found: %v\n%s", err, rr.Output())
}
})
}
func checkImageExists(ctx context.Context, t *testing.T, profile string, image string) {
// make sure the image was correctly loaded
rr, err := listImages(ctx, t, profile)
if err != nil {
t.Fatalf("listing images: %v\n%s", err, rr.Output())
}
if !strings.Contains(rr.Output(), image) {
t.Fatalf("expected %q to be loaded into minikube but the image is not there", image)
}
}
func listImages(ctx context.Context, t *testing.T, profile string) (*RunResult, error) {
return Run(t, exec.CommandContext(ctx, Target(), "-p", profile, "image", "ls"))
}
// check functionality of minikube after evaluating docker-env
func validateDockerEnv(ctx context.Context, t *testing.T, profile string) {
// docs(skip): Skips on `none` drive since `docker-env` is not supported
if NoneDriver() {
t.Skipf("none driver does not support docker-env")
}
// docs(skip): Skips on non-docker container runtime
if cr := ContainerRuntime(); cr != "docker" {
t.Skipf("only validate docker env with docker container runtime, currently testing %s", cr)
}
defer PostMortemLogs(t, profile)
type ShellTest struct {
name string
commandPrefix []string
formatArg string
}
// docs: Run `eval $(minikube docker-env)` to configure current environment to use minikube's Docker daemon
windowsTests := []ShellTest{
{"powershell", []string{"powershell.exe", "-NoProfile", "-NonInteractive"}, "%[1]s -p %[2]s docker-env | Invoke-Expression ; "},
}
posixTests := []ShellTest{
{"bash", []string{"/bin/bash", "-c"}, "eval $(%[1]s -p %[2]s docker-env) && "},
}
tests := posixTests
if runtime.GOOS == "windows" {
tests = windowsTests
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
mctx, cancel := context.WithTimeout(ctx, Seconds(120))
defer cancel()
command := make([]string, len(tc.commandPrefix)+1)
copy(command, tc.commandPrefix)
formattedArg := fmt.Sprintf(tc.formatArg, Target(), profile)
// docs: Run `minikube status` to get the minikube status
// we should be able to get minikube status with a shell which evaled docker-env
command[len(command)-1] = formattedArg + Target() + " status -p " + profile
c := exec.CommandContext(mctx, command[0], command[1:]...)
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)
}
// docs: Make sure minikube components have status `Running`
if !strings.Contains(rr.Output(), "Running") {
t.Fatalf("expected status output to include 'Running' after eval docker-env but got: *%s*", rr.Output())
}
// docs: Make sure `docker-env` has status `in-use`
if !strings.Contains(rr.Output(), "in-use") {
t.Fatalf("expected status output to include `in-use` after eval docker-env but got *%s*", rr.Output())
}
mctx, cancel = context.WithTimeout(ctx, Seconds(60))
defer cancel()
// docs: Run eval `$(minikube -p profile docker-env)` and check if we are point to docker inside minikube
command[len(command)-1] = formattedArg + "docker images"
c = exec.CommandContext(mctx, command[0], command[1:]...)
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)
}
// docs: Make sure `docker images` hits the minikube's Docker daemon by check if `gcr.io/k8s-minikube/storage-provisioner` is in the output of `docker images`
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())
}
})
}
}
// check functionality of minikube after evaluating podman-env
func validatePodmanEnv(ctx context.Context, t *testing.T, profile string) {
// docs(skip): Skips on `none` drive since `podman-env` is not supported
if NoneDriver() {
t.Skipf("none driver does not support podman-env")
}
// docs(skip): Skips on non-docker container runtime
if cr := ContainerRuntime(); cr != "podman" {
t.Skipf("only validate podman env with docker container runtime, currently testing %s", cr)
}
// docs(skip): Skips on non-Linux platforms
if runtime.GOOS != "linux" {
t.Skipf("only validate podman env on linux, currently testing %s", runtime.GOOS)
}
defer PostMortemLogs(t, profile)
mctx, cancel := context.WithTimeout(ctx, Seconds(120))
defer cancel()
// docs: Run `eval $(minikube podman-env)` to configure current environment to use minikube's Podman daemon, and `minikube status` to get the minikube status
c := exec.CommandContext(mctx, "/bin/bash", "-c", "eval $("+Target()+" -p "+profile+" podman-env) && "+Target()+" status -p "+profile)
// we should be able to get minikube status with a bash which evaluated podman-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 podman-env. error: %v", err)
}
// docs: Make sure minikube components have status `Running`
if !strings.Contains(rr.Output(), "Running") {
t.Fatalf("expected status output to include 'Running' after eval podman-env but got: *%s*", rr.Output())
}
// docs: Make sure `podman-env` has status `in-use`
if !strings.Contains(rr.Output(), "in-use") {
t.Fatalf("expected status output to include `in-use` after eval podman-env but got *%s*", rr.Output())
}
mctx, cancel = context.WithTimeout(ctx, Seconds(60))
defer cancel()
// docs: Run `eval $(minikube docker-env)` again and `docker images` to list the docker images using the minikube's Docker daemon
c = exec.CommandContext(mctx, "/bin/bash", "-c", "eval $("+Target()+" -p "+profile+" podman-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 podman-env. args %q : %v ", rr.Command(), err)
}
// docs: Make sure `docker images` hits the minikube's Podman daemon by check if `gcr.io/k8s-minikube/storage-provisioner` is in the output of `docker images`
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())
}
}
// validateStartWithProxy makes sure minikube start respects the HTTP_PROXY environment variable
func validateStartWithProxy(ctx context.Context, t *testing.T, profile string) {
defer PostMortemLogs(t, profile)
// docs: Start a local HTTP proxy
srv, err := startHTTPProxy(t)
if err != nil {
t.Fatalf("failed to set up the test proxy: %s", err)
}
// docs: Start minikube with the environment variable `HTTP_PROXY` set to the local HTTP proxy
startMinikubeWithProxy(ctx, t, profile, "HTTP_PROXY", srv.Addr)
}
// validateStartWithCustomCerts makes sure minikube start respects the HTTPS_PROXY environment variable and works with custom certs
// a proxy is started by calling the mitmdump binary in the background, then installing the certs generated by the binary
// mitmproxy/dump creates the proxy at localhost at port 8080
// only runs on GitHub Actions for amd64 linux, otherwise validateStartWithProxy runs instead
func validateStartWithCustomCerts(ctx context.Context, t *testing.T, profile string) {
defer PostMortemLogs(t, profile)
err := startProxyWithCustomCerts(ctx, t)
if err != nil {
t.Fatalf("failed to set up the test proxy: %s", err)
}
startMinikubeWithProxy(ctx, t, profile, "HTTPS_PROXY", "127.0.0.1:8080")
}
// validateAuditAfterStart makes sure the audit log contains the correct logging after minikube start
func validateAuditAfterStart(_ context.Context, t *testing.T, profile string) {
// docs: Read the audit log file and make sure it contains the current minikube profile name
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()
// docs: The test `validateStartWithProxy` should have start minikube, make sure the configured node port is `8441`
beforeCfg, err := config.LoadProfile(profile)
if err != nil {
t.Fatalf("error reading cluster config before soft start: %v", err)
}
if beforeCfg.Config.APIServerPort != apiPortTest {
t.Errorf("expected cluster config node port before soft start to be %d but got %d", apiPortTest, beforeCfg.Config.APIServerPort)
}
// docs: Run `minikube start` again as a soft start
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)
// docs: Make sure the configured node port is not changed
afterCfg, err := config.LoadProfile(profile)
if err != nil {
t.Errorf("error reading cluster config after soft start: %v", err)
}
if afterCfg.Config.APIServerPort != apiPortTest {
t.Errorf("expected node port in the config not to change after soft start. expected node port to be %d but got %d.", apiPortTest, afterCfg.Config.APIServerPort)
}
}
// validateKubeContext asserts that kubectl is properly configured (race-condition prone!)
func validateKubeContext(ctx context.Context, t *testing.T, profile string) {
defer PostMortemLogs(t, profile)
// docs: Run `kubectl config current-context`
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)
}
// docs: Make sure the current minikube profile name is in the output of the command
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)
// docs: Run `kubectl get po -A` to get all pods in the current minikube 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)
}
// docs: Make sure the output is not empty and contains `kube-system` components
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)
// docs: Run `minikube kubectl -- get pods` to get the pods in the current minikube 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...))
// docs: Make sure the command doesn't raise any error
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())
newName := "kubectl"
if runtime.GOOS == "windows" {
newName += ".exe"
}
dstfn := filepath.Join(dir, newName)
err := os.Link(Target(), dstfn)
if err != nil {
t.Fatal(err)
}
defer os.Remove(dstfn) // clean up
// docs: Run `kubectl get pods` by calling the minikube's `kubectl` binary file directly
kubectlArgs := []string{"--context", profile, "get", "pods"}
rr, err := Run(t, exec.CommandContext(ctx, dstfn, kubectlArgs...))
// docs: Make sure the command doesn't raise any error
if err != nil {
t.Fatalf("failed to run kubectl directly. args %q: %v", rr.Command(), err)
}
}
// validateExtraConfig verifies minikube with --extra-config works as expected
func validateExtraConfig(ctx context.Context, t *testing.T, profile string) {
defer PostMortemLogs(t, profile)
start := time.Now()
// docs: The tests before this already created a profile
// docs: Soft-start minikube with different `--extra-config` command line 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)
// docs: Load the profile's config
afterCfg, err := config.LoadProfile(profile)
if err != nil {
t.Errorf("error reading cluster config after soft start: %v", err)
}
// docs: Make sure the specified `--extra-config` is correctly returned
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
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,
}
// docs: Run `kubectl get po po -l tier=control-plane -n kube-system -o=json` to get all the Kubernetes conponents
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)
}
// docs: For each component, make sure the pod status is `Running`
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)
}
}
}
// validateStatusCmd makes sure `minikube status` outputs correctly
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)
}
// docs: Run `minikube status` with custom format `host:{{.Host}},kublet:{{.Kubelet}},apiserver:{{.APIServer}},kubeconfig:{{.Kubeconfig}}`
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)
}
// docs: Make sure `host`, `kublete`, `apiserver` and `kubeconfig` statuses are shown in the output
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())
}
// docs: Run `minikube status` again as 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)
}
// docs: Make sure `host`, `kublete`, `apiserver` and `kubeconfig` statuses are set in the JSON output
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()
// docs: Run `minikube dashboard --url` to start minikube dashboard and return the URL of it
args := []string{"dashboard", "--url", "--port", "36195", "-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)
}
// docs: Send a GET request to the dashboard URL
resp, err := retryablehttp.Get(u.String())
if err != nil {
t.Fatalf("failed to http get %q: %v\nresponse: %+v", u.String(), err, resp)
}
// docs: Make sure HTTP status OK is returned
if resp.StatusCode != http.StatusOK {
body, err := io.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) expect Docker Windows
timeout := Seconds(5)
if runtime.GOOS == "windows" && DockerDriver() {
timeout = Seconds(10)
}
mctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// docs: Run `minikube start --dry-run --memory 250MB`
// 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)
// docs: Since the 250MB memory is less than the required 2GB, minikube should exit with an exit code `ExInsufficientMemory`
wantCode := reason.ExInsufficientMemory
if rr.ExitCode != wantCode {
if HyperVDriver() {
t.Skip("skipping this error on HyperV till this issue is solved https://github.com/kubernetes/minikube/issues/9785")
} else {
t.Errorf("dry-run(250MB) exit code = %d, wanted = %d: %v", rr.ExitCode, wantCode, err)
}
}
dctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// docs: Run `minikube start --dry-run`
startArgs = append([]string{"start", "-p", profile, "--dry-run", "--alsologtostderr", "-v=1"}, StartArgs()...)
c = exec.CommandContext(dctx, Target(), startArgs...)
rr, err = Run(t, c)
// docs: Make sure the command doesn't raise any error
if rr.ExitCode != 0 || err != nil {
if HyperVDriver() {
t.Skip("skipping this error on HyperV till this issue is solved https://github.com/kubernetes/minikube/issues/9785")
} else {
t.Errorf("dry-run exit code = %d, wanted = %d: %v", rr.ExitCode, 0, err)
}
}