forked from goldmann/docker-squash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_integ_squash.py
1347 lines (1154 loc) · 50.4 KB
/
test_integ_squash.py
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
import codecs
import json
import logging
import os
import re
import shutil
import tarfile
import unittest
import uuid
from io import BytesIO
import docker.errors
import mock
import pytest
from packaging import version as packaging_version
from docker_squash.errors import SquashError, SquashUnnecessaryError
from docker_squash.lib import common
from docker_squash.squash import Squash
class ImageHelper(object):
@staticmethod
def top_layer_path(tar):
# tar_object.seek(0)
reader = codecs.getreader("utf-8")
if "repositories" in tar.getnames():
repositories_member = tar.getmember("repositories")
repositories = json.load(reader(tar.extractfile(repositories_member)))
return repositories.popitem()[1].popitem()[1]
if "manifest.json" in tar.getnames():
manifest_member = tar.getmember("manifest.json")
manifest = json.load(reader(tar.extractfile(manifest_member)))
return manifest[0]["Layers"][-1].split("/")[0]
class IntegSquash(unittest.TestCase):
BUSYBOX_IMAGE = "busybox:1.34"
log = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter(
"%(asctime)s %(filename)s:%(lineno)-10s %(levelname)-5s %(message)s"
)
handler.setFormatter(formatter)
log.addHandler(handler)
log.setLevel(logging.DEBUG)
docker = common.docker_client(log)
@classmethod
def build_image(cls, dockerfile):
IntegSquash.image = IntegSquash.Image(dockerfile)
IntegSquash.image.__enter__()
@classmethod
def cleanup_image(cls):
IntegSquash.image.__exit__(None, None, None)
class Image(object):
def __init__(self, dockerfile, tag="latest"):
self.dockerfile = dockerfile
self.docker = TestIntegSquash.docker
self.name = "integ-%s" % uuid.uuid1()
self.tag = f"{self.name}:{tag}"
def __enter__(self):
f = BytesIO(self.dockerfile.encode("utf-8"))
for line in self.docker.build(fileobj=f, tag=self.tag, rm=True):
try:
print(json.loads(line.decode("utf-8"))["stream"].strip())
except KeyError:
print(line)
self.history = self.docker.history(self.tag)
self.layers = [o["Id"] for o in self.history]
self.metadata = self.docker.inspect_image(self.tag)
self.tar = self._save_image()
with tarfile.open(fileobj=self.tar, mode="r") as tar:
self.tarnames = tar.getnames()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if not os.getenv("CI"):
try:
self.docker.remove_image(image=self.tag, force=True)
except docker.errors.DockerException:
# Can throw if cleanup results in the same image being deleted.
pass
# Duplicated, I know...
def _save_image(self):
image = self.docker.get_image(self.tag)
buf = BytesIO()
for chunk in image:
buf.write(chunk)
buf.seek(0) # Rewind
return buf
def assertFileExistsInLayer(self, name, layer=-1):
self.tar.seek(0) # Rewind
reader = codecs.getreader("utf-8")
with tarfile.open(fileobj=self.tar, mode="r") as tar:
manifest_member = tar.getmember("manifest.json")
manifest_file = tar.extractfile(manifest_member)
manifest = json.load(reader(manifest_file))
layer_member = tar.getmember(manifest[0]["Layers"][layer])
layer_file = tar.extractfile(layer_member)
with tarfile.open(fileobj=layer_file, mode="r") as layer_tar:
assert (
name in layer_tar.getnames()
), "File '%s' was not found in layer files: %s" % (
name,
layer_tar.getnames(),
)
class SquashedImage(object):
def __init__(
self,
image,
number_of_layers=None,
output_path=None,
load_image=True,
numeric=False,
tmp_dir=None,
log=None,
tag=True,
cleanup=False,
):
self.image = image
self.number_of_layers = number_of_layers
self.docker = TestIntegSquash.docker
self.log = log or TestIntegSquash.log
if tag:
self.tag = "%s:squashed" % self.image.name
else:
self.tag = None
self.output_path = output_path
self.load_image = load_image
self.numeric = numeric
self.tmp_dir = tmp_dir
self.cleanup = cleanup
def __enter__(self):
from_layer = self.number_of_layers
if self.number_of_layers and not self.numeric:
from_layer = self.docker.history(self.image.tag)[self.number_of_layers][
"Id"
]
squash = Squash(
self.log,
self.image.tag,
self.docker,
tag=self.tag,
from_layer=from_layer,
output_path=self.output_path,
load_image=self.load_image,
tmp_dir=self.tmp_dir,
cleanup=self.cleanup,
)
self.image_id = squash.run()
if not self.output_path:
self.history = self.docker.history(self.image_id)
if self.tag:
self.tar = self._save_image()
with tarfile.open(fileobj=self.tar, mode="r") as tar:
self.tarnames = tar.getnames()
self.squashed_layer = self._squashed_layer()
self.layers = [o["Id"] for o in self.docker.history(self.image_id)]
self.metadata = self.docker.inspect_image(self.image_id)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if not (os.getenv("CI") or self.output_path):
self.docker.remove_image(image=self.image_id, force=True)
def _save_image(self):
image = self.docker.get_image(self.tag)
buf = BytesIO()
for chunk in image:
buf.write(chunk)
buf.seek(0) # Rewind
return buf
def _extract_file(self, name, tar_object):
tar_object.seek(0)
with tarfile.open(fileobj=tar_object, mode="r") as tar:
member = tar.getmember(name)
return tar.extractfile(member)
def _squashed_layer(self):
self.tar.seek(0)
with tarfile.open(fileobj=self.tar, mode="r") as tar:
self.squashed_layer_path = ImageHelper.top_layer_path(tar)
if packaging_version.parse(
self.docker.version().get("Version")
) >= packaging_version.parse("25.0"):
return self._extract_file(
"blobs/sha256/%s" % self.squashed_layer_path, self.tar
)
else:
return self._extract_file(
"%s/layer.tar" % self.squashed_layer_path, self.tar
)
def assertFileExists(self, name):
self.squashed_layer.seek(0) # Rewind
with tarfile.open(fileobj=self.squashed_layer, mode="r") as tar:
assert (
name in tar.getnames()
), "File '%s' was not found in the squashed files: %s" % (
name,
tar.getnames(),
)
def assertFileDoesNotExist(self, name):
self.squashed_layer.seek(0) # Rewind
with tarfile.open(fileobj=self.squashed_layer, mode="r") as tar:
assert (
name not in tar.getnames()
), "File '%s' was found in the squashed layer files: %s" % (
name,
tar.getnames(),
)
def assertFileIsNotHardLink(self, name):
self.squashed_layer.seek(0) # Rewind
with tarfile.open(fileobj=self.squashed_layer, mode="r") as tar:
member = tar.getmember(name)
assert member.islnk() is False, (
"File '%s' should not be a hard link, but it is" % name
)
def assert_target_tag_exists(self):
if self.tag:
# Raise exception if it doesn't exist
self.docker.inspect_image(self.tag)
class Container(object):
def __init__(self, image):
self.image = image
self.docker = TestIntegSquash.docker
self.log = TestIntegSquash.log
def __enter__(self):
self.container = self.docker.create_container(image=self.image.tag)
data = self.docker.export(self.container)
self.content = BytesIO()
for chunk in data:
self.content.write(chunk)
self.content.seek(0) # Rewind
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if not os.getenv("CI"):
self.docker.remove_container(self.container, force=True)
def assertFileExists(self, name):
self.content.seek(0) # Rewind
with tarfile.open(fileobj=self.content, mode="r") as tar:
assert (
name in tar.getnames()
), "File %s was not found in the container files: %s" % (
name,
tar.getnames(),
)
def assertFileDoesNotExist(self, name):
self.content.seek(0) # Rewind
with tarfile.open(fileobj=self.content, mode="r") as tar:
assert (
name not in tar.getnames()
), "File %s was found in the container files: %s" % (
name,
tar.getnames(),
)
class TestIntegSquash(IntegSquash):
@pytest.fixture(autouse=True)
def inject_fixtures(self, caplog):
self.caplog = caplog
def test_same_source_and_target_image_tag_should_not_be_deleted(self):
self.caplog.set_level(logging.DEBUG, logger="cekit")
dockerfile = (
"""
FROM %s
RUN touch /somefile_layer1
RUN touch /somefile_layer2
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile, tag="squashed") as image:
with self.SquashedImage(image, 2, cleanup=True) as squashed_image:
squashed_image.assert_target_tag_exists()
assert "Tag is the same as image; preventing cleanup" in self.caplog.text
def test_all_files_should_be_in_squashed_layer(self):
"""
We squash all layers in RUN, all files should be in the resulting squashed layer.
"""
dockerfile = (
"""
FROM %s
RUN touch /somefile_layer1
RUN touch /somefile_layer2
RUN touch /somefile_layer3
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 3) as squashed_image:
squashed_image.assertFileDoesNotExist(".wh.somefile_layer1")
squashed_image.assertFileDoesNotExist(".wh.somefile_layer2")
squashed_image.assertFileDoesNotExist(".wh.somefile_layer3")
squashed_image.assertFileExists("somefile_layer1")
squashed_image.assertFileExists("somefile_layer2")
squashed_image.assertFileExists("somefile_layer3")
with self.Container(squashed_image) as container:
container.assertFileExists("somefile_layer1")
container.assertFileExists("somefile_layer2")
container.assertFileExists("somefile_layer3")
# We should have two layers less in the image
self.assertTrue(len(squashed_image.layers) == len(image.layers) - 2)
def test_only_files_from_squashed_image_should_be_in_squashed_layer(self):
"""
We squash all layers in RUN, all files should be in the resulting squashed layer.
"""
dockerfile = (
"""
FROM %s
RUN touch /somefile_layer1
RUN touch /somefile_layer2
RUN touch /somefile_layer3
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 2) as squashed_image:
squashed_image.assertFileDoesNotExist(".wh.somefile_layer2")
squashed_image.assertFileDoesNotExist(".wh.somefile_layer3")
# This file should not be in the squashed layer
squashed_image.assertFileDoesNotExist("somefile_layer1")
# Nor a marker files for it
squashed_image.assertFileDoesNotExist(".wh.somefile_layer1")
squashed_image.assertFileExists("somefile_layer2")
squashed_image.assertFileExists("somefile_layer3")
with self.Container(squashed_image) as container:
# This file should be in the container
container.assertFileExists("somefile_layer1")
container.assertFileExists("somefile_layer2")
container.assertFileExists("somefile_layer3")
# We should have two layers less in the image
self.assertEqual(len(squashed_image.layers), len(image.layers) - 1)
def test_there_should_be_a_marker_file_in_the_squashed_layer(self):
"""
Here we're testing that the squashed layer should contain a '.wh.somefile_layer1'
file, because the file was not found in the squashed tar and it is present in
the layers we do not squash.
"""
dockerfile = (
"""
FROM %s
RUN touch /somefile_layer1
RUN rm /somefile_layer1
RUN touch /somefile_layer3
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 2) as squashed_image:
squashed_image.assertFileDoesNotExist("somefile_layer1")
squashed_image.assertFileExists("somefile_layer3")
squashed_image.assertFileExists(".wh.somefile_layer1")
squashed_image.assertFileIsNotHardLink(".wh.somefile_layer1")
with self.Container(squashed_image) as container:
container.assertFileExists("somefile_layer3")
container.assertFileDoesNotExist("somefile_layer1")
# We should have one layer less in the image
self.assertEqual(len(squashed_image.layers), len(image.layers) - 1)
def test_there_should_be_a_marker_file_in_the_squashed_layer_even_more_complex(
self,
):
dockerfile = (
"""
FROM %s
RUN touch /somefile_layer1
RUN rm /somefile_layer1
RUN touch /somefile_layer2
RUN touch /somefile_layer3
RUN rm /somefile_layer2
RUN touch /somefile_layer4
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 2) as squashed_image:
squashed_image.assertFileDoesNotExist("somefile_layer1")
squashed_image.assertFileDoesNotExist("somefile_layer2")
squashed_image.assertFileDoesNotExist("somefile_layer3")
squashed_image.assertFileExists("somefile_layer4")
squashed_image.assertFileDoesNotExist(".wh.somefile_layer1")
squashed_image.assertFileExists(".wh.somefile_layer2")
squashed_image.assertFileIsNotHardLink(".wh.somefile_layer2")
squashed_image.assertFileDoesNotExist(".wh.somefile_layer3")
squashed_image.assertFileDoesNotExist(".wh.somefile_layer4")
with self.Container(squashed_image) as container:
container.assertFileExists("somefile_layer3")
container.assertFileExists("somefile_layer4")
container.assertFileDoesNotExist("somefile_layer1")
container.assertFileDoesNotExist("somefile_layer2")
# We should have one layer less in the image
self.assertEqual(len(squashed_image.layers), len(image.layers) - 1)
def test_should_handle_removal_of_directories(self):
dockerfile = (
"""
FROM %s
RUN mkdir -p /some/dir/tree
RUN touch /some/dir/tree/file1
RUN touch /some/dir/tree/file2
RUN touch /some/dir/file1
RUN touch /some/dir/file2
RUN rm -rf /some/dir/tree
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 2) as squashed_image:
squashed_image.assertFileDoesNotExist("some/dir/tree/file1")
squashed_image.assertFileDoesNotExist("some/dir/tree/file2")
squashed_image.assertFileDoesNotExist("some/dir/file1")
squashed_image.assertFileExists("some/dir/file2")
squashed_image.assertFileExists("some/dir/.wh.tree")
squashed_image.assertFileIsNotHardLink("some/dir/.wh.tree")
with self.Container(squashed_image) as container:
container.assertFileExists("some/dir/file1")
container.assertFileExists("some/dir/file2")
container.assertFileDoesNotExist("some/dir/tree")
container.assertFileDoesNotExist("some/dir/tree/file1")
container.assertFileDoesNotExist("some/dir/tree/file2")
# We should have one layer less in the image
self.assertEqual(len(squashed_image.layers), len(image.layers) - 1)
def test_should_skip_files_when_these_are_modified_and_removed_in_squashed_layer(
self,
):
dockerfile = (
"""
FROM %s
RUN touch /file
RUN chmod -R 777 /file
RUN rm -rf /file
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 2) as squashed_image:
squashed_image.assertFileDoesNotExist("file")
squashed_image.assertFileExists(".wh.file")
squashed_image.assertFileIsNotHardLink(".wh.file")
with self.Container(squashed_image) as container:
container.assertFileDoesNotExist("file")
# We should have one layer less in the image
self.assertEqual(len(squashed_image.layers), len(image.layers) - 1)
def test_should_skip_files_when_these_are_removed_and_modified_in_squashed_layer(
self,
):
dockerfile = (
"""
FROM %s
RUN touch /file
RUN chmod -R 777 /file
RUN rm -rf /file
RUN touch /file
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 3) as squashed_image:
squashed_image.assertFileExists("file")
squashed_image.assertFileDoesNotExist(".wh.file")
with self.Container(squashed_image) as container:
container.assertFileExists("file")
# We should have two layers less in the image
self.assertEqual(len(squashed_image.layers), len(image.layers) - 2)
def test_should_handle_multiple_changes_to_files_in_squashed_layers(self):
dockerfile = (
"""
FROM %s
RUN mkdir -p /some/dir/tree
RUN touch /some/dir/tree/file1
RUN touch /some/dir/tree/file2
RUN touch /some/dir/file1
RUN touch /some/dir/file2
RUN chmod -R 777 /some
RUN rm -rf /some/dir/tree
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 2, numeric=True) as squashed_image:
squashed_image.assertFileDoesNotExist("some/dir/tree/file1")
squashed_image.assertFileDoesNotExist("some/dir/tree/file2")
squashed_image.assertFileExists("some/dir/file1")
squashed_image.assertFileExists("some/dir/file2")
squashed_image.assertFileExists("some/dir/.wh.tree")
squashed_image.assertFileIsNotHardLink("some/dir/.wh.tree")
with self.Container(squashed_image) as container:
container.assertFileExists("some/dir/file1")
container.assertFileExists("some/dir/file2")
container.assertFileDoesNotExist("some/dir/tree")
container.assertFileDoesNotExist("some/dir/tree/file1")
container.assertFileDoesNotExist("some/dir/tree/file2")
# We should have one layer less in the image
self.assertEqual(len(squashed_image.layers), len(image.layers) - 1)
# https://github.com/goldmann/docker-squash/issues/97
def test_should_leave_whiteout_entries_as_is(self):
dockerfile = (
"""
FROM %s
RUN mkdir -p /opt/test.one
RUN mkdir -p /opt/test.two
RUN mkdir -p /opt/foo
RUN touch /opt/test.one/file
RUN touch /opt/test.two/file
RUN touch /opt/foo/file
RUN rm -rvf /opt/test*/*
RUN rm -rvf /opt/foo/*
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 2, numeric=True) as squashed_image:
squashed_image.assertFileDoesNotExist("opt/test.one/file")
squashed_image.assertFileDoesNotExist("opt/test.two/file")
squashed_image.assertFileDoesNotExist("opt/foo/file")
squashed_image.assertFileExists("opt/test.one")
squashed_image.assertFileExists("opt/test.two")
squashed_image.assertFileExists("opt/foo")
squashed_image.assertFileExists("opt/test.one/.wh.file")
squashed_image.assertFileExists("opt/test.two/.wh.file")
squashed_image.assertFileExists("opt/foo/.wh.file")
with self.Container(squashed_image) as container:
container.assertFileDoesNotExist("opt/test.one/file")
container.assertFileDoesNotExist("opt/test.two/file")
container.assertFileDoesNotExist("opt/foo/file")
container.assertFileExists("opt/foo")
container.assertFileExists("opt/test.one")
container.assertFileExists("opt/test.two")
# https://github.com/goldmann/docker-scripts/issues/28
def test_docker_version_in_metadata_should_be_set_after_squashing(self):
dockerfile = (
"""
FROM %s
RUN touch file
RUN touch another_file
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 2) as squashed_image:
self.assertEqual(len(squashed_image.layers), len(image.layers) - 1)
self.assertEqual(
image.metadata["DockerVersion"],
squashed_image.metadata["DockerVersion"],
)
# https://github.com/goldmann/docker-scripts/issues/30
# https://github.com/goldmann/docker-scripts/pull/31
def test_files_in_squashed_tar_not_prefixed_wth_dot(self):
dockerfile = (
"""
FROM %s
RUN touch file
RUN touch another_file
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 2, output_path="image.tar"):
with tarfile.open("image.tar", mode="r") as tar:
all_files = tar.getnames()
for name in all_files:
self.assertFalse(name.startswith("."))
# https://github.com/goldmann/docker-scripts/issues/32
def test_version_file_exists_in_squashed_layer(self):
dockerfile = (
"""
FROM %s
RUN touch file
RUN touch another_file
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 2, output_path="image.tar"):
with tarfile.open("image.tar", mode="r") as tar:
squashed_layer_path = ImageHelper.top_layer_path(tar)
all_files = tar.getnames()
self.assertIn("%s/json" % squashed_layer_path, all_files)
self.assertIn("%s/layer.tar" % squashed_layer_path, all_files)
self.assertIn("%s/VERSION" % squashed_layer_path, all_files)
# https://github.com/goldmann/docker-scripts/issues/33
def test_docker_size_in_metadata_should_be_upper_case(self):
dockerfile = (
"""
FROM %s
RUN touch file
RUN touch another_file
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 2) as squashed_image:
self.assertEqual(len(squashed_image.layers), len(image.layers) - 1)
self.assertIsInstance(image.metadata["Size"], int)
with self.assertRaisesRegex(KeyError, "'size'"):
self.assertEqual(image.metadata["size"], None)
def test_handle_correctly_squashing_layers_without_data(self):
dockerfile = (
"""
FROM %s
ENV a=1
ENV b=2
ENV c=3
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 2) as squashed_image:
self.assertEqual(len(squashed_image.layers), len(image.layers) - 1)
image_data_layers = [s for s in image.tarnames if "layer.tar" in s]
squashed_image_data_layers = [
s for s in squashed_image.tarnames if "layer.tar" in s
]
if "manifest.json" in image.tarnames:
# For v2
# For V2 only layers with data contain layer.tar archives
# In our test case we did not add any data, so the count should
# be the same
self.assertEqual(
len(image_data_layers), len(squashed_image_data_layers)
)
else:
# For v1
# V1 image contains as many layer.tar archives as the image has layers
# We squashed 2 layers, so squashed image contains one layer less
self.assertEqual(
len(image_data_layers), len(squashed_image_data_layers) + 1
)
# This is an edge case where we try to squash last 2 layers
# but these layers do not create any content on filesystem
# https://github.com/goldmann/docker-scripts/issues/54
def test_should_squash_exactly_2_layers_without_data(self):
dockerfile = (
"""
FROM %s
CMD /bin/env
LABEL foo bar
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 2) as squashed_image:
self.assertEqual(len(squashed_image.layers), len(image.layers) - 1)
def test_should_squash_exactly_3_layers_with_data(self):
dockerfile = (
"""
FROM %s
RUN touch /abc
CMD /bin/env
LABEL foo bar
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 3) as squashed_image:
self.assertEqual(len(squashed_image.layers), len(image.layers) - 2)
def test_should_not_squash_if_only_one_layer_is_to_squash(self):
dockerfile = (
"""
FROM %s
RUN touch /abc
CMD /bin/env
LABEL foo bar
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.assertRaises(SquashUnnecessaryError) as cm:
with self.SquashedImage(image, 1):
pass
self.assertEqual(
str(cm.exception), "Single layer marked to squash, no squashing is required"
)
# https://github.com/goldmann/docker-scripts/issues/52
# Test may be misleading, but squashing all layers makes sure we hit
# at least one <missing> layer
def test_should_squash_every_layer(self):
dockerfile = (
"""
FROM %s
RUN touch /tmp/test1
RUN touch /tmp/test2
CMD /bin/env
LABEL foo bar
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image) as squashed_image:
self.assertEqual(len(squashed_image.layers), 1)
# https://github.com/goldmann/docker-scripts/issues/44
def test_remove_tmp_dir_after_failure(self):
self.caplog.set_level(logging.DEBUG, logger="cekit")
dockerfile = """
FROM busybox:1.24.0
LABEL foo bar
"""
with self.Image(dockerfile) as image:
with self.assertRaisesRegex(
SquashError,
r"Cannot squash 20 layers, the .* image contains only \d " r"layers",
):
with self.SquashedImage(image, 20, numeric=True):
pass
tmp_location = re.search(
".*Using (.*)as the temporary directory.*", self.caplog.text
)
assert tmp_location
assert "Cleaning up %s temporary directory", (
tmp_location.group(1) in self.caplog.text
)
self.assertFalse(os.path.exists(tmp_location.group(1)))
def test_should_not_remove_tmp_dir_after_failure_if_development_mode_is_on(self):
dockerfile = """
FROM busybox:1.24.0
LABEL foo bar
"""
tmp_dir = "/tmp/docker-squash-integ-tmp-dir"
log = mock.Mock()
shutil.rmtree(tmp_dir, ignore_errors=True)
self.assertFalse(os.path.exists(tmp_dir))
with self.Image(dockerfile) as image:
with self.assertRaisesRegex(
SquashError,
r"Cannot squash 20 layers, the .* image contains only \d " r"layers",
):
with self.SquashedImage(
image, 20, numeric=True, tmp_dir=tmp_dir, log=log
):
pass
log.debug.assert_any_call(
"Using /tmp/docker-squash-integ-tmp-dir as the temporary directory"
)
self.assertTrue(os.path.exists(tmp_dir))
# https://github.com/goldmann/docker-squash/issues/80
def test_should_not_fail_with_hard_links(self):
dockerfile = (
"""
FROM %s
RUN touch /file && ln file link
RUN rm file
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, None):
pass
# https://github.com/goldmann/docker-squash/issues/99
# TODO: try not to use centos:6.6 image - this slows down testsuite
def test_should_not_fail_with_hard_links_to_files_gh_99(self):
dockerfile = """
FROM centos:7
RUN yum clean all
"""
with self.Image(dockerfile) as image:
with self.SquashedImage(image, None):
pass
# https://github.com/goldmann/docker-squash/issues/66
def test_build_without_tag(self):
dockerfile = (
"""
FROM %s
RUN touch file
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, None, tag=False):
pass
# https://github.com/goldmann/docker-squash/issues/94
def test_should_squash_correctly_hardlinks(self):
dockerfile = (
"""
FROM %s
RUN mkdir -p /usr/libexec/git-core && \
echo foo > /usr/libexec/git-core/git-remote-ftp && \
ln /usr/libexec/git-core/git-remote-ftp \
/usr/libexec/git-core/git-remote-http
CMD /bin/bash
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 3, numeric=True) as squashed_image:
self.assertEqual(len(squashed_image.layers), len(image.layers) - 2)
squashed_image.assertFileExists("usr/libexec/git-core/git-remote-ftp")
squashed_image.assertFileExists("usr/libexec/git-core/git-remote-http")
# https://github.com/goldmann/docker-squash/issues/104
def test_should_handle_symlinks_to_nonexisting_locations(self):
dockerfile = (
"""
FROM %s
RUN mkdir -p /var/log
RUN touch /var/log/somelog
RUN mv /var/log /var/log-removed && ln -sf /data/var/log /var/log
RUN rm -rf /var/log-removed
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 3, numeric=True) as squashed_image:
self.assertEqual(len(squashed_image.layers), len(image.layers) - 2)
def test_should_squash_every_layer_from_an_image_from_docker_hub(self):
dockerfile = """
FROM python:3.5-alpine
"""
with self.Image(dockerfile) as image:
with self.SquashedImage(image) as squashed_image:
self.assertEqual(len(squashed_image.layers), 1)
# https://github.com/goldmann/docker-squash/issues/111
def test_correct_symlinks_squashing(self):
dockerfile = (
"""
FROM %s
RUN mkdir -p /zzz
RUN ln -s /zzz /xxx
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image) as squashed_image:
squashed_image.assertFileExists("zzz")
squashed_image.assertFileExists("xxx")
with self.Container(squashed_image) as container:
container.assertFileExists("zzz")
container.assertFileExists("xxx")
# https://github.com/goldmann/docker-squash/issues/112
def test_should_add_broken_symlinks_back(self):
dockerfile = (
"""
FROM %s
RUN touch a
RUN touch b
RUN ln -s /zzz /xxx
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 2, numeric=True) as squashed_image:
squashed_image.assertFileExists("xxx")
with self.Container(squashed_image) as container:
container.assertFileExists("xxx")
def test_should_add_hard_hard_link_back_if_target_exists_in_moved_files(self):
dockerfile = (
"""
FROM %s
RUN touch a
RUN touch b
RUN ln /a /link
RUN touch c
"""
% TestIntegSquash.BUSYBOX_IMAGE
)
with self.Image(dockerfile) as image:
with self.SquashedImage(image, 3, numeric=True) as squashed_image:
squashed_image.assertFileExists("link")
squashed_image.assertFileExists("b")
with self.Container(squashed_image) as container:
container.assertFileExists("link")
container.assertFileExists("b")
container.assertFileExists("a")
container.assertFileExists("c")
# https://github.com/goldmann/docker-squash/issues/112
def test_should_add_sym_link_back_if_it_was_broken_before(self):
dockerfile = (