|
| 1 | +from dataclasses import dataclass |
| 2 | +import os |
| 3 | +import subprocess |
| 4 | +import time |
| 5 | +from typing import List, Optional |
| 6 | +from urllib.request import urlopen |
| 7 | +from . import COMPOSE_FILE |
| 8 | +import json |
| 9 | + |
| 10 | +def restart_docker(): |
| 11 | + docker = DockerManager(COMPOSE_FILE) |
| 12 | + # Restart all containers. |
| 13 | + docker.compose("restart") |
| 14 | + # Ensure all nodes are reachable from outside. |
| 15 | + containers = docker.list_containers() |
| 16 | + for container in containers: |
| 17 | + info = json.loads(docker._execute_command("docker", "inspect", container.name)) |
| 18 | + try: |
| 19 | + port = info[0]['NetworkSettings']['Ports']['80/tcp'][0]['HostPort'] |
| 20 | + except KeyError: |
| 21 | + continue |
| 22 | + ping("127.0.0.1:{}".format(port)) |
| 23 | + # TODO: ping endpoint needs to wait for database startup & leader election |
| 24 | + time.sleep(2) |
| 25 | + |
| 26 | +def ping(host): |
| 27 | + tries = 0 |
| 28 | + while tries < 10: |
| 29 | + tries += 1 |
| 30 | + try: |
| 31 | + print(f"Ping Server at {host}") |
| 32 | + urlopen(f"http://{host}/v1/ping") |
| 33 | + print(f"Server up after {tries} tries") |
| 34 | + break |
| 35 | + except Exception: |
| 36 | + print("Server down") |
| 37 | + time.sleep(3) |
| 38 | + else: |
| 39 | + raise Exception(f"Server at {host} not responding") |
| 40 | + |
| 41 | +@dataclass |
| 42 | +class DockerContainer: |
| 43 | + """Represents a Docker container with its basic properties.""" |
| 44 | + id: str |
| 45 | + name: str |
| 46 | + |
| 47 | +class DockerManager: |
| 48 | + """Manages all Docker and Docker Compose operations.""" |
| 49 | + |
| 50 | + def __init__(self, compose_file: str, **config): |
| 51 | + self.compose_file = compose_file |
| 52 | + self.network_name = config.get('network_name') or \ |
| 53 | + os.getenv('DOCKER_NETWORK_NAME', 'private_spacetime_cloud') |
| 54 | + self.control_db_container = config.get('control_db_container') or \ |
| 55 | + os.getenv('CONTROL_DB_CONTAINER', 'node') |
| 56 | + self.spacetime_cli_bin = config.get('spacetime_cli_bin') or \ |
| 57 | + os.getenv('SPACETIME_CLI_BIN', 'spacetimedb-cloud') |
| 58 | + |
| 59 | + def _execute_command(self, *args: str) -> str: |
| 60 | + """Execute a Docker command and return its output.""" |
| 61 | + try: |
| 62 | + result = subprocess.run( |
| 63 | + args, |
| 64 | + capture_output=True, |
| 65 | + text=True, |
| 66 | + check=True |
| 67 | + ) |
| 68 | + return result.stdout.strip() |
| 69 | + except subprocess.CalledProcessError as e: |
| 70 | + print(f"Command failed: {e.stderr}") |
| 71 | + raise |
| 72 | + except Exception as e: |
| 73 | + print(f"Unexpected error: {str(e)}") |
| 74 | + raise |
| 75 | + |
| 76 | + def compose(self, *args: str) -> str: |
| 77 | + """Execute a docker-compose command.""" |
| 78 | + return self._execute_command("docker", "compose", "-f", self.compose_file, *args) |
| 79 | + |
| 80 | + def list_containers(self) -> List[DockerContainer]: |
| 81 | + """List all containers and return as DockerContainer objects.""" |
| 82 | + output = self.compose("ps", "-a", "--format", "{{.ID}} {{.Name}}") |
| 83 | + containers = [] |
| 84 | + for line in output.splitlines(): |
| 85 | + if line.strip(): |
| 86 | + container_id, name = line.split(maxsplit=1) |
| 87 | + containers.append(DockerContainer(id=container_id, name=name)) |
| 88 | + return containers |
| 89 | + |
| 90 | + def get_container_by_name(self, name: str) -> Optional[DockerContainer]: |
| 91 | + """Find a container by name pattern.""" |
| 92 | + return next( |
| 93 | + (c for c in self.list_containers() if name in c.name), |
| 94 | + None |
| 95 | + ) |
| 96 | + |
| 97 | + def kill_container(self, container_id: str): |
| 98 | + """Kill a container by ID.""" |
| 99 | + print(f"Killing container {container_id}") |
| 100 | + self._execute_command("docker", "kill", container_id) |
| 101 | + |
| 102 | + def start_container(self, container_id: str): |
| 103 | + """Start a container by ID.""" |
| 104 | + print(f"Starting container {container_id}") |
| 105 | + self._execute_command("docker", "start", container_id) |
| 106 | + |
| 107 | + def disconnect_container(self, container_id: str): |
| 108 | + """Disconnect a container from the network.""" |
| 109 | + print(f"Disconnecting container {container_id}") |
| 110 | + self._execute_command( |
| 111 | + "docker", "network", "disconnect", |
| 112 | + self.network_name, container_id |
| 113 | + ) |
| 114 | + print(f"Disconnected container {container_id}") |
| 115 | + |
| 116 | + def connect_container(self, container_id: str): |
| 117 | + """Connect a container to the network.""" |
| 118 | + print(f"Connecting container {container_id}") |
| 119 | + self._execute_command( |
| 120 | + "docker", "network", "connect", |
| 121 | + self.network_name, container_id |
| 122 | + ) |
| 123 | + print(f"Connected container {container_id}") |
| 124 | + |
| 125 | + def generate_root_token(self) -> str: |
| 126 | + """Generate a root token using spacetimedb-cloud.""" |
| 127 | + return self.compose( |
| 128 | + "exec", self.control_db_container, self.spacetime_cli_bin, "token", "gen", |
| 129 | + "--subject=placeholder-node-id", |
| 130 | + "--jwt-priv-key", "/etc/spacetimedb/keys/id_ecdsa").split('|')[1] |
0 commit comments