diff --git a/README.md b/README.md index 746f92f..8e8c443 100644 --- a/README.md +++ b/README.md @@ -259,4 +259,15 @@ python3 diff.py \ -o diff-report.txt \ --no-new-file-content \ --no-removed-file-content -``` \ No newline at end of file +``` +## Remote host preparation + +Remote dev/staging/prod hosts use Ansible via `ansible-runner`, with Docker Compose as the host-local runtime. Inventories support separate `backend`, `database`, `redis`, and `proxy` hosts or a single host in multiple groups. + +```bash +pip install -e ".[deployment]" +acupedia-ops remote preflight --env dev +acupedia-ops remote prepare --env dev +``` + +See `docs/remote-deployment.md` before configuring production hosts. Secrets must not be committed to inventory or environment configuration files. diff --git a/acupedia_ops/ansible/runner.py b/acupedia_ops/ansible/runner.py index 24c00e4..e9c3a82 100644 --- a/acupedia_ops/ansible/runner.py +++ b/acupedia_ops/ansible/runner.py @@ -1,14 +1,109 @@ from __future__ import annotations -from typing import Any + +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Callable, Mapping + from acupedia_ops.common.paths import ansible_root -def run_playbook(*, playbook: str, inventory: str, extra_vars: dict[str, Any] | None = None) -> None: + +@dataclass(frozen=True, slots=True) +class AnsibleRunResult: + status: str + rc: int + playbook: Path + inventory: Path + artifact_dir: Path | None + stats: Mapping[str, Any] + + +def _resolve_inventory(inventory: str | Path) -> Path: + candidate = Path(inventory).expanduser() + if candidate.exists(): + return candidate.resolve() + candidate = ansible_root() / "inventories" / str(inventory) + if candidate.exists(): + return candidate.resolve() + raise FileNotFoundError(f"Inventory not found: {candidate}") + + +def run_playbook( + *, + playbook: str | Path, + inventory: str | Path, + extra_vars: Mapping[str, Any] | None = None, + limit: str | None = None, + tags: str | None = None, + skip_tags: str | None = None, + check: bool = False, + verbosity: int = 0, + artifact_dir: Path | None = None, + envvars: Mapping[str, str] | None = None, + quiet: bool = False, + event_handler: Callable[[dict[str, Any]], bool | None] | None = None, + status_handler: Callable[[str, dict[str, Any]], None] | None = None, +) -> AnsibleRunResult: try: import ansible_runner except ImportError as exc: - raise RuntimeError('Install deployment support with: pip install -e ".[deployment]"') from exc - root = ansible_root(); inventory_path = root / "inventories" / inventory; playbook_path = root / "playbooks" / playbook - if not inventory_path.exists(): raise FileNotFoundError(f"Inventory not found: {inventory_path}") - if not playbook_path.exists(): raise FileNotFoundError(f"Playbook not found: {playbook_path}") - result = ansible_runner.run(private_data_dir=str(root), inventory=str(inventory_path), playbook=str(playbook_path), extravars=extra_vars or {}) - if result.rc != 0: raise RuntimeError(f"Ansible playbook failed with exit code {result.rc}: {playbook_path}") + raise RuntimeError( + 'Install deployment support with: pip install -e ".[deployment]"' + ) from exc + + root = ansible_root().resolve() + inventory_path = _resolve_inventory(inventory) + playbook_path = Path(playbook) + if not playbook_path.is_absolute(): + playbook_path = root / "playbooks" / playbook_path + playbook_path = playbook_path.resolve() + if not playbook_path.exists(): + raise FileNotFoundError(f"Playbook not found: {playbook_path}") + + cmdline_parts: list[str] = [] + if limit: + cmdline_parts += ["--limit", limit] + if tags: + cmdline_parts += ["--tags", tags] + if skip_tags: + cmdline_parts += ["--skip-tags", skip_tags] + if check: + cmdline_parts.append("--check") + if verbosity: + cmdline_parts.append("-" + "v" * min(verbosity, 4)) + + kwargs: dict[str, Any] = { + "private_data_dir": str(root), + "inventory": str(inventory_path), + "playbook": str(playbook_path), + "extravars": dict(extra_vars or {}), + "envvars": dict(envvars or {}), + "quiet": quiet, + } + if cmdline_parts: + kwargs["cmdline"] = " ".join(cmdline_parts) + if artifact_dir is not None: + artifact_dir.mkdir(parents=True, exist_ok=True) + kwargs["artifact_dir"] = str(artifact_dir) + if event_handler is not None: + kwargs["event_handler"] = event_handler + if status_handler is not None: + kwargs["status_handler"] = status_handler + + result = ansible_runner.run(**kwargs) + rc = int(result.rc or 0) + status = str(result.status or ("successful" if rc == 0 else "failed")) + resolved_artifact_dir = Path(result.artifact_dir) if getattr(result, "artifact_dir", None) else artifact_dir + run_result = AnsibleRunResult( + status=status, + rc=rc, + playbook=playbook_path, + inventory=inventory_path, + artifact_dir=resolved_artifact_dir, + stats=dict(getattr(result, "stats", {}) or {}), + ) + if rc != 0: + suffix = f"; artifacts: {resolved_artifact_dir}" if resolved_artifact_dir else "" + raise RuntimeError( + f"Ansible playbook failed with exit code {rc}: {playbook_path}{suffix}" + ) + return run_result diff --git a/acupedia_ops/cli.py b/acupedia_ops/cli.py index b97d321..69f761b 100644 --- a/acupedia_ops/cli.py +++ b/acupedia_ops/cli.py @@ -11,6 +11,7 @@ from acupedia_ops.common.paths import repo_root from acupedia_ops.data.image.clean_image_borders import process_path from acupedia_ops.deployment.backend import deploy_backend from acupedia_ops.deployment.database import deploy_database +from acupedia_ops.deployment.remote import preflight_remote, prepare_remote from acupedia_ops.deployment.gitea_runner import provision_runner, remove_runner from acupedia_ops.local.bootstrap import local_bootstrap from acupedia_ops.local.database import reset_local_database @@ -196,6 +197,17 @@ def _build_parser() -> argparse.ArgumentParser: database = deploy_sub.add_parser("database") database.add_argument("--env", required=True, choices=("dev", "staging", "prod")) + # Remote host lifecycle --------------------------------------------- + remote = subparsers.add_parser("remote") + remote_sub = remote.add_subparsers(dest="remote_command", required=True) + for remote_name in ("preflight", "prepare"): + remote_cmd = remote_sub.add_parser(remote_name) + remote_cmd.add_argument("--env", required=True, choices=("dev", "staging", "prod")) + remote_cmd.add_argument("--limit") + remote_cmd.add_argument("-v", "--verbose", action="count", default=0) + if remote_name == "prepare": + remote_cmd.add_argument("--check", action="store_true") + # Gitea runner lifecycle -------------------------------------------- runner = subparsers.add_parser("runner") runner_sub = runner.add_subparsers(dest="runner_command", required=True) @@ -393,6 +405,14 @@ def main() -> None: deploy_database(environment=args.env) return + if args.command == "remote" and args.remote_command == "preflight": + preflight_remote(environment=args.env, limit=args.limit, verbosity=args.verbose) + return + + if args.command == "remote" and args.remote_command == "prepare": + prepare_remote(environment=args.env, limit=args.limit, check=args.check, verbosity=args.verbose) + return + if args.command == "runner" and args.runner_command == "provision": token = args.registration_token if not token: diff --git a/acupedia_ops/deployment/gitea_runner.py b/acupedia_ops/deployment/gitea_runner.py index c158e5a..c6b2663 100644 --- a/acupedia_ops/deployment/gitea_runner.py +++ b/acupedia_ops/deployment/gitea_runner.py @@ -1,85 +1,45 @@ from __future__ import annotations -import os -import subprocess from pathlib import Path -from typing import Sequence +from typing import Any, Sequence + +import yaml + +from acupedia_ops.common.paths import repo_root +from acupedia_ops.ansible.runner import run_playbook def _repo_root() -> Path: - return Path(__file__).resolve().parents[2] + """Backward-compatible repository root helper.""" + return repo_root() -def _ansible_playbook() -> str: - return os.environ.get("ANSIBLE_PLAYBOOK_BIN", "ansible-playbook") +def _parse_extra_vars(values: Sequence[str]) -> dict[str, Any]: + result: dict[str, Any] = {} + for value in values: + parsed = yaml.safe_load(value) + if isinstance(parsed, dict): + result.update(parsed) + continue + if "=" not in value: + raise ValueError(f"Invalid --extra-var {value!r}; expected key=value or YAML mapping") + key, raw = value.split("=", 1) + result[key] = yaml.safe_load(raw) + return result -def provision_runner( - *, - inventory: Path, - registration_token: str, - limit: str | None = None, - extra_vars: Sequence[str] = (), - force_reregister: bool = False, -) -> None: - repo_root = _repo_root() - playbook = repo_root / "ansible" / "playbooks" / "gitea-runner.yml" - - command = [ - _ansible_playbook(), - "-i", - str(inventory), - str(playbook), - "--extra-vars", - f"gitea_runner_registration_token={registration_token}", - ] - +def provision_runner(*, inventory: Path, registration_token: str, limit: str | None = None, + extra_vars: Sequence[str] = (), force_reregister: bool = False) -> None: + variables = _parse_extra_vars(extra_vars) + variables["gitea_runner_registration_token"] = registration_token if force_reregister: - command.extend( - [ - "--extra-vars", - "gitea_runner_force_reregister=true", - ] - ) - - for value in extra_vars: - command.extend(["--extra-vars", value]) - - if limit: - command.extend(["--limit", limit]) - - subprocess.run(command, cwd=repo_root, check=True) + variables["gitea_runner_force_reregister"] = True + run_playbook(playbook="gitea-runner.yml", inventory=inventory, extra_vars=variables, limit=limit) -def remove_runner( - *, - inventory: Path, - limit: str | None = None, - remove_data: bool = False, - extra_vars: Sequence[str] = (), -) -> None: - repo_root = _repo_root() - playbook = repo_root / "ansible" / "playbooks" / "gitea-runner-remove.yml" - - command = [ - _ansible_playbook(), - "-i", - str(inventory), - str(playbook), - ] - +def remove_runner(*, inventory: Path, limit: str | None = None, remove_data: bool = False, + extra_vars: Sequence[str] = ()) -> None: + variables = _parse_extra_vars(extra_vars) if remove_data: - command.extend( - [ - "--extra-vars", - "gitea_runner_remove_data=true", - ] - ) - - for value in extra_vars: - command.extend(["--extra-vars", value]) - - if limit: - command.extend(["--limit", limit]) - - subprocess.run(command, cwd=repo_root, check=True) + variables["gitea_runner_remove_data"] = True + run_playbook(playbook="gitea-runner-remove.yml", inventory=inventory, extra_vars=variables, limit=limit) diff --git a/acupedia_ops/deployment/remote.py b/acupedia_ops/deployment/remote.py new file mode 100644 index 0000000..4b8bc7d --- /dev/null +++ b/acupedia_ops/deployment/remote.py @@ -0,0 +1,12 @@ +from __future__ import annotations + +from acupedia_ops.ansible.runner import AnsibleRunResult, run_playbook + + +def preflight_remote(*, environment: str, limit: str | None = None, verbosity: int = 0) -> AnsibleRunResult: + return run_playbook(playbook="preflight.yml", inventory=environment, limit=limit, verbosity=verbosity) + + +def prepare_remote(*, environment: str, limit: str | None = None, check: bool = False, + verbosity: int = 0) -> AnsibleRunResult: + return run_playbook(playbook="prepare.yml", inventory=environment, limit=limit, check=check, verbosity=verbosity) diff --git a/ansible/inventories/dev/group_vars/all.yml b/ansible/inventories/dev/group_vars/all.yml new file mode 100644 index 0000000..e5e6279 --- /dev/null +++ b/ansible/inventories/dev/group_vars/all.yml @@ -0,0 +1,3 @@ +--- +acupedia_environment: dev +acupedia_root: /opt/acupedia diff --git a/ansible/inventories/dev/hosts.yml b/ansible/inventories/dev/hosts.yml index f4c353e..47e7dbb 100644 --- a/ansible/inventories/dev/hosts.yml +++ b/ansible/inventories/dev/hosts.yml @@ -1,5 +1,23 @@ --- +# A single dev host may belong to every service group. Replace the example host +# and address before use. all: + hosts: + acupedia-dev: + ansible_host: 10.10.0.20 children: + docker_hosts: + hosts: + acupedia-dev: backend: - hosts: {} + hosts: + acupedia-dev: + database: + hosts: + acupedia-dev: + redis: + hosts: + acupedia-dev: + proxy: + hosts: + acupedia-dev: diff --git a/ansible/inventories/prod/group_vars/all.yml b/ansible/inventories/prod/group_vars/all.yml new file mode 100644 index 0000000..dc4d695 --- /dev/null +++ b/ansible/inventories/prod/group_vars/all.yml @@ -0,0 +1,3 @@ +--- +acupedia_environment: prod +acupedia_root: /opt/acupedia diff --git a/ansible/inventories/prod/hosts.yml b/ansible/inventories/prod/hosts.yml index f4c353e..00a7aca 100644 --- a/ansible/inventories/prod/hosts.yml +++ b/ansible/inventories/prod/hosts.yml @@ -1,5 +1,19 @@ --- +# Service groups are intentionally independent: production services may live +# on separate hosts. A host may also be placed in multiple groups. all: children: + docker_hosts: + children: + backend: {} + database: {} + redis: {} + proxy: {} backend: hosts: {} + database: + hosts: {} + redis: + hosts: {} + proxy: + hosts: {} diff --git a/ansible/inventories/staging/group_vars/all.yml b/ansible/inventories/staging/group_vars/all.yml new file mode 100644 index 0000000..4dc1c94 --- /dev/null +++ b/ansible/inventories/staging/group_vars/all.yml @@ -0,0 +1,3 @@ +--- +acupedia_environment: staging +acupedia_root: /opt/acupedia diff --git a/ansible/inventories/staging/hosts.yml b/ansible/inventories/staging/hosts.yml index f4c353e..7cb9cd9 100644 --- a/ansible/inventories/staging/hosts.yml +++ b/ansible/inventories/staging/hosts.yml @@ -1,5 +1,18 @@ --- +# Replace addresses/hosts with the staging topology. all: children: + docker_hosts: + children: + backend: {} + database: {} + redis: {} + proxy: {} backend: hosts: {} + database: + hosts: {} + redis: + hosts: {} + proxy: + hosts: {} diff --git a/ansible/playbooks/preflight.yml b/ansible/playbooks/preflight.yml new file mode 100644 index 0000000..e56b476 --- /dev/null +++ b/ansible/playbooks/preflight.yml @@ -0,0 +1,14 @@ +--- +- name: Validate AcuPedia remote hosts + hosts: docker_hosts + gather_facts: true + tasks: + - name: Verify supported operating system + ansible.builtin.assert: + that: + - ansible_os_family == "Debian" + fail_msg: "Initial AccuPedia remote setup supports Debian/Ubuntu hosts only." + - name: Verify privilege escalation + ansible.builtin.command: /usr/bin/true + become: true + changed_when: false diff --git a/ansible/playbooks/prepare.yml b/ansible/playbooks/prepare.yml new file mode 100644 index 0000000..33048fd --- /dev/null +++ b/ansible/playbooks/prepare.yml @@ -0,0 +1,7 @@ +--- +- name: Prepare AcuPedia Docker hosts + hosts: docker_hosts + gather_facts: true + roles: + - role: common + - role: docker diff --git a/ansible/roles/common/defaults/main.yml b/ansible/roles/common/defaults/main.yml new file mode 100644 index 0000000..361a24b --- /dev/null +++ b/ansible/roles/common/defaults/main.yml @@ -0,0 +1,15 @@ +--- +acupedia_system_user: acupedia +acupedia_system_group: acupedia +acupedia_root: /opt/acupedia +acupedia_directories: + - "{{ acupedia_root }}" + - "{{ acupedia_root }}/compose" + - "{{ acupedia_root }}/config" + - "{{ acupedia_root }}/data" + - "{{ acupedia_root }}/backups" + - "{{ acupedia_root }}/releases" +acupedia_common_packages: + - ca-certificates + - curl + - git diff --git a/ansible/roles/common/tasks/main.yml b/ansible/roles/common/tasks/main.yml new file mode 100644 index 0000000..492d708 --- /dev/null +++ b/ansible/roles/common/tasks/main.yml @@ -0,0 +1,40 @@ +--- +- name: Assert supported operating system + ansible.builtin.assert: + that: + - ansible_os_family == "Debian" + fail_msg: "Initial AccuPedia remote setup supports Debian/Ubuntu hosts only." + +- name: Install common packages + ansible.builtin.apt: + name: "{{ acupedia_common_packages }}" + state: present + update_cache: true + become: true + +- name: Create AcuPedia system group + ansible.builtin.group: + name: "{{ acupedia_system_group }}" + system: true + state: present + become: true + +- name: Create AcuPedia system user + ansible.builtin.user: + name: "{{ acupedia_system_user }}" + group: "{{ acupedia_system_group }}" + system: true + create_home: false + shell: /usr/sbin/nologin + state: present + become: true + +- name: Create AcuPedia directories + ansible.builtin.file: + path: "{{ item }}" + state: directory + owner: "{{ acupedia_system_user }}" + group: "{{ acupedia_system_group }}" + mode: "0750" + loop: "{{ acupedia_directories }}" + become: true diff --git a/ansible/roles/docker/defaults/main.yml b/ansible/roles/docker/defaults/main.yml new file mode 100644 index 0000000..ca8eb67 --- /dev/null +++ b/ansible/roles/docker/defaults/main.yml @@ -0,0 +1,6 @@ +--- +acupedia_docker_packages: + - docker.io + - docker-compose-v2 +acupedia_docker_service: docker +acupedia_docker_users: [] diff --git a/ansible/roles/docker/tasks/main.yml b/ansible/roles/docker/tasks/main.yml new file mode 100644 index 0000000..ff52b4b --- /dev/null +++ b/ansible/roles/docker/tasks/main.yml @@ -0,0 +1,28 @@ +--- +- name: Install Docker Engine and Compose plugin + ansible.builtin.apt: + name: "{{ acupedia_docker_packages }}" + state: present + update_cache: true + become: true + +- name: Enable and start Docker + ansible.builtin.service: + name: "{{ acupedia_docker_service }}" + enabled: true + state: started + become: true + +- name: Add explicitly configured users to Docker group + ansible.builtin.user: + name: "{{ item }}" + groups: docker + append: true + loop: "{{ acupedia_docker_users }}" + become: true + +- name: Verify Docker Compose plugin + ansible.builtin.command: docker compose version + register: acupedia_compose_version + changed_when: false + become: true diff --git a/docs/remote-deployment.md b/docs/remote-deployment.md new file mode 100644 index 0000000..ef77736 --- /dev/null +++ b/docs/remote-deployment.md @@ -0,0 +1,39 @@ +# Remote deployment foundation + +AccuPedia remote environments are provisioned with Ansible through `ansible-runner`. Docker Compose is the runtime deployment mechanism on each target host. + +## Topology + +Inventory groups describe service roles: `backend`, `database`, `redis`, and `proxy`. `docker_hosts` is the aggregate group used for common host preparation. A host can belong to one or several service groups, so dev can be a single machine while production can split services across machines. + +Compose is host-local. Do not assume Docker Compose service DNS works between separate servers; cross-host service endpoints must use private network DNS/IP addresses and appropriate access controls. + +## Initial setup + +Install deployment dependencies locally: + +```bash +pip install -e ".[deployment]" +``` + +Edit `ansible/inventories//hosts.yml`, including `ansible_user` or SSH variables as required. Do not commit passwords, tokens, database credentials, or application secrets to inventory. + +Validate SSH, facts, supported OS, and privilege escalation: + +```bash +acupedia-ops remote preflight --env dev +``` + +Prepare the hosts idempotently: + +```bash +acupedia-ops remote prepare --env dev +``` + +Use `--limit ` to restrict execution and `--check` with `prepare` for Ansible check mode. `-v` through `-vvvv` increases Ansible verbosity. + +## Host state created by prepare + +The initial implementation supports Debian/Ubuntu hosts. It installs common packages, creates the `acupedia` system account and `/opt/acupedia` hierarchy, installs Docker Engine from the distribution packages, installs the Docker Compose v2 plugin, enables Docker, and verifies `docker compose`. + +The application/database/Redis/proxy Compose deployments are deliberately not part of this foundation and remain separate subsequent roles. diff --git a/seaweedfs.yml b/seaweedfs.yml new file mode 100644 index 0000000..433e002 --- /dev/null +++ b/seaweedfs.yml @@ -0,0 +1,59 @@ +version: '3.9' + +services: + master: + image: chrislusf/seaweedfs # use a remote image + ports: + - 9333:9333 + - 19333:19333 + - 9324:9324 + command: 'master -ip=master -ip.bind=0.0.0.0 -metricsPort=9324' + volume: + image: chrislusf/seaweedfs # use a remote image + ports: + - 8080:8080 + - 18080:18080 + - 9325:9325 + command: 'volume -ip=volume -master="master:9333" -ip.bind=0.0.0.0 -port=8080 -metricsPort=9325' + depends_on: + - master + filer: + image: chrislusf/seaweedfs # use a remote image + ports: + - 8888:8888 + - 18888:18888 + - 9326:9326 + command: 'filer -ip=filer -master="master:9333" -ip.bind=0.0.0.0 -metricsPort=9326' + tty: true + stdin_open: true + depends_on: + - master + - volume + s3: + image: chrislusf/seaweedfs # use a remote image + ports: + - 8333:8333 + - 9327:9327 + command: 's3 -filer="filer:8888" -ip.bind=0.0.0.0 -metricsPort=9327' + depends_on: + - master + - volume + - filer + webdav: + image: chrislusf/seaweedfs # use a remote image + ports: + - 7333:7333 + command: 'webdav -filer="filer:8888"' + depends_on: + - master + - volume + - filer + admin: + image: chrislusf/seaweedfs:dev # use a remote dev image + ports: + - 23646:23646 + command: 'admin -master=master:9333' + depends_on: + - master + - volume + - filer \ No newline at end of file