def docker_network(self) -> Iterator[Network]:
"""
Return a Docker network.
"""
client = docker.from_env(version='auto')
ipam_pool = docker.types.IPAMPool(
subnet='172.28.0.0/16',
iprange='172.28.0.0/24',
gateway='172.28.0.254',
)
# We use the default container prefix so that the
# ``minidcos docker clean`` command cleans this up.
prefix = Docker().container_name_prefix
random = uuid.uuid4()
name = '{prefix}-network-{random}'.format(prefix=prefix, random=random)
network = client.networks.create(
name=name,
driver='bridge',
ipam=docker.types.IPAMConfig(pool_configs=[ipam_pool]),
attachable=False,
)
try:
yield network
finally:
network.remove()
def ensure_local_net(
network_name: str = DOCKER_STARCRAFT_NETWORK,
subnet_cidr: str = SUBNET_CIDR
) -> None:
"""
Create docker local net if not found.
:raises docker.errors.APIError
"""
logger.info(f"checking whether docker has network {network_name}")
ipam_pool = docker.types.IPAMPool(subnet=subnet_cidr)
ipam_config = docker.types.IPAMConfig(pool_configs=[ipam_pool])
networks = docker_client.networks.list(names=DOCKER_STARCRAFT_NETWORK)
output = networks[0].short_id if networks else None
if not output:
logger.info("network not found, creating ...")
output = docker_client.networks.create(DOCKER_STARCRAFT_NETWORK, ipam=ipam_config).short_id
logger.debug(f"docker network id: {output}")