Skip to content

Commit

Permalink
fix: Re-use existing bridge network when possible (#42)
Browse files Browse the repository at this point in the history
* πŸ› Re-use existing bridge network when possible

* πŸ₯…  Narrow exception handling

Co-authored-by: Mathieu Lemay <[email protected]>

* πŸ‘½οΈ Update imports

---------

Co-authored-by: Mathieu Lemay <[email protected]>
  • Loading branch information
pboling and mathieu-lemay authored Dec 22, 2024
1 parent f9c53a1 commit 0a1c317
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions pipeline_runner/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
import os
import sys
from abc import ABC, abstractmethod
from http import HTTPStatus
from time import time as ts

import docker # type: ignore[import-untyped]
from docker.errors import APIError # type: ignore[import-untyped]
from docker.models.networks import Network # type: ignore[import-untyped]

from . import utils
Expand Down Expand Up @@ -169,7 +171,7 @@ def run(self) -> int | None: # noqa: C901, PLR0915
self._step.services.append("docker")

image = self._get_image()
network = self._create_network()
network = self._get_network()
environment = self._get_step_env_vars()

services_manager = ServicesManager(
Expand Down Expand Up @@ -252,8 +254,21 @@ def _get_image(self) -> Image:

return Image(name=DEFAULT_IMAGE)

def _create_network(self) -> Network:
def _get_network(self) -> Network:
name = f"{self._ctx.pipeline_ctx.project_metadata.slug}-network"
try:
bridge_network = self._docker_client.networks.get(name)
except APIError as e:
if e.status_code != HTTPStatus.NOT_FOUND:
raise

logger.debug("Creating network %s.", name)
bridge_network = self._create_network(name)
else:
logger.debug("Network %s already exists.", name)
return bridge_network

def _create_network(self, name: str) -> Network:
return self._docker_client.networks.create(name, driver="bridge")

def _get_step_env_vars(self) -> dict[str, str]:
Expand Down

0 comments on commit 0a1c317

Please sign in to comment.