reworked service mapping

This commit is contained in:
John Lancaster
2024-05-27 18:33:41 -05:00
parent f1ab1ce6d0
commit fc15a24ab6

View File

@@ -12,31 +12,35 @@ def manage_containers(project: str, services: list[str]):
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
client = docker.from_env() client = docker.from_env()
containers: list[Container] = [
c
for c in client.containers.list()
if c.labels['com.docker.compose.project'] == project
and c.labels['com.docker.compose.service'] in services
]
try: try:
project_containers = (
c
for c in client.containers.list()
if c.labels['com.docker.compose.project'] == project
)
service_dict = {
c.labels['com.docker.compose.service']: c for c in project_containers
}
containers: list[Container] = [service_dict[s] for s in services]
except Exception as e:
raise e
else:
# Start the containers # Start the containers
for container in containers: for container in containers:
container.stop() container.stop()
logger.info(f'Stopped container [blue]{container.name}[/]') logger.info(f'Stopped container [blue]{container.name}[/]')
# Execute the wrapped function try:
result = func(*args, **kwargs) # Execute the wrapped function
return func(*args, **kwargs)
except Exception as e: except Exception as e:
# Handle exceptions and ensure containers are stopped # Handle exceptions and ensure containers are stopped
raise e raise e
else: finally:
return result # Stop the containers
finally: for container in containers:
# Stop the containers container.start()
for container in containers: logger.info(f'Started container [blue]{container.name}[/]')
container.start()
logger.info(f'Started container [blue]{container.name}[/]')
return wrapper return wrapper