-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathintegration_test.go
1156 lines (991 loc) · 35.2 KB
/
integration_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
/*
Copyright 2018 Google LLC
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 (
"archive/tar"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"math"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"testing"
"time"
"github.com/google/go-containerregistry/pkg/name"
"github.com/google/go-containerregistry/pkg/v1/daemon"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/pkg/errors"
"google.golang.org/api/option"
"github.com/GoogleContainerTools/kaniko/pkg/timing"
"github.com/GoogleContainerTools/kaniko/pkg/util"
"github.com/GoogleContainerTools/kaniko/pkg/util/bucket"
"github.com/GoogleContainerTools/kaniko/testutil"
)
var (
config *integrationTestConfig
imageBuilder *DockerFileBuilder
allDockerfiles []string
)
const (
daemonPrefix = "daemon://"
integrationPath = "integration"
dockerfilesPath = "dockerfiles"
emptyContainerDiff = `[
{
"Image1": "%s",
"Image2": "%s",
"DiffType": "File",
"Diff": {
"Adds": null,
"Dels": null,
"Mods": null
}
},
{
"Image1": "%s",
"Image2": "%s",
"DiffType": "Metadata",
"Diff": {
"Adds": [],
"Dels": []
}
}
]`
)
func getDockerMajorVersion() int {
out, err := exec.Command("docker", "version", "--format", "{{.Server.Version}}").Output()
if err != nil {
log.Fatal("Error getting docker version of server:", err)
}
versionArr := strings.Split(string(out), ".")
ver, err := strconv.Atoi(versionArr[0])
if err != nil {
log.Fatal("Error getting docker version of server during parsing version string:", err)
}
return ver
}
func launchTests(m *testing.M) (int, error) {
if config.isGcrRepository() {
contextFilePath, err := CreateIntegrationTarball()
if err != nil {
return 1, errors.Wrap(err, "Failed to create tarball of integration files for build context")
}
bucketName, item, err := bucket.GetNameAndFilepathFromURI(config.gcsBucket)
if err != nil {
return 1, errors.Wrap(err, "failed to get bucket name from uri")
}
contextFile, err := os.Open(contextFilePath)
if err != nil {
return 1, fmt.Errorf("failed to read file at path %v: %w", contextFilePath, err)
}
err = bucket.Upload(context.Background(), bucketName, item, contextFile, config.gcsClient)
if err != nil {
return 1, errors.Wrap(err, "Failed to upload build context")
}
if err = os.Remove(contextFilePath); err != nil {
return 1, errors.Wrap(err, fmt.Sprintf("Failed to remove tarball at %s", contextFilePath))
}
deleteFunc := func() {
bucket.Delete(context.Background(), bucketName, item, config.gcsClient)
}
RunOnInterrupt(deleteFunc)
defer deleteFunc()
}
if err := buildRequiredImages(); err != nil {
return 1, errors.Wrap(err, "Error while building images")
}
imageBuilder = NewDockerFileBuilder()
return m.Run(), nil
}
func TestMain(m *testing.M) {
var err error
if !meetsRequirements() {
fmt.Println("Missing required tools")
os.Exit(1)
}
config = initIntegrationTestConfig()
if allDockerfiles, err = FindDockerFiles(dockerfilesPath, config.dockerfilesPattern); err != nil {
fmt.Println("Coudn't create map of dockerfiles", err)
os.Exit(1)
}
exitCode, err := launchTests(m)
if err != nil {
fmt.Println(err)
}
os.Exit(exitCode)
}
func buildRequiredImages() error {
setupCommands := []struct {
name string
command []string
}{{
name: "Building kaniko image",
command: []string{"docker", "build", "-t", ExecutorImage, "-f", "../deploy/Dockerfile", "--target", "kaniko-executor", ".."},
}, {
name: "Building cache warmer image",
command: []string{"docker", "build", "-t", WarmerImage, "-f", "../deploy/Dockerfile", "--target", "kaniko-warmer", ".."},
}, {
name: "Building onbuild base image",
command: []string{"docker", "build", "-t", config.onbuildBaseImage, "-f", fmt.Sprintf("%s/Dockerfile_onbuild_base", dockerfilesPath), "."},
}, {
name: "Pushing onbuild base image",
command: []string{"docker", "push", config.onbuildBaseImage},
}, {
name: "Building hardlink base image",
command: []string{"docker", "build", "-t", config.hardlinkBaseImage, "-f", fmt.Sprintf("%s/Dockerfile_hardlink_base", dockerfilesPath), "."},
}, {
name: "Pushing hardlink base image",
command: []string{"docker", "push", config.hardlinkBaseImage},
}}
for _, setupCmd := range setupCommands {
fmt.Println(setupCmd.name)
cmd := exec.Command(setupCmd.command[0], setupCmd.command[1:]...)
cmd.Env = append(os.Environ(), "DOCKER_BUILDKIT=1") // Build with buildkit enabled.
if out, err := RunCommandWithoutTest(cmd); err != nil {
return errors.Wrap(err, fmt.Sprintf("%s failed: %s", setupCmd.name, string(out)))
}
}
return nil
}
func TestRun(t *testing.T) {
for _, dockerfile := range allDockerfiles {
t.Run("test_"+dockerfile, func(t *testing.T) {
dockerfile := dockerfile
t.Parallel()
if _, ok := imageBuilder.DockerfilesToIgnore[dockerfile]; ok {
t.SkipNow()
}
if _, ok := imageBuilder.TestCacheDockerfiles[dockerfile]; ok {
t.SkipNow()
}
buildImage(t, dockerfile, imageBuilder)
dockerImage := GetDockerImage(config.imageRepo, dockerfile)
kanikoImage := GetKanikoImage(config.imageRepo, dockerfile)
diff := containerDiff(t, daemonPrefix+dockerImage, kanikoImage, "--no-cache")
expected := fmt.Sprintf(emptyContainerDiff, dockerImage, kanikoImage, dockerImage, kanikoImage)
checkContainerDiffOutput(t, diff, expected)
})
}
err := logBenchmarks("benchmark")
if err != nil {
t.Logf("Failed to create benchmark file: %v", err)
}
}
func getBranchCommitAndURL() (branch, commit, url string) {
repo := os.Getenv("GITHUB_REPOSITORY")
commit = os.Getenv("GITHUB_SHA")
if _, isPR := os.LookupEnv("GITHUB_HEAD_REF"); isPR {
branch = "main"
} else {
branch = os.Getenv("GITHUB_REF")
log.Printf("GITHUB_HEAD_REF is unset (not a PR); using GITHUB_REF=%q", branch)
branch = strings.TrimPrefix(branch, "refs/heads/")
}
if repo == "" {
repo = "GoogleContainerTools/kaniko"
}
if branch == "" {
branch = "main"
}
log.Printf("repo=%q / commit=%q / branch=%q", repo, commit, branch)
url = "github.com/" + repo
return
}
func getGitRepo(explicit bool) string {
branch, commit, url := getBranchCommitAndURL()
if explicit && commit != "" {
return url + "#" + commit
}
return url + "#refs/heads/" + branch
}
func testGitBuildcontextHelper(t *testing.T, repo string) {
t.Log("testGitBuildcontextHelper repo", repo)
dockerfile := fmt.Sprintf("%s/%s/Dockerfile_test_run_2", integrationPath, dockerfilesPath)
// Build with docker
dockerImage := GetDockerImage(config.imageRepo, "Dockerfile_test_git")
dockerCmd := exec.Command("docker",
append([]string{
"build",
"-t", dockerImage,
"-f", dockerfile,
repo,
})...)
out, err := RunCommandWithoutTest(dockerCmd)
if err != nil {
t.Errorf("Failed to build image %s with docker command %q: %s %s", dockerImage, dockerCmd.Args, err, string(out))
}
// Build with kaniko
kanikoImage := GetKanikoImage(config.imageRepo, "Dockerfile_test_git")
dockerRunFlags := []string{"run", "--net=host"}
dockerRunFlags = addServiceAccountFlags(dockerRunFlags, config.serviceAccount)
dockerRunFlags = append(dockerRunFlags, ExecutorImage,
"-f", dockerfile,
"-d", kanikoImage,
"-c", fmt.Sprintf("git://%s", repo))
kanikoCmd := exec.Command("docker", dockerRunFlags...)
out, err = RunCommandWithoutTest(kanikoCmd)
if err != nil {
t.Errorf("Failed to build image %s with kaniko command %q: %v %s", dockerImage, kanikoCmd.Args, err, string(out))
}
diff := containerDiff(t, daemonPrefix+dockerImage, kanikoImage, "--no-cache")
expected := fmt.Sprintf(emptyContainerDiff, dockerImage, kanikoImage, dockerImage, kanikoImage)
checkContainerDiffOutput(t, diff, expected)
}
// TestGitBuildcontext explicitly names the main branch
// Example:
//
// git://github.com/myuser/repo#refs/heads/main
func TestGitBuildcontext(t *testing.T) {
repo := getGitRepo(false)
testGitBuildcontextHelper(t, repo)
}
// TestGitBuildcontextNoRef builds without any commit / branch reference
// Example:
//
// git://github.com/myuser/repo
func TestGitBuildcontextNoRef(t *testing.T) {
t.Skip("Docker's behavior is to assume a 'master' branch, which the Kaniko repo doesn't have")
_, _, url := getBranchCommitAndURL()
testGitBuildcontextHelper(t, url)
}
// TestGitBuildcontextExplicitCommit uses an explicit commit hash instead of named reference
// Example:
//
// git://github.com/myuser/repo#b873088c4a7b60bb7e216289c58da945d0d771b6
func TestGitBuildcontextExplicitCommit(t *testing.T) {
repo := getGitRepo(true)
testGitBuildcontextHelper(t, repo)
}
func TestGitBuildcontextSubPath(t *testing.T) {
repo := getGitRepo(false)
dockerfile := "Dockerfile_test_run_2"
// Build with docker
dockerImage := GetDockerImage(config.imageRepo, "Dockerfile_test_git")
dockerCmd := exec.Command("docker",
append([]string{
"build",
"-t", dockerImage,
"-f", filepath.Join(integrationPath, dockerfilesPath, dockerfile),
repo,
})...)
out, err := RunCommandWithoutTest(dockerCmd)
if err != nil {
t.Errorf("Failed to build image %s with docker command %q: %s %s", dockerImage, dockerCmd.Args, err, string(out))
}
// Build with kaniko
kanikoImage := GetKanikoImage(config.imageRepo, "Dockerfile_test_git")
dockerRunFlags := []string{"run", "--net=host"}
dockerRunFlags = addServiceAccountFlags(dockerRunFlags, config.serviceAccount)
dockerRunFlags = append(
dockerRunFlags,
ExecutorImage,
"-f", dockerfile,
"-d", kanikoImage,
"-c", fmt.Sprintf("git://%s", repo),
"--context-sub-path", filepath.Join(integrationPath, dockerfilesPath),
)
kanikoCmd := exec.Command("docker", dockerRunFlags...)
out, err = RunCommandWithoutTest(kanikoCmd)
if err != nil {
t.Errorf("Failed to build image %s with kaniko command %q: %v %s", dockerImage, kanikoCmd.Args, err, string(out))
}
diff := containerDiff(t, daemonPrefix+dockerImage, kanikoImage, "--no-cache")
expected := fmt.Sprintf(emptyContainerDiff, dockerImage, kanikoImage, dockerImage, kanikoImage)
checkContainerDiffOutput(t, diff, expected)
}
func TestBuildViaRegistryMirrors(t *testing.T) {
repo := getGitRepo(false)
dockerfile := fmt.Sprintf("%s/%s/Dockerfile_registry_mirror", integrationPath, dockerfilesPath)
// Build with docker
dockerImage := GetDockerImage(config.imageRepo, "Dockerfile_registry_mirror")
dockerCmd := exec.Command("docker",
append([]string{
"build",
"-t", dockerImage,
"-f", dockerfile,
repo,
})...)
out, err := RunCommandWithoutTest(dockerCmd)
if err != nil {
t.Errorf("Failed to build image %s with docker command %q: %s %s", dockerImage, dockerCmd.Args, err, string(out))
}
// Build with kaniko
kanikoImage := GetKanikoImage(config.imageRepo, "Dockerfile_registry_mirror")
dockerRunFlags := []string{"run", "--net=host"}
dockerRunFlags = addServiceAccountFlags(dockerRunFlags, config.serviceAccount)
dockerRunFlags = append(dockerRunFlags, ExecutorImage,
"-f", dockerfile,
"-d", kanikoImage,
"--registry-mirror", "doesnotexist.example.com",
"--registry-mirror", "us-mirror.gcr.io",
"-c", fmt.Sprintf("git://%s", repo))
kanikoCmd := exec.Command("docker", dockerRunFlags...)
out, err = RunCommandWithoutTest(kanikoCmd)
if err != nil {
t.Errorf("Failed to build image %s with kaniko command %q: %v %s", dockerImage, kanikoCmd.Args, err, string(out))
}
diff := containerDiff(t, daemonPrefix+dockerImage, kanikoImage, "--no-cache")
expected := fmt.Sprintf(emptyContainerDiff, dockerImage, kanikoImage, dockerImage, kanikoImage)
checkContainerDiffOutput(t, diff, expected)
}
func TestBuildViaRegistryMap(t *testing.T) {
repo := getGitRepo(false)
dockerfile := fmt.Sprintf("%s/%s/Dockerfile_registry_mirror", integrationPath, dockerfilesPath)
// Build with docker
dockerImage := GetDockerImage(config.imageRepo, "Dockerfile_registry_mirror")
dockerCmd := exec.Command("docker",
append([]string{
"build",
"-t", dockerImage,
"-f", dockerfile,
repo,
})...)
out, err := RunCommandWithoutTest(dockerCmd)
if err != nil {
t.Errorf("Failed to build image %s with docker command %q: %s %s", dockerImage, dockerCmd.Args, err, string(out))
}
// Build with kaniko
kanikoImage := GetKanikoImage(config.imageRepo, "Dockerfile_registry_mirror")
dockerRunFlags := []string{"run", "--net=host"}
dockerRunFlags = addServiceAccountFlags(dockerRunFlags, config.serviceAccount)
dockerRunFlags = append(dockerRunFlags, ExecutorImage,
"-f", dockerfile,
"-d", kanikoImage,
"--registry-map", "index.docker.io=doesnotexist.example.com",
"--registry-map", "index.docker.io=us-mirror.gcr.io",
"-c", fmt.Sprintf("git://%s", repo))
kanikoCmd := exec.Command("docker", dockerRunFlags...)
out, err = RunCommandWithoutTest(kanikoCmd)
if err != nil {
t.Errorf("Failed to build image %s with kaniko command %q: %v %s", dockerImage, kanikoCmd.Args, err, string(out))
}
diff := containerDiff(t, daemonPrefix+dockerImage, kanikoImage, "--no-cache")
expected := fmt.Sprintf(emptyContainerDiff, dockerImage, kanikoImage, dockerImage, kanikoImage)
checkContainerDiffOutput(t, diff, expected)
}
func TestBuildSkipFallback(t *testing.T) {
repo := getGitRepo(false)
dockerfile := fmt.Sprintf("%s/%s/Dockerfile_registry_mirror", integrationPath, dockerfilesPath)
// Build with kaniko
kanikoImage := GetKanikoImage(config.imageRepo, "Dockerfile_registry_mirror")
dockerRunFlags := []string{"run", "--net=host"}
dockerRunFlags = addServiceAccountFlags(dockerRunFlags, config.serviceAccount)
dockerRunFlags = append(dockerRunFlags, ExecutorImage,
"-f", dockerfile,
"-d", kanikoImage,
"--registry-mirror", "doesnotexist.example.com",
"--skip-default-registry-fallback",
"-c", fmt.Sprintf("git://%s", repo))
kanikoCmd := exec.Command("docker", dockerRunFlags...)
_, err := RunCommandWithoutTest(kanikoCmd)
if err == nil {
t.Errorf("Build should fail after using skip-default-registry-fallback and registry-mirror fail to pull")
}
}
// TestKanikoDir tests that a build that sets --kaniko-dir produces the same output as the equivalent docker build.
func TestKanikoDir(t *testing.T) {
repo := getGitRepo(false)
dockerfile := fmt.Sprintf("%s/%s/Dockerfile_registry_mirror", integrationPath, dockerfilesPath)
// Build with docker
dockerImage := GetDockerImage(config.imageRepo, "Dockerfile_registry_mirror")
dockerCmd := exec.Command("docker",
append([]string{
"build",
"-t", dockerImage,
"-f", dockerfile,
repo,
})...)
out, err := RunCommandWithoutTest(dockerCmd)
if err != nil {
t.Errorf("Failed to build image %s with docker command %q: %s %s", dockerImage, dockerCmd.Args, err, string(out))
}
// Build with kaniko
kanikoImage := GetKanikoImage(config.imageRepo, "Dockerfile_registry_mirror")
dockerRunFlags := []string{"run", "--net=host"}
dockerRunFlags = addServiceAccountFlags(dockerRunFlags, config.serviceAccount)
dockerRunFlags = append(dockerRunFlags, ExecutorImage,
"-f", dockerfile,
"-d", kanikoImage,
"--kaniko-dir", "/not-kaniko",
"-c", fmt.Sprintf("git://%s", repo))
kanikoCmd := exec.Command("docker", dockerRunFlags...)
out, err = RunCommandWithoutTest(kanikoCmd)
if err != nil {
t.Errorf("Failed to build image %s with kaniko command %q: %v %s", dockerImage, kanikoCmd.Args, err, string(out))
}
diff := containerDiff(t, daemonPrefix+dockerImage, kanikoImage, "--no-cache")
expected := fmt.Sprintf(emptyContainerDiff, dockerImage, kanikoImage, dockerImage, kanikoImage)
checkContainerDiffOutput(t, diff, expected)
}
func TestBuildWithLabels(t *testing.T) {
repo := getGitRepo(false)
dockerfile := fmt.Sprintf("%s/%s/Dockerfile_test_label", integrationPath, dockerfilesPath)
testLabel := "mylabel=myvalue"
// Build with docker
dockerImage := GetDockerImage(config.imageRepo, "Dockerfile_test_label:mylabel")
dockerCmd := exec.Command("docker",
append([]string{
"build",
"-t", dockerImage,
"-f", dockerfile,
"--label", testLabel,
repo,
})...)
out, err := RunCommandWithoutTest(dockerCmd)
if err != nil {
t.Errorf("Failed to build image %s with docker command %q: %s %s", dockerImage, dockerCmd.Args, err, string(out))
}
// Build with kaniko
kanikoImage := GetKanikoImage(config.imageRepo, "Dockerfile_test_label:mylabel")
dockerRunFlags := []string{"run", "--net=host"}
dockerRunFlags = addServiceAccountFlags(dockerRunFlags, config.serviceAccount)
dockerRunFlags = append(dockerRunFlags, ExecutorImage,
"-f", dockerfile,
"-d", kanikoImage,
"--label", testLabel,
"-c", fmt.Sprintf("git://%s", repo),
)
kanikoCmd := exec.Command("docker", dockerRunFlags...)
out, err = RunCommandWithoutTest(kanikoCmd)
if err != nil {
t.Errorf("Failed to build image %s with kaniko command %q: %v %s", dockerImage, kanikoCmd.Args, err, string(out))
}
diff := containerDiff(t, daemonPrefix+dockerImage, kanikoImage, "--no-cache")
expected := fmt.Sprintf(emptyContainerDiff, dockerImage, kanikoImage, dockerImage, kanikoImage)
checkContainerDiffOutput(t, diff, expected)
}
func TestBuildWithHTTPError(t *testing.T) {
repo := getGitRepo(false)
dockerfile := fmt.Sprintf("%s/%s/Dockerfile_test_add_404", integrationPath, dockerfilesPath)
// Build with docker
dockerImage := GetDockerImage(config.imageRepo, "Dockerfile_test_add_404")
dockerCmd := exec.Command("docker",
append([]string{
"build",
"-t", dockerImage,
"-f", dockerfile,
repo,
})...)
out, err := RunCommandWithoutTest(dockerCmd)
if err == nil {
t.Errorf("an error was expected, got %s", string(out))
}
// Build with kaniko
kanikoImage := GetKanikoImage(config.imageRepo, "Dockerfile_test_add_404")
dockerRunFlags := []string{"run", "--net=host"}
dockerRunFlags = addServiceAccountFlags(dockerRunFlags, config.serviceAccount)
dockerRunFlags = append(dockerRunFlags, ExecutorImage,
"-f", dockerfile,
"-d", kanikoImage,
"-c", fmt.Sprintf("git://%s", repo),
)
kanikoCmd := exec.Command("docker", dockerRunFlags...)
out, err = RunCommandWithoutTest(kanikoCmd)
if err == nil {
t.Errorf("an error was expected, got %s", string(out))
}
}
func TestLayers(t *testing.T) {
offset := map[string]int{
"Dockerfile_test_add": 12,
"Dockerfile_test_scratch": 3,
}
if os.Getenv("CI") == "true" {
// TODO: tejaldesai fix this!
// This files build locally with difference 0, on CI docker
// produces a different amount of layers (?).
offset["Dockerfile_test_copy_same_file_many_times"] = 47
offset["Dockerfile_test_meta_arg"] = 1
offset["Dockerfile_test_copyadd_chmod"] = 6
}
for _, dockerfile := range allDockerfiles {
t.Run("test_layer_"+dockerfile, func(t *testing.T) {
dockerfileTest := dockerfile
t.Parallel()
if _, ok := imageBuilder.DockerfilesToIgnore[dockerfileTest]; ok {
t.SkipNow()
}
buildImage(t, dockerfileTest, imageBuilder)
// Pull the kaniko image
dockerImage := GetDockerImage(config.imageRepo, dockerfileTest)
kanikoImage := GetKanikoImage(config.imageRepo, dockerfileTest)
pullCmd := exec.Command("docker", "pull", kanikoImage)
RunCommand(pullCmd, t)
checkLayers(t, dockerImage, kanikoImage, offset[dockerfileTest])
})
}
err := logBenchmarks("benchmark_layers")
if err != nil {
t.Logf("Failed to create benchmark file: %v", err)
}
}
func TestReplaceFolderWithFileOrLink(t *testing.T) {
dockerfiles := []string{"TestReplaceFolderWithFile", "TestReplaceFolderWithLink"}
for _, dockerfile := range dockerfiles {
t.Run(dockerfile, func(t *testing.T) {
buildImage(t, dockerfile, imageBuilder)
kanikoImage := GetKanikoImage(config.imageRepo, dockerfile)
kanikoFiles, err := getLastLayerFiles(kanikoImage)
if err != nil {
t.Fatal(err)
}
fmt.Println(kanikoFiles)
for _, file := range kanikoFiles {
if strings.HasPrefix(file, "a/.wh.") {
t.Errorf("Last layer should not add whiteout files to deleted directory but found %s", file)
}
}
})
}
}
func buildImage(t *testing.T, dockerfile string, imageBuilder *DockerFileBuilder) {
t.Logf("Building image '%v'...", dockerfile)
if err := imageBuilder.BuildImage(t, config, dockerfilesPath, dockerfile); err != nil {
t.Errorf("Error building image: %s", err)
t.FailNow()
}
return
}
// Build each image with kaniko twice, and then make sure they're exactly the same
func TestCache(t *testing.T) {
populateVolumeCache()
// Build dockerfiles with registry cache
for dockerfile := range imageBuilder.TestCacheDockerfiles {
t.Run("test_cache_"+dockerfile, func(t *testing.T) {
dockerfile := dockerfile
cache := filepath.Join(config.imageRepo, "cache", fmt.Sprintf("%v", time.Now().UnixNano()))
t.Parallel()
verifyBuildWith(t, cache, dockerfile)
})
}
// Build dockerfiles with layout cache
for dockerfile := range imageBuilder.TestOCICacheDockerfiles {
t.Run("test_oci_cache_"+dockerfile, func(t *testing.T) {
dockerfile := dockerfile
cache := filepath.Join("oci:", cacheDir, "cached", fmt.Sprintf("%v", time.Now().UnixNano()))
t.Parallel()
verifyBuildWith(t, cache, dockerfile)
})
}
if err := logBenchmarks("benchmark_cache"); err != nil {
t.Logf("Failed to create benchmark file: %v", err)
}
}
// Attempt to warm an image two times : first time should populate the cache, second time should find the image in the cache.
func TestWarmerTwice(t *testing.T) {
_, ex, _, _ := runtime.Caller(0)
cwd := filepath.Dir(ex) + "/tmpCache"
// Start a sleeping warmer container
dockerRunFlags := []string{"run", "--net=host"}
dockerRunFlags = addServiceAccountFlags(dockerRunFlags, config.serviceAccount)
dockerRunFlags = append(dockerRunFlags,
"--memory=16m",
"-v", cwd+":/cache",
WarmerImage,
"--cache-dir=/cache",
"-i", "debian:trixie-slim")
warmCmd := exec.Command("docker", dockerRunFlags...)
out, err := RunCommandWithoutTest(warmCmd)
if err != nil {
t.Fatalf("Unable to perform first warming: %s", err)
}
t.Logf("First warm output: %s", out)
warmCmd = exec.Command("docker", dockerRunFlags...)
out, err = RunCommandWithoutTest(warmCmd)
if err != nil {
t.Fatalf("Unable to perform second warming: %s", err)
}
t.Logf("Second warm output: %s", out)
}
func verifyBuildWith(t *testing.T, cache, dockerfile string) {
args := []string{}
if strings.HasPrefix(dockerfile, "Dockerfile_test_cache_copy") {
args = append(args, "--cache-copy-layers=true")
}
// Build the initial image which will cache layers
if err := imageBuilder.buildCachedImage(config, cache, dockerfilesPath, dockerfile, 0, args); err != nil {
t.Fatalf("error building cached image for the first time: %v", err)
}
// Build the second image which should pull from the cache
if err := imageBuilder.buildCachedImage(config, cache, dockerfilesPath, dockerfile, 1, args); err != nil {
t.Fatalf("error building cached image for the second time: %v", err)
}
// Make sure both images are the same
kanikoVersion0 := GetVersionedKanikoImage(config.imageRepo, dockerfile, 0)
kanikoVersion1 := GetVersionedKanikoImage(config.imageRepo, dockerfile, 1)
diff := containerDiff(t, kanikoVersion0, kanikoVersion1)
expected := fmt.Sprintf(emptyContainerDiff, kanikoVersion0, kanikoVersion1, kanikoVersion0, kanikoVersion1)
checkContainerDiffOutput(t, diff, expected)
}
func TestRelativePaths(t *testing.T) {
dockerfile := "Dockerfile_relative_copy"
t.Run("test_relative_"+dockerfile, func(t *testing.T) {
t.Parallel()
dockerfile = filepath.Join("./dockerfiles", dockerfile)
contextPath := "./context"
err := imageBuilder.buildRelativePathsImage(
config.imageRepo,
dockerfile,
config.serviceAccount,
contextPath,
)
if err != nil {
t.Fatal(err)
}
dockerImage := GetDockerImage(config.imageRepo, "test_relative_"+dockerfile)
kanikoImage := GetKanikoImage(config.imageRepo, "test_relative_"+dockerfile)
diff := containerDiff(t, daemonPrefix+dockerImage, kanikoImage, "--no-cache")
expected := fmt.Sprintf(emptyContainerDiff, dockerImage, kanikoImage, dockerImage, kanikoImage)
checkContainerDiffOutput(t, diff, expected)
})
}
func TestExitCodePropagation(t *testing.T) {
currentDir, err := os.Getwd()
if err != nil {
t.Fatal("Could not get working dir")
}
context := fmt.Sprintf("%s/testdata/exit-code-propagation", currentDir)
dockerfile := fmt.Sprintf("%s/Dockerfile_exit_code_propagation", context)
t.Run("test error code propagation", func(t *testing.T) {
// building the image with docker should fail with exit code 42
dockerImage := GetDockerImage(config.imageRepo, "Dockerfile_exit_code_propagation")
dockerFlags := []string{
"build",
"-t", dockerImage,
"-f", dockerfile,
}
dockerCmd := exec.Command("docker", append(dockerFlags, context)...)
out, kanikoErr := RunCommandWithoutTest(dockerCmd)
if kanikoErr == nil {
t.Fatalf("docker build did not produce an error:\n%s", out)
}
var dockerCmdExitErr *exec.ExitError
var dockerExitCode int
if errors.As(kanikoErr, &dockerCmdExitErr) {
dockerExitCode = dockerCmdExitErr.ExitCode()
testutil.CheckDeepEqual(t, 42, dockerExitCode)
if t.Failed() {
t.Fatalf("Output was:\n%s", out)
}
} else {
t.Fatalf("did not produce the expected error:\n%s", out)
}
// try to build the same image with kaniko the error code should match with the one from the plain docker build
contextVolume := fmt.Sprintf("%s:/workspace", context)
dockerFlags = []string{
"run",
"-v", contextVolume,
}
dockerFlags = addServiceAccountFlags(dockerFlags, "")
dockerFlags = append(dockerFlags, ExecutorImage,
"-c", "dir:///workspace/",
"-f", "./Dockerfile_exit_code_propagation",
"--no-push",
"--force", // TODO: detection of whether kaniko is being run inside a container might be broken?
)
dockerCmdWithKaniko := exec.Command("docker", dockerFlags...)
out, kanikoErr = RunCommandWithoutTest(dockerCmdWithKaniko)
if kanikoErr == nil {
t.Fatalf("the kaniko build did not produce the expected error:\n%s", out)
}
var kanikoExitErr *exec.ExitError
if errors.As(kanikoErr, &kanikoExitErr) {
testutil.CheckDeepEqual(t, dockerExitCode, kanikoExitErr.ExitCode())
if t.Failed() {
t.Fatalf("Output was:\n%s", out)
}
} else {
t.Fatalf("did not produce the expected error:\n%s", out)
}
})
}
type fileDiff struct {
Name string `json:"Name"`
Size int `json:"Size"`
}
type fileDiffResult struct {
Adds []fileDiff `json:"Adds"`
Dels []fileDiff `json:"Dels"`
}
type metaDiffResult struct {
Adds []string `json:"Adds"`
Dels []string `json:"Dels"`
}
type diffOutput struct {
Image1 string
Image2 string
DiffType string
Diff interface{}
}
func (diff *diffOutput) UnmarshalJSON(data []byte) error {
type Alias diffOutput
aux := &struct{ *Alias }{Alias: (*Alias)(diff)}
var rawJSON json.RawMessage
aux.Diff = &rawJSON
err := json.Unmarshal(data, &aux)
if err != nil {
return err
}
switch diff.DiffType {
case "File":
var dst fileDiffResult
err = json.Unmarshal(rawJSON, &dst)
diff.Diff = &dst
case "Metadata":
var dst metaDiffResult
err = json.Unmarshal(rawJSON, &dst)
diff.Diff = &dst
}
if err != nil {
return err
}
return err
}
var allowedDiffPaths = []string{"/sys"}
func checkContainerDiffOutput(t *testing.T, diff []byte, expected string) {
// Let's compare the json objects themselves instead of strings to avoid
// issues with spaces and indents
t.Helper()
diffInt := []diffOutput{}
expectedInt := []diffOutput{}
err := json.Unmarshal(diff, &diffInt)
if err != nil {
t.Error(err)
}
err = json.Unmarshal([]byte(expected), &expectedInt)
if err != nil {
t.Error(err)
}
// Some differences (ignored paths, etc.) are known and expected.
fdr := diffInt[0].Diff.(*fileDiffResult)
fdr.Adds = filterFileDiff(fdr.Adds)
fdr.Dels = filterFileDiff(fdr.Dels)
// Remove some of the meta diffs that shouldn't be checked
mdr := diffInt[1].Diff.(*metaDiffResult)
mdr.Adds = filterMetaDiff(mdr.Adds)
mdr.Dels = filterMetaDiff(mdr.Dels)
testutil.CheckErrorAndDeepEqual(t, false, nil, expectedInt, diffInt)
}
func filterMetaDiff(metaDiff []string) []string {
// TODO remove this once we agree testing shouldn't run on docker 18.xx
// currently docker 18.xx will build an image with Metadata set
// ArgsEscaped: true, however Docker 19.xx will build an image and have
// ArgsEscaped: false
if config.dockerMajorVersion == 19 {
return metaDiff
}
newDiffs := []string{}
for _, meta := range metaDiff {
if !strings.HasPrefix(meta, "ArgsEscaped") {
newDiffs = append(newDiffs, meta)
}
}
return newDiffs
}
func filterFileDiff(f []fileDiff) []fileDiff {
var newDiffs []fileDiff
for _, diff := range f {
isIgnored := false
for _, p := range allowedDiffPaths {
if util.HasFilepathPrefix(diff.Name, p, false) {
isIgnored = true
break
}
}
if !isIgnored {
newDiffs = append(newDiffs, diff)
}
}
return newDiffs
}
func checkLayers(t *testing.T, image1, image2 string, offset int) {
t.Helper()
img1, err := getImageDetails(image1)
if err != nil {
t.Fatalf("Couldn't get details from image reference for (%s): %s", image1, err)
}
img2, err := getImageDetails(image2)
if err != nil {
t.Fatalf("Couldn't get details from image reference for (%s): %s", image2, err)
}
actualOffset := int(math.Abs(float64(img1.numLayers - img2.numLayers)))
if actualOffset != offset {
t.Fatalf("Difference in number of layers in each image is %d but should be %d. Image 1: %s, Image 2: %s", actualOffset, offset, img1, img2)
}
}
func getImageDetails(image string) (*imageDetails, error) {
ref, err := name.ParseReference(image, name.WeakValidation)
if err != nil {
return nil, fmt.Errorf("Couldn't parse referance to image %s: %w", image, err)
}
imgRef, err := daemon.Image(ref)
if err != nil {
return nil, fmt.Errorf("Couldn't get reference to image %s from daemon: %w", image, err)
}
layers, err := imgRef.Layers()
if err != nil {
return nil, fmt.Errorf("Error getting layers for image %s: %w", image, err)
}
digest, err := imgRef.Digest()
if err != nil {
return nil, fmt.Errorf("Error getting digest for image %s: %w", image, err)
}
return &imageDetails{
name: image,
numLayers: len(layers),
digest: digest.Hex,
}, nil
}