acupedia-ops/acupedia_ops/local/infrastructure.py

104 lines
2.6 KiB
Python

from __future__ import annotations
import shutil
from pathlib import Path
from typing import Sequence
from acupedia_ops.common.process import CommandResult, run_command
from acupedia_ops.local.workspace import LocalWorkspace
def _compose_command() -> list[str]:
if shutil.which("docker"):
result = run_command(
["docker", "compose", "version"],
capture=True,
check=False,
)
if result.returncode == 0:
return ["docker", "compose"]
if shutil.which("docker-compose"):
return ["docker-compose"]
raise RuntimeError(
"Docker Compose is required. Install Docker with the compose plugin "
"or docker-compose."
)
def _base(workspace: LocalWorkspace) -> list[str]:
if not workspace.infra.compose_file.exists():
raise FileNotFoundError(
"Local compose file not found: "
f"{workspace.infra.compose_file}. "
"Set ACUPEDIA_LOCAL_COMPOSE_FILE or configure config/local.yaml."
)
return [
*_compose_command(),
"--project-name",
workspace.infra.project_name,
"--file",
str(workspace.infra.compose_file),
]
def infra_up(
workspace: LocalWorkspace,
*,
build: bool = False,
services: Sequence[str] = (),
) -> None:
command = [*_base(workspace), "up", "--detach"]
if build:
command.append("--build")
command.extend(services)
run_command(command, cwd=workspace.infra.compose_file.parent)
def infra_down(
workspace: LocalWorkspace,
*,
volumes: bool = False,
remove_orphans: bool = True,
) -> None:
command = [*_base(workspace), "down"]
if volumes:
command.append("--volumes")
if remove_orphans:
command.append("--remove-orphans")
run_command(command, cwd=workspace.infra.compose_file.parent)
def infra_restart(
workspace: LocalWorkspace,
*,
services: Sequence[str] = (),
) -> None:
command = [*_base(workspace), "restart", *services]
run_command(command, cwd=workspace.infra.compose_file.parent)
def infra_status(workspace: LocalWorkspace) -> CommandResult:
return run_command(
[*_base(workspace), "ps"],
cwd=workspace.infra.compose_file.parent,
capture=True,
check=False,
)
def infra_logs(
workspace: LocalWorkspace,
*,
services: Sequence[str] = (),
follow: bool = False,
tail: int = 200,
) -> None:
command = [*_base(workspace), "logs", "--tail", str(tail)]
if follow:
command.append("--follow")
command.extend(services)
run_command(command, cwd=workspace.infra.compose_file.parent)