Combine develop with main

Maintaining develop has little value.

Merge request reports

Loading
+300
Changes for behave_utils/binaries.py: 300 added lines, 0 removed lines.
Original line number Diff line number Diff line
#  Copyright 2021,2022  Dominik Sekotill <dom.sekotill@kodo.org.uk>
#
#  This Source Code Form is subject to the terms of the Mozilla Public
#  License, v. 2.0. If a copy of the MPL was not distributed with this
#  file, You can obtain one at http://mozilla.org/MPL/2.0/.

"""
Start and manage a test Kubernetes cluster with Kubernetes-in-Docker (kind)
"""

from __future__ import annotations

import platform
import re
from abc import ABC
from abc import abstractmethod
from io import BytesIO
from pathlib import Path
from shutil import copyfileobj
from tarfile import TarFile
from typing import IO
from typing import Iterator

import requests
import xdg
from packaging.version import Version

from behave_utils.json import JSONObject
from behave_utils.url import URL

CACHE_DIR: Path = xdg.xdg_cache_home() / "behave-testing"


class DownloadableExecutable(ABC):
	"""
	Base class for downloading static binaries to local paths

	Subclasses should implement `get_latest` and `get_stream` methods.  They may use the
	"kernel", "arch" and "goarch" attributes to select the correct source for the current
	platform.

	Subclasses must also provide the "name" attribute, either as a class or instance
	attribute.  It is used to generate a cache path.

	Users of the subclasses SHOULD ONLY call the `get_binary` method to get a path pointing
	to a locally cached copy of the downloaded binary.
	"""

	# Map of `uname -m` output to architecture values accepted by Go
	# Many Go binaries include the architecture value accepted by `go` in their names, so
	# the "goarch" class attribute is added for convenience, generated from this map.
	# This map may not be fully complete. Only non-equal values need to be added.
	GOARCH_MAP = {
		"i386": "386",
		"i686": "386",
		"x86": "386",

		"x86_64": "amd64",

		"armv6l": "arm",
		"armv7l": "arm",

		"aarch64": "arm64",
	}

	kernel = platform.system().lower()
	arch = platform.machine()
	goarch = GOARCH_MAP.get(arch, arch)

	name: str

	def __init__(self, version: str = "latest"):
		self.version = version

	@abstractmethod
	def get_latest(self, session: requests.Session) -> str:
		"""
		Return the latest release string for a supported binary

		Implementations must discover and return the latest release or tag string

		`session` is provided for performing HTTP requests.  Although its use is not
		required, it has and automatic code check hook so there is no need to manually check
		the return code and handle errors.
		"""
		raise NotImplementedError

	@abstractmethod
	def get_stream(self, session: requests.Session, version: str) -> IO[bytes]:
		"""
		Return a stream that emits the requested version of a supported binary

		Implementations must perform a request for the binary and return a file-like reader

		The return object must be a readable FileIO like instance, returning bytes.  If the
		source is uncompressed the "raw" attribute of a `requests.Response` object opened
		with `stream=True` will suffice.  See examples below.

		`version` specifies the wanted version of the binary, which MAY be different from
		the "version" instance attribute.  Other attributes such as "kernel" and "arch" (or
		"goarch" if appropriate) MUST be honoured when selecting a source.

		`session` is provided for performing HTTP requests.  Although its use is not
		required, it has and automatic code check hook so there is no need to manually check
		the return code and handle errors.


		Examples:

		1) Get an uncompressed binary:

		>>> def get_stream(session: requests.Session, version: str) -> IO[bytes]:
		...     url = "https://example.com/binary"
		...     return session.get(url, stream=True).raw


		2) Get a binary from a GZip compressed tar archive, storing the tar file in memory:

		Note: Avoid this for very large downloads. Unfortunately the Python tarfile
		implementation cannot handle non-seekable streams.

		>>> from tarfile import TarFile

		>>> def get_stream(session: requests.Session, version: str) -> IO[bytes]:
		...     url = "https://example.com/binary.tar.gz"
		...     buf = BytesIO(session.get(url).content)
		...     tar = TarFile.gzopen("buffer", fileobj=buf)
		...     return tar.extractfile(self.name)


		3) Get a binary from a GZip compressed tar archive, storing the tar file in the file
		system:

		>>> from tarfile import TarFile
		>>> from tempfile import TemporaryFile
		>>> from shutil import copyfileobj

		>>> def get_stream(session: requests.Session, version: str) -> IO[bytes]:
		...     url = "https://example.com/binary.tar.gz"
		...     resp = session.get(url, stream=True)
		...     temp = TemporaryFile()
		...     copyfileobj(resp.raw, temp)
		...     tar = TarFile.gzopen("buffer", fileobj=temp)
		...     return tar.extractfile(self.name)
		"""
		raise NotImplementedError

	def get_binary(self) -> Path:
		"""
		Return a Path to a locally cached executable, downloading it if necessary
		"""
		CACHE_DIR.mkdir(0o775, True, True)
		version = self.version

		with requests.Session() as session:
			assert isinstance(session.hooks["response"], list)
			session.hooks["response"].append(lambda r, *a, **k: r.raise_for_status())

			if version == "latest":
				version = self.get_latest(session)

			binary = CACHE_DIR / f"{self.name}-{version}-{self.kernel}-{self.arch}"
			if binary.exists():
				return binary

			stream = self.get_stream(session, version)

			try:
				with binary.open("wb") as f:
					copyfileobj(stream, f)
			except BaseException:
				binary.unlink()
				raise
			binary.chmod(0o755)

		return binary


class DownloadableDocker(DownloadableExecutable):
	"""
	Download class for the Docker client binary
	"""

	URL = "https://download.docker.com/{kernel}/static/stable/{arch}/docker-{version}.tgz"
	LATEST_URL = "https://download.docker.com/{kernel}/static/stable/{arch}/"
	VERSION_RE = re.compile(rb'href="docker-(?P<release>[0-9.]+).tgz"')

	name = "docker"

	def get_latest(self, session: requests.Session) -> str:
		"""
		Return latest Docker release
		"""
		url = self.LATEST_URL.format(kernel=self.kernel, arch=self.arch)
		doc = session.get(url).content
		latest = max(self._extract_versions(doc))
		return str(latest)

	def get_stream(self, session: requests.Session, version: str) -> IO[bytes]:
		"""
		Return a stream that emits theDocker CLI binary
		"""
		url = self.URL.format(version=version, kernel=self.kernel, arch=self.arch)
		buf = BytesIO(session.get(url).content)
		tar = TarFile.gzopen("buffer", fileobj=buf)
		stream = tar.extractfile("docker/docker")
		if stream is None:
			raise FileNotFoundError(f"'docker/docker' in {url}")
		return stream

	@classmethod
	def _extract_versions(cls, doc: bytes) -> Iterator[Version]:
		for match in cls.VERSION_RE.finditer(doc):
			yield Version(match.group("release").decode())


class DownloadableKubeTools(DownloadableExecutable):
	"""
	Download class for the kubernetes binaries "kubectl", "kubelet" and "kubeadm"
	"""

	URL = "https://dl.k8s.io/release/{version}/bin/{kernel}/{arch}/{name}"
	LATEST_URL = "https://dl.k8s.io/release/stable.txt"

	def __init__(self, name: str, version: str = "latest"):
		DownloadableExecutable.__init__(self, version)
		self.name = name
		self._latest = ""

	def get_latest(self, session: requests.Session) -> str:
		"""
		Return that latest release of Kubernetes
		"""
		if not self._latest:
			self._latest = session.get(self.LATEST_URL).content.decode().strip()
		return self._latest

	def get_stream(self, session: requests.Session, version: str) -> IO[bytes]:
		"""
		Return a stream that emits the requested Kubernetes binary
		"""
		url = self.URL.format(version=version, kernel=self.kernel, arch=self.goarch, name=self.name)
		stream: IO[bytes] = session.get(url, stream=True).raw
		return stream


class DownloadableCrictl(DownloadableExecutable):
	"""
	Download class for the "crictl" binary
	"""

	URL = "https://github.com/kubernetes-sigs/cri-tools/releases/download/{version}/crictl-{version}-{kernel}-{arch}.tar.gz"
	LATEST_URL = "https://api.github.com/repos/kubernetes-sigs/cri-tools/releases/latest"

	name = "cri"

	def get_latest(self, session: requests.Session) -> str:
		"""
		Return the latest "crictl" release
		"""
		json = JSONObject.from_string(session.get(self.LATEST_URL).content)
		return json.path("$.name", str).replace("cri-tools ", "")

	def get_stream(self, session: requests.Session, version: str) -> IO[bytes]:
		"""
		Return a stream that emits the requested "crictl" binary
		"""
		url = self.URL.format(version=version, kernel=self.kernel, arch=self.goarch)
		buf = BytesIO(session.get(url).content)
		tar = TarFile.gzopen("buffer", fileobj=buf)
		stream = tar.extractfile("crictl")
		if stream is None:
			raise FileNotFoundError(f"'crictl' in {url}")
		return stream


class DownloadableKind(DownloadableExecutable):
	"""
	Download class for the "kind" (Kubernetes-in-Docker) binary
	"""

	URL = "https://kind.sigs.k8s.io/dl/{version}/kind-{kernel}-{arch}"
	LATEST_URL = "https://api.github.com/repos/kubernetes-sigs/kind/releases/latest"

	name = "kind"

	def get_latest(self, session: requests.Session) -> str:
		"""
		Return the latest Kind binary
		"""
		json = JSONObject.from_string(session.get(self.LATEST_URL).content)
		return json.path("$.name", str)

	def get_stream(self, session: requests.Session, version: str) -> IO[bytes]:
		"""
		Return a stream that emits the requested Kind binary
		"""
		url = self.URL.format(version=version, kernel=self.kernel, arch=self.goarch)
		stream: IO[bytes] = session.get(url, stream=True).raw
		return stream
+183 −124
Changes for behave_utils/docker.py: 183 added lines, 124 removed lines.
Original line number Diff line number Diff line
#  Copyright 2021  Dominik Sekotill <dom.sekotill@kodo.org.uk>
#  Copyright 2021-2022  Dominik Sekotill <dom.sekotill@kodo.org.uk>
#
#  This Source Code Form is subject to the terms of the Mozilla Public
#  License, v. 2.0. If a copy of the MPL was not distributed with this
@@ -10,10 +10,13 @@ Commands for managing Docker for fixtures

from __future__ import annotations

import codecs
import ipaddress
import json
import logging
from contextlib import contextmanager
from os import PathLike
from os import fspath
from pathlib import Path
from secrets import token_hex
from subprocess import DEVNULL
@@ -27,44 +30,57 @@ from typing import IO
from typing import Any
from typing import Iterable
from typing import Iterator
from typing import Literal
from typing import SupportsBytes
from typing import MutableMapping
from typing import Tuple
from typing import TypeVar
from typing import Union
from typing import overload
from typing import cast

from .binaries import DownloadableDocker
from .json import JSONArray
from .json import JSONObject
from .proc import Argument
from .proc import Arguments
from .proc import Deserialiser
from .proc import Environ
from .proc import Executor
from .proc import MutableArguments
from .proc import PathLike
from .proc import coerce_args
from .proc import exec_io

HostMount = tuple[PathLike, PathLike]
NamedMount = tuple[str, PathLike]
AnonMount = PathLike
Mount = Union[HostMount, NamedMount, AnonMount]
MountPath = Union[PathLike[bytes], PathLike[str]]
HostMount = tuple[MountPath, MountPath]
NamedMount = tuple[str, MountPath]
Mount = Union[HostMount, NamedMount, MountPath]
Volumes = Iterable[Mount]

DOCKER = "docker"

try:
	run([b"docker", b"version"], stdout=DEVNULL)
except FileNotFoundError:
	DOCKER: Argument = DownloadableDocker().get_binary()
else:
	DOCKER = b"docker"


def utf8_decode(buffer: bytes) -> str:
	"""
	Return a decoded string from a bytes-like sequence of bytes
	"""
	return codecs.getdecoder("utf-8")(buffer)[0]


def docker(*args: Argument, **env: str) -> None:
	"""
	Run a Docker command, with output going to stdout
	"""
	run([DOCKER, *coerce_args(args)], env=env, check=True)
	run([DOCKER, *args], env=env, check=True)


def docker_output(*args: Argument, **env: str) -> str:
	"""
	Run a Docker command, capturing and returning its stdout
	"""
	proc = run([DOCKER, *coerce_args(args)], env=env, check=True, stdout=PIPE, text=True)
	proc = run([DOCKER, *args], env=env, check=True, stdout=PIPE, text=True)
	return proc.stdout.strip()


@@ -72,7 +88,7 @@ def docker_quiet(*args: Argument, **env: str) -> None:
	"""
	Run a Docker command, directing its stdout to /dev/null
	"""
	run([DOCKER, *coerce_args(args)], env=env, check=True, stdout=DEVNULL)
	run([DOCKER, *args], env=env, check=True, stdout=DEVNULL)


class IPv4Address(ipaddress.IPv4Address):
@@ -136,7 +152,7 @@ class Image(Item):
		arguments from external lookups without complex argument composing.
		"""
		cmd: Arguments = [
			'build', context, f"--target={target}",
			b"build", context, f"--target={target}",
			*(f"--build-arg={arg}={val}" for arg, val in build_args.items() if val is not None),
		]
		docker(*cmd, DOCKER_BUILDKIT='1')
@@ -148,7 +164,7 @@ class Image(Item):
		"""
		Pull an image from a registry
		"""
		docker('pull', repository)
		docker(b"pull", repository)
		iid = Item(repository).inspect().path('$.Id', str)
		return cls(iid)

@@ -167,6 +183,8 @@ class Container(Item):
	exiting the context.
	"""

	T = TypeVar('T', bound='Container')

	DEFAULT_ALIASES = tuple[str]()

	def __init__(
@@ -177,6 +195,7 @@ class Container(Item):
		env: Environ = {},
		network: Network|None = None,
		entrypoint: HostMount|Argument|None = None,
		privileged: bool = False,
	):
		if isinstance(entrypoint, tuple):
			volumes = [*volumes, entrypoint]
@@ -187,13 +206,14 @@ class Container(Item):
		self.volumes = volumes
		self.env = env
		self.entrypoint = entrypoint
		self.privileged = privileged
		self.networks = dict[Network, Tuple[str, ...]]()
		self.cid: str|None = None

		if network:
			self.connect(network, *self.DEFAULT_ALIASES)

	def __enter__(self) -> Container:
	def __enter__(self: T) -> T:
		return self

	def __exit__(self, etype: type[BaseException], exc: BaseException, tb: TracebackType) -> None:
@@ -210,7 +230,7 @@ class Container(Item):
			self.start()
			yield self

	def is_running(self) -> bool:
	def is_running(self, raise_on_exit: bool = False) -> bool:
		"""
		Return whether the container is running
		"""
@@ -223,6 +243,10 @@ class Container(Item):
				logging.getLogger(__name__).warning(
					f"container {self.cid} exited ({code})",
				)
			if raise_on_exit:
				cmd = details.path("$.Config.Entrypoint", list[str])
				cmd.extend(details.path("$.Config.Cmd", list[str]))
				raise CalledProcessError(code, cmd)
		return (
			self.cid is not None
			and details.path('$.State.Running', bool)
@@ -236,22 +260,34 @@ class Container(Item):
			return self.cid

		opts: MutableArguments = [
			"--network=none",
			*(
				(f"--volume={vol[0]}:{vol[1]}" if isinstance(vol, tuple) else f"--volume={vol}")
				for vol in self.volumes
			),
			b"--network=none",
			*(f"--env={name}={val}" for name, val in self.env.items()),
		]

		for vol in self.volumes:
			if isinstance(vol, tuple):
				src = fspath(vol[0])
				dst = fspath(vol[1])
				if isinstance(src, bytes):
					src = src.decode()
				if isinstance(dst, bytes):
					dst = dst.decode()
				arg: Argument = f"{src}:{dst}"
			else:
				arg = vol
			opts.extend((b"--volume", arg))

		if self.entrypoint:
			opts.append(f"--entrypoint={self.entrypoint}")
			opts.extend((b"--entrypoint", self.entrypoint))

		self.cid = docker_output('container', 'create', *opts, self.image.iid, *self.cmd)
		if self.privileged:
			opts.append(b"--privileged")

		self.cid = docker_output(b"container", b"create", *opts, self.image.iid, *self.cmd)
		assert self.cid

		# Disconnect the "none" network specified as the starting network
		docker_quiet("network", "disconnect", "none", self.cid)
		docker_quiet(b"network", b"disconnect", b"none", self.cid)

		return self.cid

@@ -261,7 +297,7 @@ class Container(Item):
		"""
		if self.is_running():
			return
		docker_quiet('container', 'start', self.get_id())
		docker_quiet(b"container", b"start", self.get_id())

	def stop(self, rm: bool = False) -> None:
		"""
@@ -271,13 +307,18 @@ class Container(Item):
			return
		try:
			if self.is_running():
				docker_quiet('container', 'stop', self.cid)
				docker_quiet(b"container", b"stop", self.cid)
		finally:
			if rm:
				docker_quiet('container', 'rm', self.cid)
				docker_quiet(b"container", b"rm", self.cid)
				self.cid = None

	def connect(self, network: Network, *aliases: str) -> None:
	def connect(
		self,
		network: Network,
		*aliases: str,
		address: ipaddress.IPv4Address|ipaddress.IPv6Address|None = None,
	) -> None:
		"""
		Connect the container to a Docker network

@@ -285,15 +326,20 @@ class Container(Item):
		network.
		"""
		cid = self.get_id()
		opts = [f'--alias={a}' for a in aliases]

		if address is None:
			address = network.reserve_address()
		opts.append(
			f"--ip={address}" if isinstance(address, ipaddress.IPv4Address) else
			f"--ip6={address}",
		)

		if network in self.networks:
			if self.networks[network] == aliases:
				return
			docker('network', 'disconnect', str(network), cid)
		docker(
			'network', 'connect',
			*(f'--alias={a}' for a in aliases),
			str(network), cid,
		)
			docker(b"network", b"disconnect", str(network), cid)
		docker(b"network", b"connect", *opts, str(network), cid)
		self.networks[network] = aliases

	def show_logs(self) -> None:
@@ -301,13 +347,13 @@ class Container(Item):
		Print the container logs to stdout
		"""
		if self.cid:
			docker('logs', self.cid)
			docker(b"logs", self.cid)

	def get_exec_args(self, cmd: Arguments, interactive: bool = False) -> MutableArguments:
		"""
		Return a full argument list for running "cmd" inside the container
		"""
		return [DOCKER, "exec", *(("-i",) if interactive else ""), self.get_id(), *coerce_args(cmd)]
		return [DOCKER, b"exec", *((b"-i",) if interactive else []), self.get_id(), *cmd]

	def run(
		self,
@@ -353,8 +399,12 @@ class Network(Item):
	A Docker network
	"""

	DOCKER_SUBNET = ipaddress.IPv4Network("172.16.0.0/12")

	def __init__(self, name: str|None = None) -> None:
		self._name = name or f"br{token_hex(6)}"
		self._nid: str|None = None
		self._assigned = set[ipaddress.IPv4Address]()

	def __str__(self) -> str:
		return self._name
@@ -389,22 +439,103 @@ class Network(Item):
		"""
		Return an identifier for the Docker Network
		"""
		return self._name
		if self._nid is None:
			self.create()
		assert self._nid is not None
		return self._nid

	def create(self) -> None:
		"""
		Create the network
		"""
		docker_quiet("network", "create", self._name)
		subnet = self.get_free_subnet()
		gateway = next(subnet.hosts())
		try:
			self._nid = docker_output(
				b"network", b"create", self._name,
				f"--subnet={subnet}", f"--gateway={gateway}",
			)
		except CalledProcessError:
			data = exec_io(
				[DOCKER, b"network", b"inspect", self._name],
				deserialiser=JSONArray.from_string,
			)
			if len(data) == 0:
				raise
			self._nid = data.path("$[0].Id", str)
			self._assigned.update(
				data.path(
					"$[0].IPAM.Config[*].Gateway",
					list[str], lambda ls: (IPv4Address(s) for s in ls),
				),
			)
		else:
			self._assigned.add(gateway)
		assert self._nid is not None
		assert len(self._assigned) > 0, \
			"Expected gateways address(es) to be added to assigned addresses set"

	def destroy(self) -> None:
		"""
		Remove the network
		"""
		docker_quiet("network", "rm", self._name)
		if self._nid:
			docker_quiet(b"network", b"rm", self._nid)

	@classmethod
	def get_free_subnet(cls) -> ipaddress.IPv4Network:
		"""
		Return a free private subnet
		"""
		networks = exec_io(
			[DOCKER, b"network", b"ls", b"--format={{.ID}}"],
			deserialiser=utf8_decode,
		).splitlines()
		subnets = exec_io(
			[DOCKER, b"network", b"inspect"] + cast(list[Argument], networks),
			deserialiser=JSONArray.from_string,
		).path(
			"$[*].IPAM.Config[*].Subnet", list[str],
			lambda subnets: {ipaddress.ip_network(net) for net in subnets},
		)
		for subnet in cls.DOCKER_SUBNET.subnets(8):
			if not any(net.overlaps(subnet) for net in subnets):
				return subnet
		raise LookupError(f"No free subnets found in subnet {cls.DOCKER_SUBNET}")

	def reserve_address(self) -> ipaddress.IPv4Address:
		"""
		Return a free address in the network

		Note that the address is not reserved; any changes made to the network such as
		adding a container may invalidate the assurance that the address is free.
		"""
		# TODO: support IPv6
		data = self.inspect()
		# Considering only the first listed subnet
		net = data.path("$.IPAM.Config[0].Subnet", str, ipaddress.IPv4Network)

		# Recycle some old code for an assertion about assigned addresses
		if __debug__:
			reserved: set[ipaddress.IPv4Address] = data.path(
				"$.Containers.*.IPv4Address", list[str],
				lambda addrs: {IPv4Address.with_suffix(a) for a in addrs},
			)
			reserved.add(data.path("$.IPAM.Config[0].Gateway", str, IPv4Address))
			missing = reserved - self._assigned
			assert len(missing) == 0, f"Missing addresses from assigned set: {missing}"

		# Optimise for CPython 3.x without early binding
		assigned = self._assigned

		for addr in net.hosts():
			if addr not in assigned:
				assigned.add(addr)
				return addr
		raise LookupError(f"No free addresses found in subnet {net}")

class Cli:

class Cli(Executor):
	"""
	Manage calling executables in a container

@@ -412,91 +543,19 @@ class Cli:
	is called.
	"""

	T = TypeVar("T")

	def __init__(self, container: Container, *cmd: Argument):
		Executor.__init__(self, *cmd)
		self.container = container
		self.cmd = cmd

	@overload
	def __call__(
	def get_arguments(
		self,
		*args: Argument,
		input: str|bytes|SupportsBytes|None = ...,
		deserialiser: Deserialiser[T],
		query: Literal[False] = False,
		**kwargs: Any,
	) -> T: ...

	@overload
	def __call__(
		self,
		*args: Argument,
		input: str|bytes|SupportsBytes|None = ...,
		deserialiser: None = None,
		query: Literal[True],
		**kwargs: Any,
	) -> int: ...

	@overload
	def __call__(
		self,
		*args: Argument,
		input: str|bytes|SupportsBytes|None = ...,
		deserialiser: None = None,
		query: Literal[False] = False,
		**kwargs: Any,
	) -> None: ...

	def __call__(
		self,
		*args: Argument,
		input: str|bytes|SupportsBytes|None = None,
		deserialiser: Deserialiser[Any]|None = None,
		query: bool = False,
		**kwargs: Any,
	) -> Any:
		cmd: Arguments,
		kwargs: MutableMapping[str, Any],
		has_input: bool,
		is_query: bool,
		deserialiser: Deserialiser[Any]|None,
	) -> Arguments:
		"""
		Run the container executable with the given arguments

		Input:
			Any bytes passed as "input" will be fed into the process' stdin pipe.

		Output:
			If "deserialiser" is provided it will be called with a memoryview of a buffer
			containing any bytes from the process' stdout; whatever is returned by
			"deserialiser" will be returned.

			If "query" is true the return code of the process will be returned.

			Otherwise nothing is returned.

			Note that "deserialiser" and "query" are mutually exclusive; if debugging is
			enabled an AssertionError will be raised if both are non-None/non-False, otherwise
			"query" is ignored.

		Errors:
			If "query" is not true any non-zero return code will cause CalledProcessError to
			be raised.
		Prefix the command arguments with a command necessary for executing in a container
		"""
		# deserialiser = kwargs.pop('deserialiser', None)
		assert not deserialiser or not query

		data = (
			b"" if input is None else
			input.encode() if isinstance(input, str) else
			bytes(input)
		)
		cmd = self.container.get_exec_args([*self.cmd, *args], interactive=bool(data))

		if deserialiser:
			return exec_io(cmd, data, deserialiser=deserialiser, **kwargs)

		rcode = exec_io(cmd, data, **kwargs)
		if query:
			return rcode
		if not isinstance(rcode, int):
			raise TypeError(f"got rcode {rcode!r}")
		if 0 != rcode:
			raise CalledProcessError(rcode, ' '.join(coerce_args(cmd)))
		return None
		return self.container.get_exec_args(cmd, interactive=has_input)
+42 −12
Changes for behave_utils/http.py: 42 added lines, 12 removed lines.
Original line number Diff line number Diff line
#  Copyright 2021  Dominik Sekotill <dom.sekotill@kodo.org.uk>
#  Copyright 2021,2022  Dominik Sekotill <dom.sekotill@kodo.org.uk>
#
#  This Source Code Form is subject to the terms of the Mozilla Public
#  License, v. 2.0. If a copy of the MPL was not distributed with this
@@ -16,11 +16,16 @@ from typing import Mapping
from urllib.parse import urlparse

import requests.adapters
from requests.packages.urllib3 import connection
from requests.packages.urllib3 import connectionpool
from urllib3 import connection
from urllib3 import connectionpool


def redirect(session: requests.Session, prefix: str, address: ipaddress.IPv4Address) -> None:
def redirect(
	session: requests.Session,
	prefix: str,
	address: ipaddress.IPv4Address,
	certificate: str|None = None,
) -> None:
	"""
	Redirect all requests for "prefix" to a given address

@@ -31,11 +36,9 @@ def redirect(session: requests.Session, prefix: str, address: ipaddress.IPv4Addr
	"prefix" is formated as either "{hostname}[:{port}]" or "{schema}://{hostname}[:{port}]"
	where "schema" defaults to (and currently only supports) "http".
	"""
	if prefix.startswith("https://"):
		raise ValueError("https:// prefixes not currently supported")
	if not prefix.startswith("http://"):
		prefix = f"http://{prefix}"
	session.mount(prefix, _DirectedAdapter(address))
	if not prefix.startswith("http://") or prefix.startswith("https://"):
		prefix = f"http://{prefix}" if certificate is None else f"https://{prefix}"
	session.mount(prefix, _DirectedAdapter(address, certificate))


class _DirectedAdapter(requests.adapters.HTTPAdapter):
@@ -49,14 +52,35 @@ class _DirectedAdapter(requests.adapters.HTTPAdapter):
	function.
	"""

	def __init__(self, destination: ipaddress.IPv4Address):
	def __init__(self, destination: ipaddress.IPv4Address, certificate: str|None):
		super().__init__()
		self.destination = destination
		self.certificate = certificate

	def get_connection(self, url: str, proxies: Mapping[str, str]|None = None) -> _HTTPConnectionPool:
	def get_connection(self, url: str, proxies: Mapping[str, str]|None = None) -> connectionpool.HTTPConnectionPool:
		parts = urlparse(url)
		if parts.scheme == "https":
			return _HTTPSConnectionPool(parts.hostname, parts.port, address=self.destination)
		else:
			return _HTTPConnectionPool(parts.hostname, parts.port, address=self.destination)

	def cert_verify(
		self,
		conn: connection.HTTPConnection,
		url: str,
		verify: bool|str,
		cert: str|tuple[str, str],
	) -> None:
		if verify is False:
			raise ValueError("Never disable TLS verification")
		if verify is not True:
			raise ValueError(
				"To supply verification certificates please use "
				"redirect(session, '{url.scheme}://{url.netloc}', '{self.destination}', Path('{verify}'))",
			)
		super().cert_verify(conn, url, True, cert)  # type: ignore
		conn.ca_cert_data = self.certificate  # type: ignore


class _HTTPConnectionPool(connectionpool.HTTPConnectionPool):

@@ -66,5 +90,11 @@ class _HTTPConnectionPool(connectionpool.HTTPConnectionPool):
		host = ""

		def __init__(self, /, address: ipaddress.IPv4Address, **kwargs: Any):
			connection.HTTPConnection.__init__(self, **kwargs)
			super().__init__(**kwargs)
			self._dns_host = str(address)


class _HTTPSConnectionPool(connectionpool.HTTPSConnectionPool):

	class ConnectionCls(connection.HTTPSConnection, _HTTPConnectionPool.ConnectionCls):
		...
+4 −1
Changes for behave_utils/json.py: 4 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -10,6 +10,7 @@ JSON classes for container types (objects and arrays)

from __future__ import annotations

from types import GenericAlias
from typing import Any
from typing import Callable
from typing import TypeVar
@@ -35,13 +36,15 @@ class JSONPathMixin:
	@overload
	def path(self, path: str, kind: type[T], convert: Callable[[T], C]) -> C: ...

	def path(self, path: str, kind: type[T], convert: Callable[[T], C]|None = None) -> T|C:
	def path(self, path: str, kind: type[T]|GenericAlias, convert: Callable[[T], C]|None = None) -> T|C:
		result = JSONPath(path).parse(self)
		if "*" not in path:
			try:
				result = result[0]
			except IndexError:
				raise KeyError(path) from None
		if isinstance(kind, GenericAlias):
			kind = kind.__origin__
		if not isinstance(result, kind):
			raise TypeError(f"{path} is wrong type; expected {kind}; got {type(result)}")
		if convert is None:
+173 −28
Changes for behave_utils/proc.py: 173 added lines, 28 removed lines.
Original line number Diff line number Diff line
#  Copyright 2021  Dominik Sekotill <dom.sekotill@kodo.org.uk>
#  Copyright 2021-2022  Dominik Sekotill <dom.sekotill@kodo.org.uk>
#
#  This Source Code Form is subject to the terms of the Mozilla Public
#  License, v. 2.0. If a copy of the MPL was not distributed with this
@@ -11,28 +11,38 @@ Manage processes asynchronously with stdio capture
from __future__ import annotations

import io
import os
import sys
from copy import copy
from functools import partial
from os import PathLike
from os import fspath
from os import write as fdwrite
from subprocess import DEVNULL
from subprocess import PIPE
from subprocess import CalledProcessError
from typing import IO
from typing import Any
from typing import BinaryIO
from typing import Callable
from typing import Iterator
from typing import Literal
from typing import Mapping
from typing import MutableMapping
from typing import MutableSequence
from typing import Sequence
from typing import SupportsBytes
from typing import TextIO
from typing import TypeVar
from typing import Union
from typing import overload
from warnings import warn

import trio.abc

T = TypeVar('T')
Deserialiser = Callable[[memoryview], T]

PathLike = os.PathLike[str]
Argument = Union[PathLike, str]
Argument = Union[str, bytes, PathLike[str], PathLike[bytes]]
PathArg = Argument  # deprecated
Arguments = Sequence[Argument]
MutableArguments = MutableSequence[Argument]
@@ -43,37 +53,39 @@ def coerce_args(args: Arguments) -> Iterator[str]:
	"""
	Ensure path-like arguments are converted to strings
	"""
	return (os.fspath(a) for a in args)
	for arg in args:
		arg = fspath(arg)
		yield arg if isinstance(arg, str) else arg.decode()


@overload
def exec_io(
	cmd: Arguments,
	data: bytes = b'',
	deserialiser: Deserialiser[T] = ...,
	cmd: Arguments, *,
	input: bytes = b'',
	deserialiser: Deserialiser[T],
	**kwargs: Any,
) -> T: ...


@overload
def exec_io(
	cmd: Arguments,
	data: bytes = b'',
	cmd: Arguments, *,
	input: bytes = b'',
	deserialiser: None = None,
	**kwargs: Any,
) -> int: ...


def exec_io(
	cmd: Arguments,
	data: bytes = b'',
	cmd: Arguments, *,
	input: bytes = b'',
	deserialiser: Deserialiser[Any]|None = None,
	**kwargs: Any,
) -> Any:
	"""
	Execute a command, handling output asynchronously

	If data is provided it will be fed to the process' stdin.
	If input is provided it will be fed to the process' stdin.
	If a deserialiser is provided it will be used to parse stdout data from the process.

	Stderr and stdout (if no deserialiser is provided) will be written to `sys.stderr` and
@@ -84,11 +96,16 @@ def exec_io(
	"""
	if deserialiser and 'stdout' in kwargs:
		raise TypeError("Cannot provide 'deserialiser' with 'stdout' argument")
	if data and 'stdin' in kwargs:
		raise TypeError("Cannot provide 'data' with 'stdin' argument")
	if "data" in kwargs:
		if input:
			raise TypeError("both 'input' and the deprecated 'data' keywords provided")
		warn(DeprecationWarning("the 'data' keyword argument is deprecated, use 'input'"))
		input = kwargs.pop("data")
	if input and 'stdin' in kwargs:
		raise TypeError("Cannot provide 'input' with 'stdin' argument")
	stdout: IO[str]|IO[bytes]|int = io.BytesIO() if deserialiser else kwargs.pop('stdout', sys.stdout)
	stderr: IO[str]|IO[bytes]|int = kwargs.pop('stderr', sys.stderr)
	proc = trio.run(_exec_io, cmd, data, stdout, stderr, kwargs)
	proc = trio.run(_exec_io, cmd, input, stdout, stderr, kwargs)
	if deserialiser:
		assert isinstance(stdout, io.BytesIO)
		return deserialiser(stdout.getbuffer())
@@ -102,14 +119,16 @@ async def _exec_io(
	stderr: IO[str]|IO[bytes]|int,
	kwargs: dict[str, Any],
) -> trio.Process:
	proc = await trio.open_process(
		[*coerce_args(cmd)],
	async with trio.open_nursery() as nursery:
		proc: trio.Process = await nursery.start(
			partial(
				trio.run_process, [*coerce_args(cmd)],
				stdin=PIPE if data else DEVNULL,
		stdout=PIPE,
		stderr=PIPE,
				stdout=PIPE, stderr=PIPE,
				check=False,
				**kwargs,
			),
		)
	async with proc, trio.open_nursery() as nursery:
		assert proc.stdout is not None and proc.stderr is not None
		nursery.start_soon(_passthru, proc.stderr, stderr)
		nursery.start_soon(_passthru, proc.stdout, stdout)
@@ -126,16 +145,14 @@ async def _passthru(in_stream: trio.abc.ReceiveStream, out_stream: IO[str]|IO[by
			out_stream = out_stream.fileno()
	except (OSError, AttributeError):
		# cannot get file descriptor, probably a memory buffer
		if isinstance(out_stream, io.BytesIO):
		if isinstance(out_stream, (BinaryIO, io.BytesIO)):
			async def write(data: bytes) -> None:
				assert isinstance(out_stream, io.BytesIO)
				assert isinstance(out_stream, (BinaryIO, io.BytesIO))
				out_stream.write(data)
		elif isinstance(out_stream, io.StringIO):
		else:
			async def write(data: bytes) -> None:
				assert isinstance(out_stream, io.StringIO)
				assert isinstance(out_stream, (TextIO, io.StringIO))
				out_stream.write(data.decode())
		else:
			raise TypeError(f"Unknown IO type: {type(out_stream)}")
	else:
		# is/has a file descriptor, out_stream is now that file descriptor
		async def write(data: bytes) -> None:
@@ -144,7 +161,7 @@ async def _passthru(in_stream: trio.abc.ReceiveStream, out_stream: IO[str]|IO[by
			remaining = len(data)
			while remaining:
				await trio.lowlevel.wait_writable(out_stream)
				written = os.write(out_stream, data)
				written = fdwrite(out_stream, data)
				data = data[written:]
				remaining -= written

@@ -153,3 +170,131 @@ async def _passthru(in_stream: trio.abc.ReceiveStream, out_stream: IO[str]|IO[by
		if not data:
			return
		await write(data)


class Executor(list[Argument]):
	"""
	Manage calling executables with composable argument lists

	Subclasses may add or amend the argument list just prior to execution by implementing
	`get_arguments`.

	Any arguments passed to the constructor will prefix the arguments passed when the object
	is called.
	"""

	T = TypeVar("T")
	E = TypeVar("E", bound="Executor")

	def __init__(self, *cmd: Argument):
		self[:] = cmd

	@overload
	def __call__(
		self,
		*args: Argument,
		input: str|bytes|SupportsBytes|None = ...,
		deserialiser: Deserialiser[T],
		query: Literal[False] = False,
		**kwargs: Any,
	) -> T: ...

	@overload
	def __call__(
		self,
		*args: Argument,
		input: str|bytes|SupportsBytes|None = ...,
		deserialiser: None = None,
		query: Literal[True],
		**kwargs: Any,
	) -> int: ...

	@overload
	def __call__(
		self,
		*args: Argument,
		input: str|bytes|SupportsBytes|None = ...,
		deserialiser: None = None,
		query: Literal[False] = False,
		**kwargs: Any,
	) -> None: ...

	def __call__(
		self,
		*args: Argument,
		input: str|bytes|SupportsBytes|None = None,
		deserialiser: Deserialiser[Any]|None = None,
		query: bool = False,
		**kwargs: Any,
	) -> Any:
		"""
		Execute the configure command with the given arguments

		Input:
			Any bytes passed as "input" will be fed into the process' stdin pipe.

		Output:
			If "deserialiser" is provided it will be called with a memoryview of a buffer
			containing any bytes from the process' stdout; whatever is returned by
			"deserialiser" will be returned.

			If "query" is true the return code of the process will be returned.

			Otherwise nothing is returned.

			Note that "deserialiser" and "query" are mutually exclusive; if debugging is
			enabled an AssertionError will be raised if both are non-None/non-False, otherwise
			"query" is ignored.

		Errors:
			If "query" is not true any non-zero return code will cause CalledProcessError to
			be raised.
		"""
		assert not deserialiser or not query

		data = (
			b"" if input is None else
			input.encode() if isinstance(input, str) else
			bytes(input)
		)
		cmd = self.get_arguments(
			[*self, *args], kwargs,
			has_input=bool(data),
			is_query=query,
			deserialiser=deserialiser,
		)

		if deserialiser:
			return exec_io(cmd, input=data, deserialiser=deserialiser, **kwargs)

		rcode = exec_io(cmd, input=data, **kwargs)
		if query:
			return rcode
		if 0 != rcode:
			raise CalledProcessError(rcode, ' '.join(coerce_args(cmd)))
		return None

	def get_arguments(
		self,
		cmd: Arguments,
		kwargs: MutableMapping[str, Any],
		has_input: bool,
		is_query: bool,
		deserialiser: Deserialiser[Any]|None,
	) -> Arguments:
		"""
		Override to amend command arguments and kwargs for exec_io() prior to execution
		"""
		return cmd

	def subcommand(self: E, *args: Argument) -> E:
		"""
		Return a new Executor instance of the same class with additional arguments appended

		The returned instance is created as a shallow copy; if attribute values need to be
		copied, subclasses must implement __copy__().
		(see https://docs.python.org/3/library/copy.html)
		"""
		new = copy(self)
		new.extend(args)
		return new
Loading
Loading