setting up deployment

This commit is contained in:
Amit Salunke 2026-09-25 14:48:32 +05:30
parent 90eb11bd2f
commit 2a16c328cb
19 changed files with 441 additions and 81 deletions

View File

@ -259,4 +259,15 @@ python3 diff.py \
-o diff-report.txt \ -o diff-report.txt \
--no-new-file-content \ --no-new-file-content \
--no-removed-file-content --no-removed-file-content
``` ```
## 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.

View File

@ -1,14 +1,109 @@
from __future__ import annotations 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 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: try:
import ansible_runner import ansible_runner
except ImportError as exc: except ImportError as exc:
raise RuntimeError('Install deployment support with: pip install -e ".[deployment]"') from exc raise RuntimeError(
root = ansible_root(); inventory_path = root / "inventories" / inventory; playbook_path = root / "playbooks" / playbook 'Install deployment support with: pip install -e ".[deployment]"'
if not inventory_path.exists(): raise FileNotFoundError(f"Inventory not found: {inventory_path}") ) from exc
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 {}) root = ansible_root().resolve()
if result.rc != 0: raise RuntimeError(f"Ansible playbook failed with exit code {result.rc}: {playbook_path}") 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

View File

@ -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.data.image.clean_image_borders import process_path
from acupedia_ops.deployment.backend import deploy_backend from acupedia_ops.deployment.backend import deploy_backend
from acupedia_ops.deployment.database import deploy_database 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.deployment.gitea_runner import provision_runner, remove_runner
from acupedia_ops.local.bootstrap import local_bootstrap from acupedia_ops.local.bootstrap import local_bootstrap
from acupedia_ops.local.database import reset_local_database 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 = deploy_sub.add_parser("database")
database.add_argument("--env", required=True, choices=("dev", "staging", "prod")) 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 -------------------------------------------- # Gitea runner lifecycle --------------------------------------------
runner = subparsers.add_parser("runner") runner = subparsers.add_parser("runner")
runner_sub = runner.add_subparsers(dest="runner_command", required=True) runner_sub = runner.add_subparsers(dest="runner_command", required=True)
@ -393,6 +405,14 @@ def main() -> None:
deploy_database(environment=args.env) deploy_database(environment=args.env)
return 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": if args.command == "runner" and args.runner_command == "provision":
token = args.registration_token token = args.registration_token
if not token: if not token:

View File

@ -1,85 +1,45 @@
from __future__ import annotations from __future__ import annotations
import os
import subprocess
from pathlib import Path 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: def _repo_root() -> Path:
return Path(__file__).resolve().parents[2] """Backward-compatible repository root helper."""
return repo_root()
def _ansible_playbook() -> str: def _parse_extra_vars(values: Sequence[str]) -> dict[str, Any]:
return os.environ.get("ANSIBLE_PLAYBOOK_BIN", "ansible-playbook") 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( def provision_runner(*, inventory: Path, registration_token: str, limit: str | None = None,
*, extra_vars: Sequence[str] = (), force_reregister: bool = False) -> None:
inventory: Path, variables = _parse_extra_vars(extra_vars)
registration_token: str, variables["gitea_runner_registration_token"] = registration_token
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}",
]
if force_reregister: if force_reregister:
command.extend( variables["gitea_runner_force_reregister"] = True
[ run_playbook(playbook="gitea-runner.yml", inventory=inventory, extra_vars=variables, limit=limit)
"--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)
def remove_runner( def remove_runner(*, inventory: Path, limit: str | None = None, remove_data: bool = False,
*, extra_vars: Sequence[str] = ()) -> None:
inventory: Path, variables = _parse_extra_vars(extra_vars)
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),
]
if remove_data: if remove_data:
command.extend( variables["gitea_runner_remove_data"] = True
[ run_playbook(playbook="gitea-runner-remove.yml", inventory=inventory, extra_vars=variables, limit=limit)
"--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)

View File

@ -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)

View File

@ -0,0 +1,3 @@
---
acupedia_environment: dev
acupedia_root: /opt/acupedia

View File

@ -1,5 +1,23 @@
--- ---
# A single dev host may belong to every service group. Replace the example host
# and address before use.
all: all:
hosts:
acupedia-dev:
ansible_host: 10.10.0.20
children: children:
docker_hosts:
hosts:
acupedia-dev:
backend: backend:
hosts: {} hosts:
acupedia-dev:
database:
hosts:
acupedia-dev:
redis:
hosts:
acupedia-dev:
proxy:
hosts:
acupedia-dev:

View File

@ -0,0 +1,3 @@
---
acupedia_environment: prod
acupedia_root: /opt/acupedia

View File

@ -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: all:
children: children:
docker_hosts:
children:
backend: {}
database: {}
redis: {}
proxy: {}
backend: backend:
hosts: {} hosts: {}
database:
hosts: {}
redis:
hosts: {}
proxy:
hosts: {}

View File

@ -0,0 +1,3 @@
---
acupedia_environment: staging
acupedia_root: /opt/acupedia

View File

@ -1,5 +1,18 @@
--- ---
# Replace addresses/hosts with the staging topology.
all: all:
children: children:
docker_hosts:
children:
backend: {}
database: {}
redis: {}
proxy: {}
backend: backend:
hosts: {} hosts: {}
database:
hosts: {}
redis:
hosts: {}
proxy:
hosts: {}

View File

@ -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

View File

@ -0,0 +1,7 @@
---
- name: Prepare AcuPedia Docker hosts
hosts: docker_hosts
gather_facts: true
roles:
- role: common
- role: docker

View File

@ -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

View File

@ -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

View File

@ -0,0 +1,6 @@
---
acupedia_docker_packages:
- docker.io
- docker-compose-v2
acupedia_docker_service: docker
acupedia_docker_users: []

View File

@ -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

39
docs/remote-deployment.md Normal file
View File

@ -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/<environment>/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 <host-or-group>` 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.

59
seaweedfs.yml Normal file
View File

@ -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