Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 22 additions & 5 deletions bin/docker-to-squash.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,9 +239,22 @@ def hdfs_stat(file_path, fmt, print_stdout=False, print_stderr=True, raise_on_er
return out, err, rc


def get_working_dir(directory):
def get_working_dir(directory, reuse=False):
"""Create the working directory and return its path.

By default a directory that already exists is not used directly: a fresh
"docker-to-squash" subdirectory is created in it instead, because most commands
remove their working directory when they finish.

pull-build and push-update are two halves of one workflow and don't remove the
working directory, so they pass reuse=True and both use ``directory`` itself.
"""
working_dir = "(undefined)"
try:
if reuse:
working_dir = directory
os.makedirs(working_dir, exist_ok=True)
return working_dir
if os.path.isdir(directory):
working_dir = os.path.join(directory, "docker-to-squash")
else:
Expand Down Expand Up @@ -820,10 +833,12 @@ def pull_build(args):
logging.debug(f"Layers: {layers}")
logging.debug(f"Config: {config_hash}")
skopeo_dir = None
created_skopeo_dir = False

try:
working_dir = get_working_dir(args.working_dir)
working_dir = get_working_dir(args.working_dir, reuse=True)
skopeo_dir = os.path.join(working_dir, image.split("/")[-1])
created_skopeo_dir = not os.path.exists(skopeo_dir)
logging.debug(f"skopeo_dir: {skopeo_dir}")
skopeo_copy_image(pull_format, image, skopeo_format, skopeo_dir)

Expand All @@ -835,7 +850,7 @@ def pull_build(args):
docker_to_squash(skopeo_dir, layer, working_dir)

except Exception as _:
if skopeo_dir and os.path.isdir(skopeo_dir):
if created_skopeo_dir and skopeo_dir and os.path.isdir(skopeo_dir):
shutil.rmtree(skopeo_dir)
raise

Expand All @@ -856,7 +871,7 @@ def push_update(args):
local_image_tag_to_hash = None

try:
working_dir = get_working_dir(args.working_dir)
working_dir = get_working_dir(args.working_dir, reuse=True)
local_image_tag_to_hash = os.path.join(working_dir, os.path.basename(image_tag_to_hash))
if bootstrap:
hdfs_dirs = [HDFS_ROOT, HDFS_LAYERS_DIR, HDFS_CONFIG_DIR, HDFS_MANIFEST_DIR, HDFS_UNREF_DIR]
Expand Down Expand Up @@ -1671,7 +1686,9 @@ def create_parsers():

def add_parser_default_arguments(parser):
parser.add_argument("--working-dir", type=str, dest='working_dir', default="dts-work-dir",
help="Name of working directory")
help="Name of working directory. pull-build and push-update reuse this "
"directory as-is so they can share it; other commands create a "
"subdirectory if it already exists")
parser.add_argument("--skopeo-format", type=str, dest='skopeo_format',
default='dir', help="Output format for skopeo copy")
parser.add_argument("--pull-format", type=str, dest='pull_format',
Expand Down
98 changes: 98 additions & 0 deletions bin/test_docker_to_squash.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import json
import os
import tempfile
from unittest import TestCase, mock
# import docker-to-squash as dtsq
dtsq = __import__('docker-to-squash') # TODO: rename docker-to-squash.py as docker_to_squash.py
Expand Down Expand Up @@ -79,6 +82,101 @@ def fake_shell_command(cmd, *args, **kwargs):
self.assertEqual(["docker://registry.example.com/team/app:1.0",
"docker://registry.example.com/team/app@sha256:amd"], inspected)

def test_get_working_dir_reuse(self):
with tempfile.TemporaryDirectory() as tmp:
work_dir = os.path.join(tmp, "dts-work-dir")
# pull-build calls this once per image, push-update once more later
for _ in range(3):
self.assertEqual(work_dir, dtsq.get_working_dir(work_dir, reuse=True))
self.assertEqual([], os.listdir(work_dir))

def test_get_working_dir_default_does_not_use_existing_dir(self):
with tempfile.TemporaryDirectory() as tmp:
# commands that clean up afterwards must not remove a directory they didn't create
self.assertEqual(os.path.join(tmp, "docker-to-squash"), dtsq.get_working_dir(tmp))

def test_pull_build_and_push_update_use_the_same_dir(self):
with tempfile.TemporaryDirectory() as tmp:
work_dir = os.path.join(tmp, "dts-work-dir")
images = ["ubuntu:22.04,ubuntu", "alpine:3.20,alpine", "busybox:1.36,busybox"]
copied_to = []
args = argparse.Namespace(skopeo_format="dir", pull_format="docker", images_and_tags=images,
check_magic_file=False, magic_file=None, working_dir=work_dir)

def fake_copy(pull_format, image, skopeo_format, skopeo_dir):
os.makedirs(skopeo_dir)
copied_to.append(skopeo_dir)

with mock.patch.object(dtsq, "get_manifest_from_docker_image", return_value=({}, "hash")), \
mock.patch.object(dtsq, "get_layer_hashes_from_manifest", return_value=[]), \
mock.patch.object(dtsq, "get_config_hash_from_manifest", return_value="config"), \
mock.patch.object(dtsq, "skopeo_copy_image", side_effect=fake_copy):
dtsq.pull_build(args)

self.assertEqual([os.path.join(work_dir, "ubuntu:22.04"), os.path.join(work_dir, "alpine:3.20"),
os.path.join(work_dir, "busybox:1.36")], copied_to)

# push-update must look for the image where pull-build left it
seen = []
push_args = argparse.Namespace(image_tag_to_hash="image-tag-to-hash", replication=1, force=False,
images_and_tags=images[:1], bootstrap=False, working_dir=work_dir)

def fake_local_manifest(path):
seen.append(path)
raise RuntimeError("stop after the lookup")

with mock.patch.object(dtsq, "populate_tag_dicts", return_value=({}, {}, "hash")), \
mock.patch.object(dtsq, "get_local_manifest_from_path", side_effect=fake_local_manifest):
with self.assertRaisesRegex(RuntimeError, "stop after the lookup"):
dtsq.push_update(push_args)
self.assertEqual([os.path.join(work_dir, "ubuntu:22.04", "manifest.json")], seen)

def test_pull_build_keeps_existing_skopeo_dir_on_failure(self):
with tempfile.TemporaryDirectory() as tmp:
work_dir = os.path.join(tmp, "dts-work-dir")
skopeo_dir = os.path.join(work_dir, "ubuntu:22.04")
os.makedirs(skopeo_dir)
leftover = os.path.join(skopeo_dir, "layer.sqsh")
with open(leftover, "w") as f:
f.write("previous-run")

args = argparse.Namespace(skopeo_format="dir", pull_format="docker",
images_and_tags=["ubuntu:22.04,ubuntu"],
check_magic_file=False, magic_file=None, working_dir=work_dir)

with mock.patch.object(dtsq, "get_manifest_from_docker_image", return_value=({}, "hash")), \
mock.patch.object(dtsq, "get_layer_hashes_from_manifest", return_value=[]), \
mock.patch.object(dtsq, "get_config_hash_from_manifest", return_value="config"), \
mock.patch.object(dtsq, "skopeo_copy_image", side_effect=RuntimeError("copy failed")):
with self.assertRaisesRegex(RuntimeError, "copy failed"):
dtsq.pull_build(args)

self.assertTrue(os.path.isdir(skopeo_dir))
self.assertTrue(os.path.isfile(leftover))
with open(leftover) as f:
self.assertEqual("previous-run", f.read())

def test_pull_build_removes_skopeo_dir_created_this_run_on_failure(self):
with tempfile.TemporaryDirectory() as tmp:
work_dir = os.path.join(tmp, "dts-work-dir")
skopeo_dir = os.path.join(work_dir, "ubuntu:22.04")
args = argparse.Namespace(skopeo_format="dir", pull_format="docker",
images_and_tags=["ubuntu:22.04,ubuntu"],
check_magic_file=False, magic_file=None, working_dir=work_dir)

def fake_copy(pull_format, image, skopeo_format, dest):
os.makedirs(dest)
raise RuntimeError("copy failed")

with mock.patch.object(dtsq, "get_manifest_from_docker_image", return_value=({}, "hash")), \
mock.patch.object(dtsq, "get_layer_hashes_from_manifest", return_value=[]), \
mock.patch.object(dtsq, "get_config_hash_from_manifest", return_value="config"), \
mock.patch.object(dtsq, "skopeo_copy_image", side_effect=fake_copy):
with self.assertRaisesRegex(RuntimeError, "copy failed"):
dtsq.pull_build(args)

self.assertFalse(os.path.exists(skopeo_dir))

# TODO:
# def test_read_image_tag_to_hash(self):
# """
Expand Down