karl/app/services/containers.py
2025-10-12 20:30:43 +02:00

30 lines
931 B
Python

import docker
from docker.models.containers import Container
from injectable import injectable
from app.model.containers import Tree, Compose, SimpleContainer
@injectable(singleton=True)
class DockerService:
def __init__(self):
self._client = docker.from_env()
self._tree = self._init_tree()
def _init_tree(self) -> Tree:
tree = Tree()
container: Container
for container in self._client.containers.list():
labels = container.labels
working_dir = labels.get("com.docker.compose.project.working_dir")
if working_dir:
if tree.composes.get(working_dir) is None:
tree.composes[working_dir] = Compose(working_dir)
tree.composes[working_dir].containers.append(SimpleContainer.from_container(container))
else:
tree.containers.append(SimpleContainer.from_container(container))
return tree
@property
def tree(self) -> Tree:
return self._tree