Skip to content

Commit

Permalink
Use --iidfile & --cidfile to get the ctr & img ids
Browse files Browse the repository at this point in the history
We don't have to rely on stdout containing the img id, which is not the case
with the newest docker.
  • Loading branch information
dcermak committed Aug 7, 2023
1 parent 66e1c68 commit 03864e7
Showing 1 changed file with 29 additions and 6 deletions.
35 changes: 29 additions & 6 deletions pytest_container/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
from typing import overload
from typing import Type
from typing import Union
from uuid import uuid4

import pytest
import testinfra
Expand Down Expand Up @@ -682,6 +683,7 @@ def prepare_container(

with tempfile.TemporaryDirectory() as tmpdirname:
containerfile_path = os.path.join(tmpdirname, "Dockerfile")
iidfile = os.path.join(tmpdirname, str(uuid4()))
with open(containerfile_path, "w") as containerfile:
from_id = (
self.base
Expand Down Expand Up @@ -747,12 +749,22 @@ def prepare_container(
if self.add_build_tags
else []
)
+ ["-f", containerfile_path, str(rootdir)]
+ [
f"--iidfile={iidfile}",
"-f",
containerfile_path,
str(rootdir),
]
)

_logger.debug("Building image via: %s", cmd)
self.container_id = runtime.get_image_id_from_stdout(
check_output(cmd).decode().strip()
)
check_output(cmd)

with open(iidfile, "r") as iidfile_f:
hash, img_id = iidfile_f.read(-1).strip().split(":")
assert hash == "sha256"
self.container_id = img_id

_logger.debug(
"Successfully build the container image %s", self.container_id
)
Expand Down Expand Up @@ -862,6 +874,12 @@ class ContainerLauncher:

_stack: contextlib.ExitStack = field(default_factory=contextlib.ExitStack)

_cidfile: str = field(
default_factory=lambda: os.path.join(
tempfile.gettempdir(), str(uuid4())
)
)

def __enter__(self) -> "ContainerLauncher":
return self

Expand Down Expand Up @@ -918,6 +936,8 @@ def release_lock() -> None:
if self.container_name:
extra_run_args.extend(["--name", self.container_name])

extra_run_args.append(f"--cidfile={self._cidfile}")

# We must perform the launches in separate branches, as containers with
# port forwards must be launched while the lock is being held. Otherwise
# another container could pick the same ports before this one launches.
Expand All @@ -934,14 +954,17 @@ def release_lock() -> None:
)

_logger.debug("Launching container via: %s", launch_cmd)
self._container_id = check_output(launch_cmd).decode().strip()
check_output(launch_cmd)
else:
launch_cmd = self.container.get_launch_cmd(
self.container_runtime, extra_run_args=extra_run_args
)

_logger.debug("Launching container via: %s", launch_cmd)
self._container_id = check_output(launch_cmd).decode().strip()
check_output(launch_cmd)

with open(self._cidfile, "r") as cidfile:
self._container_id = cidfile.read(-1).strip()

self._wait_for_container_to_become_healthy()

Expand Down

0 comments on commit 03864e7

Please sign in to comment.