From 4ad259dd89bd7af971b29e19a44a7a00999a8945 Mon Sep 17 00:00:00 2001 From: Rasmus Larsen Date: Wed, 2 Dec 2026 14:51:56 +0000 Subject: [PATCH 1/2] Add declarative OpenTofu/Ansible infra and wire gatewayd into gateway-reconcile --- .gitignore | 6 + docs/operations.md | 29 +- infra/ansible/README.md | 46 +++ infra/ansible/ansible.cfg | 11 + .../hetzner.example/group_vars/all.yml | 59 ++++ .../inventories/hetzner.example/hosts.yml | 18 ++ .../ucloud.example/group_vars/all.yml | 26 ++ .../inventories/ucloud.example/hosts.yml | 16 + infra/ansible/roles/common/defaults/main.yml | 28 ++ infra/ansible/roles/common/handlers/main.yml | 9 + infra/ansible/roles/common/tasks/main.yml | 74 +++++ infra/ansible/roles/gateway/defaults/main.yml | 33 ++ infra/ansible/roles/gateway/handlers/main.yml | 11 + infra/ansible/roles/gateway/tasks/main.yml | 287 ++++++++++++++++++ .../templates/gatewayd-upstream.conf.j2 | 3 + .../roles/gateway/templates/provider.conf.j2 | 2 + .../gateway/templates/registry-volume.conf.j2 | 5 + .../ucloud-sandbox-gatewayd.service.j2 | 23 ++ .../roles/gateway/templates/ucloud.conf.j2 | 6 + .../roles/gateway_ingress/defaults/main.yml | 5 + .../roles/gateway_ingress/tasks/main.yml | 45 +++ .../roles/gateway_nat/defaults/main.yml | 3 + .../roles/gateway_nat/handlers/main.yml | 9 + .../ansible/roles/gateway_nat/tasks/main.yml | 38 +++ .../templates/ucloud-sandboxes-nat.j2 | 31 ++ .../roles/observability/defaults/main.yml | 25 ++ .../roles/observability/handlers/main.yml | 14 + .../roles/observability/tasks/main.yml | 56 ++++ .../ucloud-telemetry-collector.service.j2 | 17 ++ .../ucloud-telemetry-grafana.service.j2 | 18 ++ .../ucloud-telemetry-tempo.service.j2 | 17 ++ .../ucloud-telemetry-victoria.service.j2 | 17 ++ infra/ansible/roles/ops/defaults/main.yml | 15 + infra/ansible/roles/ops/handlers/main.yml | 4 + infra/ansible/roles/ops/tasks/main.yml | 139 +++++++++ ...loud-sandbox-backup-chunk-index.service.j2 | 10 + .../ucloud-sandbox-backup-gateway.service.j2 | 10 + .../ucloud-sandbox-ops-watch.service.j2 | 10 + infra/ansible/roles/store/defaults/main.yml | 15 + infra/ansible/roles/store/handlers/main.yml | 14 + infra/ansible/roles/store/tasks/main.yml | 154 ++++++++++ .../templates/ucloud-chunk-index.service.j2 | 22 ++ .../templates/ucloud-chunk-serve.service.j2 | 22 ++ .../templates/ucloud-chunk-store.service.j2 | 22 ++ .../templates/ucloud-package-cache.service.j2 | 21 ++ infra/ansible/site.yml | 30 ++ infra/ansible/upgrade.yml | 34 +++ infra/hetzner/.terraform.lock.hcl | 23 ++ infra/hetzner/README.md | 25 ++ infra/hetzner/main.tf | 179 +++++++++++ infra/hetzner/outputs.tf | 39 +++ infra/hetzner/terraform.tfvars.example | 22 ++ infra/hetzner/variables.tf | 113 +++++++ infra/hetzner/versions.tf | 19 ++ sandboxes/deploy.py | 1 + sandboxes/systemd.py | 31 +- .../systemd/ucloud-sandbox-gatewayd.service | 23 ++ scripts/release/build_release.py | 133 ++++++++ tests/test_systemd.py | 34 +++ 59 files changed, 2134 insertions(+), 17 deletions(-) create mode 100644 infra/ansible/README.md create mode 100644 infra/ansible/ansible.cfg create mode 100644 infra/ansible/inventories/hetzner.example/group_vars/all.yml create mode 100644 infra/ansible/inventories/hetzner.example/hosts.yml create mode 100644 infra/ansible/inventories/ucloud.example/group_vars/all.yml create mode 100644 infra/ansible/inventories/ucloud.example/hosts.yml create mode 100644 infra/ansible/roles/common/defaults/main.yml create mode 100644 infra/ansible/roles/common/handlers/main.yml create mode 100644 infra/ansible/roles/common/tasks/main.yml create mode 100644 infra/ansible/roles/gateway/defaults/main.yml create mode 100644 infra/ansible/roles/gateway/handlers/main.yml create mode 100644 infra/ansible/roles/gateway/tasks/main.yml create mode 100644 infra/ansible/roles/gateway/templates/gatewayd-upstream.conf.j2 create mode 100644 infra/ansible/roles/gateway/templates/provider.conf.j2 create mode 100644 infra/ansible/roles/gateway/templates/registry-volume.conf.j2 create mode 100644 infra/ansible/roles/gateway/templates/ucloud-sandbox-gatewayd.service.j2 create mode 100644 infra/ansible/roles/gateway/templates/ucloud.conf.j2 create mode 100644 infra/ansible/roles/gateway_ingress/defaults/main.yml create mode 100644 infra/ansible/roles/gateway_ingress/tasks/main.yml create mode 100644 infra/ansible/roles/gateway_nat/defaults/main.yml create mode 100644 infra/ansible/roles/gateway_nat/handlers/main.yml create mode 100644 infra/ansible/roles/gateway_nat/tasks/main.yml create mode 100644 infra/ansible/roles/gateway_nat/templates/ucloud-sandboxes-nat.j2 create mode 100644 infra/ansible/roles/observability/defaults/main.yml create mode 100644 infra/ansible/roles/observability/handlers/main.yml create mode 100644 infra/ansible/roles/observability/tasks/main.yml create mode 100644 infra/ansible/roles/observability/templates/ucloud-telemetry-collector.service.j2 create mode 100644 infra/ansible/roles/observability/templates/ucloud-telemetry-grafana.service.j2 create mode 100644 infra/ansible/roles/observability/templates/ucloud-telemetry-tempo.service.j2 create mode 100644 infra/ansible/roles/observability/templates/ucloud-telemetry-victoria.service.j2 create mode 100644 infra/ansible/roles/ops/defaults/main.yml create mode 100644 infra/ansible/roles/ops/handlers/main.yml create mode 100644 infra/ansible/roles/ops/tasks/main.yml create mode 100644 infra/ansible/roles/ops/templates/ucloud-sandbox-backup-chunk-index.service.j2 create mode 100644 infra/ansible/roles/ops/templates/ucloud-sandbox-backup-gateway.service.j2 create mode 100644 infra/ansible/roles/ops/templates/ucloud-sandbox-ops-watch.service.j2 create mode 100644 infra/ansible/roles/store/defaults/main.yml create mode 100644 infra/ansible/roles/store/handlers/main.yml create mode 100644 infra/ansible/roles/store/tasks/main.yml create mode 100644 infra/ansible/roles/store/templates/ucloud-chunk-index.service.j2 create mode 100644 infra/ansible/roles/store/templates/ucloud-chunk-serve.service.j2 create mode 100644 infra/ansible/roles/store/templates/ucloud-chunk-store.service.j2 create mode 100644 infra/ansible/roles/store/templates/ucloud-package-cache.service.j2 create mode 100644 infra/ansible/site.yml create mode 100644 infra/ansible/upgrade.yml create mode 100644 infra/hetzner/.terraform.lock.hcl create mode 100644 infra/hetzner/README.md create mode 100644 infra/hetzner/main.tf create mode 100644 infra/hetzner/outputs.tf create mode 100644 infra/hetzner/terraform.tfvars.example create mode 100644 infra/hetzner/variables.tf create mode 100644 infra/hetzner/versions.tf create mode 100644 sandboxes/systemd/ucloud-sandbox-gatewayd.service create mode 100644 scripts/release/build_release.py diff --git a/.gitignore b/.gitignore index 2824cdf3..643635ae 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,12 @@ target/ # Local secrets and run output .env .hetzner/ +.deploy/ +**/.terraform/ +*.tfstate +*.tfstate.* +*.tfvars +*.retry logs/ inspect-logs/ diff --git a/docs/operations.md b/docs/operations.md index 2e9d9674..a6816c66 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -134,9 +134,32 @@ sudo python -m sandboxes.systemd gateway-reconcile \ ``` The one convergence routine for every provider: enables timers and optional -services by configuration, restarts everything in order and waits for health. -Run it after any change to the wheel, units or `deployment.json`. Hosts never -upgrade OS packages unattended; package updates are a deliberate task. +services by configuration (including `ucloud-sandbox-gatewayd.service` when +`/usr/local/libexec/ucloud-gatewayd` and its unit are installed), restarts +everything in order and waits for health. Run it after any change to the wheel, +units or `deployment.json`. Hosts never upgrade OS packages unattended; package +updates are a deliberate task. + +## Declarative infrastructure + +Permanent host infrastructure is split into two layers under `infra/`: + +- **Cloud resources (`infra/hetzner/`):** OpenTofu module managing the Hetzner + private network, egress route, SSH key, firewalls, protected Primary IPv4s, + persistent chunk-store volume, and Gateway/Store VMs (default `cpx32`). + UCloud continues provisioning VMs with `sandboxes submit-vm`; future backends + add either an OpenTofu module or existing SSH hosts. +- **Host convergence (`infra/ansible/`):** Provider-agnostic Ansible playbooks + (`site.yml`, `upgrade.yml`) and roles (`common`, `gateway`, `store`, + `observability`, `ops`, plus optional `gateway_nat` and `gateway_ingress` + overlays toggled via inventory vars). Uses only `ansible.builtin.*` modules + and keeps environment inventories outside Git under `.deploy//`. +- **Release builds (`scripts/release/build_release.py`):** Builds the Python + wheel, `ucloud-gatewayd`, and `ucloud-chunk-serve` into one digest-pinned + directory consumed by `ansible-playbook upgrade.yml -e release_dir=...`. + +See `infra/hetzner/README.md` and `infra/ansible/README.md` for usage and +example inventories (`hetzner.example`, `ucloud.example`). ## Releases diff --git a/infra/ansible/README.md b/infra/ansible/README.md new file mode 100644 index 00000000..dc822dc3 --- /dev/null +++ b/infra/ansible/README.md @@ -0,0 +1,46 @@ +# Provider-Agnostic Host Convergence (Ansible) + +Converges the permanent **gateway** and **store** hosts across Hetzner Cloud, +UCloud, or any SSH-reachable Ubuntu VM using built-in Ansible modules only (no +external Galaxy collections required). + +Ephemeral sandbox workers and builders remain managed by the gateway autoscaler +via snapshot + digest-pinned bundles. + +## Quick Start + +1. Copy the matching example inventory into a gitignored `.deploy//inventory/` directory: + + ```bash + cp -r infra/ansible/inventories/hetzner.example .deploy/prod/inventory + # Edit .deploy/prod/inventory/hosts.yml and group_vars/all.yml + ``` + +2. Dry-run with full diff before touching production: + + ```bash + cd infra/ansible + ansible-playbook -i ../../.deploy/prod/inventory/hosts.yml site.yml --check --diff + ``` + +3. Apply convergence: + + ```bash + ansible-playbook -i ../../.deploy/prod/inventory/hosts.yml site.yml + ``` + +## Fast Application Upgrades + +Build a versioned release directory (wheel + `ucloud-gatewayd` + `ucloud-chunk-serve`): + +```bash +uv run python scripts/release/build_release.py --out dist/releases/candidate +``` + +Then roll out to Gateway and Store in one command: + +```bash +cd infra/ansible +ansible-playbook -i ../../.deploy/prod/inventory/hosts.yml upgrade.yml \ + -e release_dir=../../dist/releases/candidate +``` diff --git a/infra/ansible/ansible.cfg b/infra/ansible/ansible.cfg new file mode 100644 index 00000000..954106dc --- /dev/null +++ b/infra/ansible/ansible.cfg @@ -0,0 +1,11 @@ +[defaults] +roles_path = roles +host_key_checking = True +retry_files_enabled = False +interpreter_python = auto_silent +stdout_callback = default +result_format = yaml + +[ssh_connection] +pipelining = True +ssh_args = -o ControlMaster=auto -o ControlPersist=60s diff --git a/infra/ansible/inventories/hetzner.example/group_vars/all.yml b/infra/ansible/inventories/hetzner.example/group_vars/all.yml new file mode 100644 index 00000000..99cd36ec --- /dev/null +++ b/infra/ansible/inventories/hetzner.example/group_vars/all.yml @@ -0,0 +1,59 @@ +--- +# Hetzner Cloud overlay for cpx32 (4c / 8 GiB / 160 GiB NVMe) gateway + store. +# Copy to .deploy//inventory/group_vars/all.yml and fill in your values. + +gateway_nat_enabled: true +gateway_private_ip: 10.42.0.2 +gateway_private_subnet_cidr: 10.42.0.0/24 + +gateway_ingress_mode: nginx_tls +gateway_public_host: 203.0.113.10 +gateway_public_url: "https://203.0.113.10" +gateway_public_relay_url: "https://203.0.113.10/relay" + +gateway_provider_env_file: /etc/ucloud-sandboxes/hetzner.env +gateway_provider_dropin_name: hetzner.conf + +# Local NVMe bind mounts on gateway (avoids separate Hetzner registry volume). +gateway_registry_require_mount: true +gateway_mounts: + - src: /var/lib/ucloud-registry-local + path: /mnt/ucloud-registry + fstype: none + opts: bind + dump: 0 + passno: 0 + - src: /mnt/ucloud-registry/backups + path: /work/backups + fstype: none + opts: "bind,nofail,x-systemd.requires-mounts-for=/mnt/ucloud-registry" + dump: 0 + passno: 0 + +# Persistent 1 TB Hetzner volume + cache/index bind mounts on store. +# Replace with `tofu output -raw chunk_store_volume_id`. +store_mounts: + - src: /dev/disk/by-id/scsi-0HC_Volume_ + path: /mnt/store-replica + fstype: ext4 + opts: "defaults,discard,nofail" + dump: 0 + passno: 2 + - src: /mnt/store-replica/cache + path: /var/lib/ucloud-chunk-store/cache + fstype: none + opts: "bind,nofail,x-systemd.requires-mounts-for=/mnt/store-replica" + dump: 0 + passno: 0 + - src: /mnt/store-replica/index + path: /var/lib/ucloud-chunk-index + fstype: none + opts: "bind,nofail,x-systemd.requires-mounts-for=/mnt/store-replica" + dump: 0 + passno: 0 + +ops_backup_dir: /work/backups +ops_backup_requires_mounts_for: /work/backups +ops_backup_gateway_keep: 4 +ops_backup_chunk_index_keep: 2 +ops_backup_chunk_index_ssh_user: root diff --git a/infra/ansible/inventories/hetzner.example/hosts.yml b/infra/ansible/inventories/hetzner.example/hosts.yml new file mode 100644 index 00000000..e9c2abc7 --- /dev/null +++ b/infra/ansible/inventories/hetzner.example/hosts.yml @@ -0,0 +1,18 @@ +# Copy this directory to a gitignored path such as .deploy/prod/inventory/ +# and replace placeholder addresses, volume device IDs, and SSH key paths. +all: + children: + gateway: + hosts: + sandboxes-gateway: + ansible_host: 203.0.113.10 + ansible_user: root + ansible_ssh_private_key_file: /path/to/gateway-init + store: + hosts: + sandboxes-store: + ansible_host: 10.42.0.200 + ansible_user: root + ansible_ssh_private_key_file: /path/to/gateway-init + ansible_ssh_common_args: >- + -o ProxyCommand="ssh -i /path/to/gateway-init -W %h:%p root@203.0.113.10" diff --git a/infra/ansible/inventories/ucloud.example/group_vars/all.yml b/infra/ansible/inventories/ucloud.example/group_vars/all.yml new file mode 100644 index 00000000..b1ae54e1 --- /dev/null +++ b/infra/ansible/inventories/ucloud.example/group_vars/all.yml @@ -0,0 +1,26 @@ +--- +# UCloud provider overlay (VMs created via `sandboxes submit-vm`). +# UCloud handles private worker egress and public TLS links natively. + +gateway_nat_enabled: false +gateway_ingress_mode: none +gateway_public_host: "" +gateway_public_url: "https://gateway.example.cloud" +gateway_public_relay_url: "https://relay.example.cloud" + +# Project drive mounted by UCloud at /work/data holds registry + backups. +gateway_registry_mount: /work/data +gateway_registry_require_mount: true +gateway_mounts: [] +store_mounts: [] + +# UCloud gateway typically has more RAM; tune PG & observability as desired. +gateway_postgres_shared_buffers: 2GB +gateway_postgres_effective_cache_size: 8GB +observability_private_bind_ip: 0.0.0.0 + +ops_backup_dir: /work/data/backups +ops_backup_requires_mounts_for: /work/data +ops_backup_gateway_keep: 24 +ops_backup_chunk_index_keep: 4 +ops_backup_chunk_index_ssh_user: ucloud diff --git a/infra/ansible/inventories/ucloud.example/hosts.yml b/infra/ansible/inventories/ucloud.example/hosts.yml new file mode 100644 index 00000000..ba6a4b16 --- /dev/null +++ b/infra/ansible/inventories/ucloud.example/hosts.yml @@ -0,0 +1,16 @@ +# Copy this directory to a gitignored path such as .deploy/ucloud/inventory/ +# and replace hostnames with your UCloud gateway and store VM hostnames. +all: + children: + gateway: + hosts: + ucloud-gateway: + ansible_host: gateway.example.internal + ansible_user: ucloud + ansible_become: true + store: + hosts: + ucloud-store: + ansible_host: store.example.internal + ansible_user: ucloud + ansible_become: true diff --git a/infra/ansible/roles/common/defaults/main.yml b/infra/ansible/roles/common/defaults/main.yml new file mode 100644 index 00000000..1d5b94c4 --- /dev/null +++ b/infra/ansible/roles/common/defaults/main.yml @@ -0,0 +1,28 @@ +--- +ucloud_user: ucloud +ucloud_group: ucloud +ucloud_install_root: /work/ucloud-sandboxes +ucloud_venv_dir: "{{ ucloud_install_root }}/gateway-venv" +ucloud_data_parent: /var/lib/ucloud-sandboxes +ucloud_data_root: "{{ ucloud_data_parent }}/state" +ucloud_etc_dir: /etc/ucloud-sandboxes +ucloud_libexec_dir: /usr/local/libexec/ucloud-sandboxes +ucloud_chunk_tokens_dir: /var/lib/ucloud-chunk-index + +disable_unattended_upgrades: true +gateway_journald_max_use: 1G +store_journald_max_use: 512M +gateway_nat_enabled: false +gateway_ingress_mode: none +observability_enabled: true +ops_backups_enabled: true +ops_watch_enabled: true + +gateway_sysctl: + 90-ucloud-sandboxes-gateway.conf: + net.ipv4.ip_forward: "{{ 1 if (gateway_nat_enabled | bool) else 0 }}" +store_sysctl: + 90-ucloud-chunk-store.conf: + net.core.somaxconn: 4096 + +store_ucloud_home: /home/ucloud diff --git a/infra/ansible/roles/common/handlers/main.yml b/infra/ansible/roles/common/handlers/main.yml new file mode 100644 index 00000000..676d0451 --- /dev/null +++ b/infra/ansible/roles/common/handlers/main.yml @@ -0,0 +1,9 @@ +--- +- name: Restart systemd-journald + ansible.builtin.systemd_service: + name: systemd-journald + state: restarted + +- name: Reload sysctl + ansible.builtin.command: sysctl --system + changed_when: false diff --git a/infra/ansible/roles/common/tasks/main.yml b/infra/ansible/roles/common/tasks/main.yml new file mode 100644 index 00000000..a8576a82 --- /dev/null +++ b/infra/ansible/roles/common/tasks/main.yml @@ -0,0 +1,74 @@ +--- +- name: Ensure ucloud group exists + ansible.builtin.group: + name: "{{ ucloud_group }}" + system: true + state: present + +- name: Ensure ucloud system user exists + ansible.builtin.user: + name: "{{ ucloud_user }}" + group: "{{ ucloud_group }}" + home: "{{ common_ucloud_home }}" + shell: /usr/sbin/nologin + system: true + create_home: true + state: present + +- name: Disable unattended APT upgrades when configured + when: disable_unattended_upgrades | bool + block: + - name: Write APT no-unattended-upgrades policy + ansible.builtin.copy: + dest: /etc/apt/apt.conf.d/99zz-ucloud-no-unattended-upgrades + owner: root + group: root + mode: "0644" + content: | + APT::Periodic::Enable "0"; + APT::Periodic::Update-Package-Lists "0"; + APT::Periodic::Unattended-Upgrade "0"; + + - name: Disable and mask unattended APT timers + ansible.builtin.systemd_service: + name: "{{ item }}" + enabled: false + state: stopped + masked: true + loop: + - apt-daily.timer + - apt-daily-upgrade.timer + failed_when: false + +- name: Ensure journald drop-in directory exists + ansible.builtin.file: + path: /etc/systemd/journald.conf.d + state: directory + owner: root + group: root + mode: "0755" + +- name: Cap systemd journal disk usage + ansible.builtin.copy: + dest: /etc/systemd/journald.conf.d/ucloud-limit.conf + owner: root + group: root + mode: "0644" + content: | + [Journal] + SystemMaxUse={{ common_journald_max_use }} + notify: Restart systemd-journald + +- name: Write sysctl configuration files + ansible.builtin.copy: + dest: "/etc/sysctl.d/{{ item.key }}" + owner: root + group: root + mode: "0644" + content: | + {% for k, v in item.value.items() %} + {{ k }}={{ v }} + {% endfor %} + loop: "{{ common_sysctl | dict2items }}" + when: item.value | length > 0 + notify: Reload sysctl diff --git a/infra/ansible/roles/gateway/defaults/main.yml b/infra/ansible/roles/gateway/defaults/main.yml new file mode 100644 index 00000000..fe00b362 --- /dev/null +++ b/infra/ansible/roles/gateway/defaults/main.yml @@ -0,0 +1,33 @@ +--- +ucloud_user: ucloud +ucloud_group: ucloud +ucloud_install_root: /work/ucloud-sandboxes +ucloud_venv_dir: "{{ ucloud_install_root }}/gateway-venv" +ucloud_data_parent: /var/lib/ucloud-sandboxes +ucloud_data_root: "{{ ucloud_data_parent }}/state" +ucloud_etc_dir: /etc/ucloud-sandboxes +ucloud_libexec_dir: /usr/local/libexec/ucloud-sandboxes +ucloud_chunk_tokens_dir: /var/lib/ucloud-chunk-index + +gateway_port: 8090 +gateway_upstream_port: 18090 +gateway_enable_gatewayd: true +gateway_gatewayd_binary: /usr/local/libexec/ucloud-gatewayd +gateway_gatewayd_heartbeat_ttl: 45s +gateway_gatewayd_route_cache_ttl: 30s +gateway_registry_mount: /mnt/ucloud-registry +gateway_registry_require_mount: true +gateway_provider_env_file: "" +gateway_provider_dropin_name: hetzner.conf +gateway_mounts: [] +gateway_deployment_config_src: "" + +gateway_postgres_version: "18" +gateway_postgres_max_connections: 200 +gateway_postgres_shared_buffers: 1GB +gateway_postgres_effective_cache_size: 4GB +gateway_postgres_wal_compression: "on" +gateway_postgres_checkpoint_timeout: 15min +gateway_postgres_max_wal_size: 2GB + +release_dir: "" diff --git a/infra/ansible/roles/gateway/handlers/main.yml b/infra/ansible/roles/gateway/handlers/main.yml new file mode 100644 index 00000000..4030f276 --- /dev/null +++ b/infra/ansible/roles/gateway/handlers/main.yml @@ -0,0 +1,11 @@ +--- +- name: Restart postgresql + ansible.builtin.systemd_service: + name: "postgresql@{{ gateway_postgres_version }}-main" + state: restarted + +- name: Reconcile gateway services + ansible.builtin.command: >- + {{ ucloud_venv_dir }}/bin/python -m sandboxes.systemd gateway-reconcile + --config {{ ucloud_etc_dir }}/deployment.json + changed_when: true diff --git a/infra/ansible/roles/gateway/tasks/main.yml b/infra/ansible/roles/gateway/tasks/main.yml new file mode 100644 index 00000000..254dfef4 --- /dev/null +++ b/infra/ansible/roles/gateway/tasks/main.yml @@ -0,0 +1,287 @@ +--- +- name: Install required gateway OS packages + ansible.builtin.apt: + name: + - ca-certificates + - curl + - docker.io + - nftables + - openssl + - "postgresql-{{ gateway_postgres_version }}" + - python3-venv + - rsync + - sqlite3 + state: present + update_cache: true + cache_valid_time: 3600 + when: not (gateway_upgrade_only | default(false) | bool) + +- name: Ensure docker service is enabled and started + ansible.builtin.systemd_service: + name: docker + enabled: true + state: started + when: not (gateway_upgrade_only | default(false) | bool) + +- name: Ensure core gateway directories exist + ansible.builtin.file: + path: "{{ item.path }}" + state: directory + owner: "{{ item.owner | default('root') }}" + group: "{{ item.group | default('root') }}" + mode: "{{ item.mode | default('0755') }}" + loop: + - { path: "{{ ucloud_install_root }}" } + - { path: "{{ ucloud_install_root }}/release" } + - { path: "{{ ucloud_etc_dir }}" } + - { path: "{{ ucloud_libexec_dir }}" } + - { path: "{{ ucloud_data_parent }}", owner: "{{ ucloud_user }}", group: "{{ ucloud_group }}", mode: "0750" } + - { path: "{{ ucloud_data_root }}", owner: "{{ ucloud_user }}", group: "{{ ucloud_group }}", mode: "0700" } + - { path: "{{ ucloud_data_root }}/ssh", owner: "{{ ucloud_user }}", group: "{{ ucloud_group }}", mode: "0700" } + - { path: "{{ ucloud_chunk_tokens_dir }}", owner: "{{ ucloud_user }}", group: "{{ ucloud_group }}", mode: "0700" } + when: not (gateway_upgrade_only | default(false) | bool) + +- name: Ensure declarative gateway mount points and fstab entries exist + when: + - not (gateway_upgrade_only | default(false) | bool) + - gateway_mounts | length > 0 + block: + - name: Create mount target directories + ansible.builtin.file: + path: "{{ item.path }}" + state: directory + owner: "{{ item.owner | default(omit) }}" + group: "{{ item.group | default(omit) }}" + mode: "{{ item.mode | default(omit) }}" + loop: "{{ gateway_mounts }}" + + - name: Create local bind-mount source directories when applicable + ansible.builtin.file: + path: "{{ item.src }}" + state: directory + owner: "{{ item.owner | default(omit) }}" + group: "{{ item.group | default(omit) }}" + mode: "{{ item.mode | default(omit) }}" + loop: "{{ gateway_mounts }}" + when: item.fstype == "none" + + - name: Ensure fstab entries for gateway mounts + ansible.builtin.lineinfile: + path: /etc/fstab + regexp: "^\\S+\\s+{{ item.path | regex_escape }}\\s+" + line: "{{ item.src }} {{ item.path }} {{ item.fstype }} {{ item.opts }} {{ item.dump | default(0) }} {{ item.passno | default(0) }}" + loop: "{{ gateway_mounts }}" + register: gateway_fstab + + - name: Check mount state for gateway mounts + ansible.builtin.command: "mountpoint -q {{ item.path }}" + loop: "{{ gateway_mounts }}" + register: gateway_mount_checks + changed_when: false + failed_when: false + + - name: Mount unmounted gateway filesystems + ansible.builtin.command: "mount {{ item.item.path }}" + loop: "{{ gateway_mount_checks.results }}" + when: item.rc != 0 + changed_when: true + +- name: Configure PostgreSQL tuning for gateway host sizing + ansible.builtin.template: + src: ucloud.conf.j2 + dest: "/etc/postgresql/{{ gateway_postgres_version }}/main/conf.d/ucloud.conf" + owner: postgres + group: postgres + mode: "0644" + when: not (gateway_upgrade_only | default(false) | bool) + notify: Restart postgresql + +- name: Ensure PostgreSQL service is enabled and cluster is running + ansible.builtin.systemd_service: + name: postgresql + enabled: true + state: started + when: not (gateway_upgrade_only | default(false) | bool) + +- name: Ensure PostgreSQL main cluster is running + ansible.builtin.systemd_service: + name: "postgresql@{{ gateway_postgres_version }}-main" + state: started + when: not (gateway_upgrade_only | default(false) | bool) + +- name: Install deployment.json when provided by inventory + ansible.builtin.copy: + src: "{{ gateway_deployment_config_src }}" + dest: "{{ ucloud_etc_dir }}/deployment.json" + owner: root + group: root + mode: "0644" + when: (gateway_deployment_config_src | default('') | length) > 0 + notify: Reconcile gateway services + +- name: Ensure gateway virtual environment exists + ansible.builtin.command: "python3 -m venv {{ ucloud_venv_dir }}" + args: + creates: "{{ ucloud_venv_dir }}/bin/python" + when: not (gateway_upgrade_only | default(false) | bool) + +- name: Deploy release artifacts when release_dir is provided + when: (release_dir | default('') | length) > 0 + block: + - name: Locate wheel in release_dir + ansible.builtin.find: + paths: "{{ release_dir }}" + patterns: "*.whl" + delegate_to: localhost + become: false + register: release_wheels + + - name: Stage wheel on gateway + ansible.builtin.copy: + src: "{{ release_wheels.files[0].path }}" + dest: "/tmp/{{ release_wheels.files[0].path | basename }}" + mode: "0644" + when: release_wheels.files | length > 0 + register: staged_wheel + + - name: Install sandboxes wheel into gateway venv + ansible.builtin.command: >- + {{ ucloud_venv_dir }}/bin/pip install --disable-pip-version-check --force-reinstall + /tmp/{{ release_wheels.files[0].path | basename }}[postgres] + when: release_wheels.files | length > 0 + changed_when: true + notify: Reconcile gateway services + + - name: Check if ucloud-gatewayd exists in release_dir + ansible.builtin.stat: + path: "{{ release_dir }}/ucloud-gatewayd" + delegate_to: localhost + become: false + register: release_gatewayd + + - name: Install ucloud-gatewayd binary from release_dir + ansible.builtin.copy: + src: "{{ release_dir }}/ucloud-gatewayd" + dest: "{{ gateway_gatewayd_binary }}" + owner: root + group: root + mode: "0755" + when: + - gateway_enable_gatewayd | bool + - release_gatewayd.stat.exists + notify: Reconcile gateway services + +- name: Ensure gateway authentication tokens exist without overwriting + ansible.builtin.shell: | + set -euo pipefail + token_path="{{ ucloud_data_root }}/{{ item }}" + if [ ! -s "$token_path" ]; then + (umask 077 && openssl rand -hex 32 > "$token_path") + chown {{ ucloud_user }}:{{ ucloud_group }} "$token_path" + chmod 0600 "$token_path" + echo CHANGED + fi + args: + executable: /bin/bash + loop: + - gateway-token + - sandbox-api-token + - heartbeat-token + - node-control-token + - relay-sandbox-token + - relay-worker-token + register: token_gen + changed_when: "'CHANGED' in token_gen.stdout" + when: not (gateway_upgrade_only | default(false) | bool) + +- name: Install ucloud-sandbox-gatewayd systemd unit when enabled + ansible.builtin.template: + src: ucloud-sandbox-gatewayd.service.j2 + dest: /etc/systemd/system/ucloud-sandbox-gatewayd.service + owner: root + group: root + mode: "0644" + when: gateway_enable_gatewayd | bool + notify: Reconcile gateway services + +- name: Ensure gateway systemd drop-in directories exist + ansible.builtin.file: + path: "/etc/systemd/system/{{ item }}.d" + state: directory + owner: root + group: root + mode: "0755" + loop: + - ucloud-sandbox-gateway.service + - ucloud-sandbox-autoscaler.service + - ucloud-sandbox-registry.service + - ucloud-sandbox-registry-gc.service + - ucloud-sandbox-registry-pressure.service + - ucloud-sandbox-upstream-mirror@.service + - ucloud-sandbox-upstream-mirror-trim.service + +- name: Configure Python gateway upstream bind drop-in when gatewayd is enabled + ansible.builtin.template: + src: gatewayd-upstream.conf.j2 + dest: /etc/systemd/system/ucloud-sandbox-gateway.service.d/gatewayd-upstream.conf + owner: root + group: root + mode: "0644" + when: gateway_enable_gatewayd | bool + notify: Reconcile gateway services + +- name: Remove gatewayd upstream drop-in when gatewayd is disabled + ansible.builtin.file: + path: /etc/systemd/system/ucloud-sandbox-gateway.service.d/gatewayd-upstream.conf + state: absent + when: not (gateway_enable_gatewayd | bool) + notify: Reconcile gateway services + +- name: Configure provider environment drop-in for autoscaler + ansible.builtin.template: + src: provider.conf.j2 + dest: "/etc/systemd/system/ucloud-sandbox-autoscaler.service.d/{{ gateway_provider_dropin_name }}" + owner: root + group: root + mode: "0644" + when: (gateway_provider_env_file | default('') | length) > 0 + notify: Reconcile gateway services + +- name: Configure registry mount drop-ins when filesystem registry requires mount + ansible.builtin.template: + src: registry-volume.conf.j2 + dest: "/etc/systemd/system/{{ item }}.d/volume.conf" + owner: root + group: root + mode: "0644" + loop: + - ucloud-sandbox-registry.service + - ucloud-sandbox-registry-gc.service + - ucloud-sandbox-registry-pressure.service + - ucloud-sandbox-upstream-mirror@.service + - ucloud-sandbox-upstream-mirror-trim.service + when: gateway_registry_require_mount | bool + notify: Reconcile gateway services + +- name: Remove registry mount drop-ins when not required + ansible.builtin.file: + path: "/etc/systemd/system/{{ item }}.d/volume.conf" + state: absent + loop: + - ucloud-sandbox-registry.service + - ucloud-sandbox-registry-gc.service + - ucloud-sandbox-registry-pressure.service + - ucloud-sandbox-upstream-mirror@.service + - ucloud-sandbox-upstream-mirror-trim.service + when: not (gateway_registry_require_mount | bool) + notify: Reconcile gateway services + +- name: Record chunk-index read/write token checksums on gateway for store verification + ansible.builtin.stat: + path: "{{ ucloud_chunk_tokens_dir }}/{{ item }}" + checksum_algorithm: sha256 + loop: + - read.token + - write.token + register: gateway_chunk_token_stats + when: not (gateway_upgrade_only | default(false) | bool) diff --git a/infra/ansible/roles/gateway/templates/gatewayd-upstream.conf.j2 b/infra/ansible/roles/gateway/templates/gatewayd-upstream.conf.j2 new file mode 100644 index 00000000..9cd521e4 --- /dev/null +++ b/infra/ansible/roles/gateway/templates/gatewayd-upstream.conf.j2 @@ -0,0 +1,3 @@ +[Service] +ExecStart= +ExecStart={{ ucloud_venv_dir }}/bin/sandboxes serve-control-plane --config {{ ucloud_etc_dir }}/deployment.json --host 127.0.0.1 --port {{ gateway_upstream_port }} diff --git a/infra/ansible/roles/gateway/templates/provider.conf.j2 b/infra/ansible/roles/gateway/templates/provider.conf.j2 new file mode 100644 index 00000000..61edf7dc --- /dev/null +++ b/infra/ansible/roles/gateway/templates/provider.conf.j2 @@ -0,0 +1,2 @@ +[Service] +EnvironmentFile={{ gateway_provider_env_file }} diff --git a/infra/ansible/roles/gateway/templates/registry-volume.conf.j2 b/infra/ansible/roles/gateway/templates/registry-volume.conf.j2 new file mode 100644 index 00000000..ca6d9586 --- /dev/null +++ b/infra/ansible/roles/gateway/templates/registry-volume.conf.j2 @@ -0,0 +1,5 @@ +[Unit] +RequiresMountsFor={{ gateway_registry_mount }} + +[Service] +ExecStartPre=/usr/bin/mountpoint -q {{ gateway_registry_mount }} diff --git a/infra/ansible/roles/gateway/templates/ucloud-sandbox-gatewayd.service.j2 b/infra/ansible/roles/gateway/templates/ucloud-sandbox-gatewayd.service.j2 new file mode 100644 index 00000000..2e80a805 --- /dev/null +++ b/infra/ansible/roles/gateway/templates/ucloud-sandbox-gatewayd.service.j2 @@ -0,0 +1,23 @@ +[Unit] +Description=UCloud Sandbox Go fast-path gateway front door (ucloud-gatewayd) +After=network-online.target ucloud-sandbox-gateway.service +Wants=network-online.target ucloud-sandbox-gateway.service + +[Service] +Type=simple +User={{ ucloud_user }} +Group={{ ucloud_group }} +ExecStart={{ gateway_gatewayd_binary }} \ + --listen 0.0.0.0:{{ gateway_port }} \ + --upstream http://127.0.0.1:{{ gateway_upstream_port }} \ + --gateway-token-file {{ ucloud_data_root }}/gateway-token \ + --sandbox-api-token-file {{ ucloud_data_root }}/sandbox-api-token \ + --node-control-token-file {{ ucloud_data_root }}/node-control-token \ + --heartbeat-ttl {{ gateway_gatewayd_heartbeat_ttl }} \ + --route-cache-ttl {{ gateway_gatewayd_route_cache_ttl }} +LimitNOFILE=65536 +Restart=always +RestartSec=1 + +[Install] +WantedBy=multi-user.target diff --git a/infra/ansible/roles/gateway/templates/ucloud.conf.j2 b/infra/ansible/roles/gateway/templates/ucloud.conf.j2 new file mode 100644 index 00000000..0e3f09b1 --- /dev/null +++ b/infra/ansible/roles/gateway/templates/ucloud.conf.j2 @@ -0,0 +1,6 @@ +max_connections = {{ gateway_postgres_max_connections }} +shared_buffers = {{ gateway_postgres_shared_buffers }} +effective_cache_size = {{ gateway_postgres_effective_cache_size }} +wal_compression = {{ gateway_postgres_wal_compression }} +checkpoint_timeout = {{ gateway_postgres_checkpoint_timeout }} +max_wal_size = {{ gateway_postgres_max_wal_size }} diff --git a/infra/ansible/roles/gateway_ingress/defaults/main.yml b/infra/ansible/roles/gateway_ingress/defaults/main.yml new file mode 100644 index 00000000..fabf1114 --- /dev/null +++ b/infra/ansible/roles/gateway_ingress/defaults/main.yml @@ -0,0 +1,5 @@ +--- +gateway_public_host: "" +gateway_relay_port: 8092 +gateway_grafana_port: 3000 +observability_enabled: true diff --git a/infra/ansible/roles/gateway_ingress/tasks/main.yml b/infra/ansible/roles/gateway_ingress/tasks/main.yml new file mode 100644 index 00000000..7ae45b53 --- /dev/null +++ b/infra/ansible/roles/gateway_ingress/tasks/main.yml @@ -0,0 +1,45 @@ +--- +- name: Install nginx for TLS ingress + ansible.builtin.apt: + name: + - nginx + state: present + +- name: Install ingress helper script + ansible.builtin.copy: + src: "{{ playbook_dir }}/../../scripts/ops/configure_hetzner_sdk_ingress.sh" + dest: /usr/local/sbin/configure-hetzner-sdk-ingress + owner: root + group: root + mode: "0755" + +- name: Check whether nginx gateway site is already configured + ansible.builtin.stat: + path: /etc/nginx/sites-enabled/ucloud-sandbox-gateway + register: nginx_site_stat + +- name: Configure TLS ingress when bootstrapping or explicitly requested + ansible.builtin.command: >- + /usr/local/sbin/configure-hetzner-sdk-ingress + --public-host {{ gateway_public_host }} + --relay-port {{ gateway_relay_port }} + {% if observability_enabled | bool %}--grafana-port {{ gateway_grafana_port }}{% endif %} + when: + - (gateway_public_host | length) > 0 + - (not nginx_site_stat.stat.exists) or (configure_ingress | default(false) | bool) + changed_when: true + +- name: Validate nginx configuration + ansible.builtin.command: nginx -t + changed_when: false + when: nginx_site_stat.stat.exists + +- name: Ensure nginx and certbot renewal timer are enabled and active + ansible.builtin.systemd_service: + name: "{{ item }}" + enabled: true + state: started + loop: + - nginx.service + - ucloud-sandbox-certbot-renew.timer + when: nginx_site_stat.stat.exists diff --git a/infra/ansible/roles/gateway_nat/defaults/main.yml b/infra/ansible/roles/gateway_nat/defaults/main.yml new file mode 100644 index 00000000..975fe930 --- /dev/null +++ b/infra/ansible/roles/gateway_nat/defaults/main.yml @@ -0,0 +1,3 @@ +--- +gateway_private_ip: 10.42.0.2 +gateway_private_subnet_cidr: 10.42.0.0/24 diff --git a/infra/ansible/roles/gateway_nat/handlers/main.yml b/infra/ansible/roles/gateway_nat/handlers/main.yml new file mode 100644 index 00000000..a8803d38 --- /dev/null +++ b/infra/ansible/roles/gateway_nat/handlers/main.yml @@ -0,0 +1,9 @@ +--- +- name: Reload systemd + ansible.builtin.systemd_service: + daemon_reload: true + +- name: Restart ucloud-sandboxes-nat + ansible.builtin.systemd_service: + name: ucloud-sandboxes-nat.service + state: restarted diff --git a/infra/ansible/roles/gateway_nat/tasks/main.yml b/infra/ansible/roles/gateway_nat/tasks/main.yml new file mode 100644 index 00000000..d6515646 --- /dev/null +++ b/infra/ansible/roles/gateway_nat/tasks/main.yml @@ -0,0 +1,38 @@ +--- +- name: Install private worker NAT script + ansible.builtin.template: + src: ucloud-sandboxes-nat.j2 + dest: /usr/local/sbin/ucloud-sandboxes-nat + owner: root + group: root + mode: "0755" + notify: Restart ucloud-sandboxes-nat + +- name: Install ucloud-sandboxes-nat systemd service + ansible.builtin.copy: + dest: /etc/systemd/system/ucloud-sandboxes-nat.service + owner: root + group: root + mode: "0644" + content: | + [Unit] + Description=UCloud Sandboxes private worker NAT + After=docker.service network-online.target + Wants=docker.service network-online.target + + [Service] + Type=oneshot + ExecStart=/usr/local/sbin/ucloud-sandboxes-nat + RemainAfterExit=yes + + [Install] + WantedBy=multi-user.target + notify: + - Reload systemd + - Restart ucloud-sandboxes-nat + +- name: Ensure ucloud-sandboxes-nat is enabled and active + ansible.builtin.systemd_service: + name: ucloud-sandboxes-nat.service + enabled: true + state: started diff --git a/infra/ansible/roles/gateway_nat/templates/ucloud-sandboxes-nat.j2 b/infra/ansible/roles/gateway_nat/templates/ucloud-sandboxes-nat.j2 new file mode 100644 index 00000000..a19cfa7a --- /dev/null +++ b/infra/ansible/roles/gateway_nat/templates/ucloud-sandboxes-nat.j2 @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail +public_if="$(ip -4 route show default | awk 'NR == 1 {print $5}')" +private_if="$(ip -o -4 address show | awk '$4 ~ /^{{ gateway_private_ip | replace(".", "\\.") }}\// {print $2; exit}')" +if [[ -z "$public_if" || -z "$private_if" ]]; then + echo "could not resolve public/private interfaces for {{ gateway_private_ip }}" >&2 + exit 1 +fi +nft delete table inet ucloud_sandboxes_nat 2>/dev/null || true +nft -f - </dev/null || true +iptables -F UCLOUD-SANDBOXES +iptables -A UCLOUD-SANDBOXES \ + -i "$private_if" -o "$public_if" -s {{ gateway_private_subnet_cidr }} -j ACCEPT +iptables -A UCLOUD-SANDBOXES \ + -i "$public_if" -o "$private_if" -d {{ gateway_private_subnet_cidr }} \ + -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT +iptables -A UCLOUD-SANDBOXES -j RETURN +if ! iptables -C DOCKER-USER -j UCLOUD-SANDBOXES 2>/dev/null; then + iptables -I DOCKER-USER 1 -j UCLOUD-SANDBOXES +fi diff --git a/infra/ansible/roles/observability/defaults/main.yml b/infra/ansible/roles/observability/defaults/main.yml new file mode 100644 index 00000000..e6f06db1 --- /dev/null +++ b/infra/ansible/roles/observability/defaults/main.yml @@ -0,0 +1,25 @@ +--- +ucloud_data_parent: /var/lib/ucloud-sandboxes +ucloud_etc_dir: /etc/ucloud-sandboxes +gateway_private_ip: 10.42.0.2 +gateway_public_host: "" +gateway_public_url: "" +gateway_grafana_port: 3000 + +observability_private_bind_ip: "{{ gateway_private_ip }}" +observability_data_root: "{{ ucloud_data_parent }}/telemetry" +observability_config_root: "{{ ucloud_etc_dir }}/telemetry" +observability_collector_image: "otel/opentelemetry-collector-contrib:0.153.0" +observability_collector_memory: 320m +observability_collector_cpus: "0.50" +observability_victoria_image: "victoriametrics/victoria-metrics:v1.148.0" +observability_victoria_memory: 384m +observability_victoria_cpus: "0.40" +observability_victoria_retention: 14d +observability_victoria_min_free_disk: 20GB +observability_tempo_image: "grafana/tempo:2.10.7" +observability_tempo_memory: 768m +observability_tempo_cpus: "0.60" +observability_grafana_image: "grafana/grafana:13.2.4" +observability_grafana_memory: 768m +observability_grafana_cpus: "1.0" diff --git a/infra/ansible/roles/observability/handlers/main.yml b/infra/ansible/roles/observability/handlers/main.yml new file mode 100644 index 00000000..1f0edfc3 --- /dev/null +++ b/infra/ansible/roles/observability/handlers/main.yml @@ -0,0 +1,14 @@ +--- +- name: Reload systemd + ansible.builtin.systemd_service: + daemon_reload: true + +- name: Restart telemetry stack + ansible.builtin.systemd_service: + name: "{{ item }}.service" + state: restarted + loop: + - ucloud-telemetry-collector + - ucloud-telemetry-victoria + - ucloud-telemetry-tempo + - ucloud-telemetry-grafana diff --git a/infra/ansible/roles/observability/tasks/main.yml b/infra/ansible/roles/observability/tasks/main.yml new file mode 100644 index 00000000..b9fde3d2 --- /dev/null +++ b/infra/ansible/roles/observability/tasks/main.yml @@ -0,0 +1,56 @@ +--- +- name: Ensure telemetry data and config directories exist + ansible.builtin.file: + path: "{{ item.path }}" + state: directory + owner: "{{ item.owner | default('root') }}" + group: "{{ item.group | default('root') }}" + mode: "{{ item.mode | default('0755') }}" + loop: + - { path: "{{ observability_data_root }}" } + - { path: "{{ observability_data_root }}/victoria-metrics", mode: "0700" } + - { path: "{{ observability_data_root }}/tempo", mode: "0700" } + - { path: "{{ observability_data_root }}/grafana", owner: "{{ omit }}", group: "{{ omit }}", mode: "0750" } + - { path: "{{ observability_config_root }}" } + +- name: Check if observability config files are bootstrapped + ansible.builtin.stat: + path: "{{ observability_config_root }}/collector.yaml" + register: obs_collector_cfg + +- name: Bootstrap observability config files when missing + ansible.builtin.command: >- + {{ playbook_dir }}/../../scripts/ops/install_ucloud_observability_stack.sh + --private-bind-ip {{ observability_private_bind_ip }} + {% if (gateway_public_url | length) > 0 %}--public-url {{ gateway_public_url }}/grafana/{% endif %} + when: not obs_collector_cfg.stat.exists + changed_when: true + +- name: Render declarative telemetry systemd units with resource caps + ansible.builtin.template: + src: "{{ item }}.service.j2" + dest: "/etc/systemd/system/{{ item }}.service" + owner: root + group: root + mode: "0644" + loop: + - ucloud-telemetry-collector + - ucloud-telemetry-victoria + - ucloud-telemetry-tempo + - ucloud-telemetry-grafana + when: obs_collector_cfg.stat.exists + notify: + - Reload systemd + - Restart telemetry stack + +- name: Ensure telemetry services are enabled and running + ansible.builtin.systemd_service: + name: "{{ item }}.service" + enabled: true + state: started + loop: + - ucloud-telemetry-collector + - ucloud-telemetry-victoria + - ucloud-telemetry-tempo + - ucloud-telemetry-grafana + when: obs_collector_cfg.stat.exists diff --git a/infra/ansible/roles/observability/templates/ucloud-telemetry-collector.service.j2 b/infra/ansible/roles/observability/templates/ucloud-telemetry-collector.service.j2 new file mode 100644 index 00000000..47076dd9 --- /dev/null +++ b/infra/ansible/roles/observability/templates/ucloud-telemetry-collector.service.j2 @@ -0,0 +1,17 @@ +[Unit] +Description=UCloud OpenTelemetry Collector +After=docker.service network-online.target ucloud-telemetry-tempo.service ucloud-telemetry-victoria.service +Wants=docker.service network-online.target +Wants=ucloud-telemetry-tempo.service ucloud-telemetry-victoria.service + +[Service] +Restart=always +RestartSec=5 +ExecStartPre=-/usr/bin/docker network create ucloud-telemetry +ExecStartPre=-/usr/bin/docker rm -f ucloud-telemetry-collector +ExecStart=/usr/bin/docker run --name ucloud-telemetry-collector --network ucloud-telemetry --memory {{ observability_collector_memory }} --cpus {{ observability_collector_cpus }} --cpu-shares 256 --log-driver journald -p {{ observability_private_bind_ip }}:4318:4318 -p 127.0.0.1:13133:13133 -v {{ observability_config_root }}/collector.yaml:/etc/otelcol-contrib/config.yaml:ro {{ observability_collector_image }} --config=/etc/otelcol-contrib/config.yaml +ExecStop=/usr/bin/docker stop --time 20 ucloud-telemetry-collector +TimeoutStopSec=30 + +[Install] +WantedBy=multi-user.target diff --git a/infra/ansible/roles/observability/templates/ucloud-telemetry-grafana.service.j2 b/infra/ansible/roles/observability/templates/ucloud-telemetry-grafana.service.j2 new file mode 100644 index 00000000..50fa511b --- /dev/null +++ b/infra/ansible/roles/observability/templates/ucloud-telemetry-grafana.service.j2 @@ -0,0 +1,18 @@ +[Unit] +Description=UCloud Grafana observability UI +After=docker.service network-online.target ucloud-telemetry-tempo.service ucloud-telemetry-victoria.service +Wants=docker.service network-online.target +Wants=ucloud-telemetry-tempo.service ucloud-telemetry-victoria.service +RequiresMountsFor={{ observability_data_root }} + +[Service] +Restart=always +RestartSec=5 +ExecStartPre=-/usr/bin/docker network create ucloud-telemetry +ExecStartPre=-/usr/bin/docker rm -f ucloud-telemetry-grafana +ExecStart=/usr/bin/docker run --name ucloud-telemetry-grafana --network ucloud-telemetry --memory {{ observability_grafana_memory }} --cpus {{ observability_grafana_cpus }} --cpu-shares 256 --log-driver journald --env-file {{ observability_config_root }}/grafana.env -e GF_AUTH_ANONYMOUS_ENABLED=false -e GF_USERS_ALLOW_SIGN_UP=false -e GF_ANALYTICS_REPORTING_ENABLED=false -e GF_ANALYTICS_CHECK_FOR_UPDATES=false -e GF_PLUGINS_PREINSTALL_SYNC=yesoreyeram-infinity-datasource@4.1.1 -e GF_PLUGINS_PREINSTALL_AUTO_UPDATE=false {% if (gateway_public_host | length) > 0 %}-e GF_SERVER_DOMAIN={{ gateway_public_host }} -e GF_SERVER_ROOT_URL=https://{{ gateway_public_host }}/grafana/ -e GF_SERVER_SERVE_FROM_SUB_PATH=true {% endif %}-e GF_SECURITY_COOKIE_SECURE=true -e GF_SECURITY_COOKIE_SAMESITE=strict -p 127.0.0.1:{{ gateway_grafana_port }}:3000 -v {{ observability_data_root }}/grafana:/var/lib/grafana -v {{ observability_config_root }}/grafana/provisioning:/etc/grafana/provisioning:ro -v {{ observability_config_root }}/grafana/dashboards:/var/lib/grafana/dashboards:ro -v {{ observability_config_root }}/grafana/gateway-token:/etc/grafana/gateway-token:ro {{ observability_grafana_image }} +ExecStop=/usr/bin/docker stop --time 20 ucloud-telemetry-grafana +TimeoutStopSec=30 + +[Install] +WantedBy=multi-user.target diff --git a/infra/ansible/roles/observability/templates/ucloud-telemetry-tempo.service.j2 b/infra/ansible/roles/observability/templates/ucloud-telemetry-tempo.service.j2 new file mode 100644 index 00000000..effe5bd1 --- /dev/null +++ b/infra/ansible/roles/observability/templates/ucloud-telemetry-tempo.service.j2 @@ -0,0 +1,17 @@ +[Unit] +Description=UCloud Tempo trace store +After=docker.service network-online.target +Wants=docker.service network-online.target +RequiresMountsFor={{ observability_data_root }} + +[Service] +Restart=always +RestartSec=5 +ExecStartPre=-/usr/bin/docker network create ucloud-telemetry +ExecStartPre=-/usr/bin/docker rm -f ucloud-telemetry-tempo +ExecStart=/usr/bin/docker run --name ucloud-telemetry-tempo --network ucloud-telemetry --memory {{ observability_tempo_memory }} --cpus {{ observability_tempo_cpus }} --cpu-shares 256 --user 0:0 --log-driver journald -p 127.0.0.1:3200:3200 -v {{ observability_config_root }}/tempo.yaml:/etc/tempo.yaml:ro -v {{ observability_data_root }}/tempo:/var/tempo {{ observability_tempo_image }} -config.file=/etc/tempo.yaml +ExecStop=/usr/bin/docker stop --time 30 ucloud-telemetry-tempo +TimeoutStopSec=40 + +[Install] +WantedBy=multi-user.target diff --git a/infra/ansible/roles/observability/templates/ucloud-telemetry-victoria.service.j2 b/infra/ansible/roles/observability/templates/ucloud-telemetry-victoria.service.j2 new file mode 100644 index 00000000..f067bbc8 --- /dev/null +++ b/infra/ansible/roles/observability/templates/ucloud-telemetry-victoria.service.j2 @@ -0,0 +1,17 @@ +[Unit] +Description=UCloud VictoriaMetrics store +After=docker.service network-online.target +Wants=docker.service network-online.target +RequiresMountsFor={{ observability_data_root }} + +[Service] +Restart=always +RestartSec=5 +ExecStartPre=-/usr/bin/docker network create ucloud-telemetry +ExecStartPre=-/usr/bin/docker rm -f ucloud-telemetry-victoria +ExecStart=/usr/bin/docker run --name ucloud-telemetry-victoria --network ucloud-telemetry --memory {{ observability_victoria_memory }} --cpus {{ observability_victoria_cpus }} --cpu-shares 256 --user 0:0 --log-driver journald -p 127.0.0.1:8428:8428 -v {{ observability_data_root }}/victoria-metrics:/victoria-metrics-data -v {{ observability_config_root }}/scrape.yaml:/etc/victoria/scrape.yaml:ro -v {{ observability_config_root }}/gateway-token:/etc/victoria/gateway-token:ro {{ observability_victoria_image }} -promscrape.config=/etc/victoria/scrape.yaml -storageDataPath=/victoria-metrics-data -retentionPeriod={{ observability_victoria_retention }} -storage.minFreeDiskSpaceBytes={{ observability_victoria_min_free_disk }} -memory.allowedPercent=50 -selfScrapeInterval=10s +ExecStop=/usr/bin/docker stop --time 30 ucloud-telemetry-victoria +TimeoutStopSec=40 + +[Install] +WantedBy=multi-user.target diff --git a/infra/ansible/roles/ops/defaults/main.yml b/infra/ansible/roles/ops/defaults/main.yml new file mode 100644 index 00000000..6a3fc59a --- /dev/null +++ b/infra/ansible/roles/ops/defaults/main.yml @@ -0,0 +1,15 @@ +--- +ucloud_install_root: /work/ucloud-sandboxes +ucloud_venv_dir: "{{ ucloud_install_root }}/gateway-venv" +ucloud_etc_dir: /etc/ucloud-sandboxes +ucloud_libexec_dir: /usr/local/libexec/ucloud-sandboxes +gateway_public_url: "" +gateway_public_relay_url: "" + +ops_backups_enabled: true +ops_watch_enabled: true +ops_backup_dir: /work/backups +ops_backup_requires_mounts_for: "{{ ops_backup_dir }}" +ops_backup_gateway_keep: 4 +ops_backup_chunk_index_keep: 2 +ops_backup_chunk_index_ssh_user: root diff --git a/infra/ansible/roles/ops/handlers/main.yml b/infra/ansible/roles/ops/handlers/main.yml new file mode 100644 index 00000000..5498019f --- /dev/null +++ b/infra/ansible/roles/ops/handlers/main.yml @@ -0,0 +1,4 @@ +--- +- name: Reload systemd + ansible.builtin.systemd_service: + daemon_reload: true diff --git a/infra/ansible/roles/ops/tasks/main.yml b/infra/ansible/roles/ops/tasks/main.yml new file mode 100644 index 00000000..5fe47d2e --- /dev/null +++ b/infra/ansible/roles/ops/tasks/main.yml @@ -0,0 +1,139 @@ +--- +- name: Install gateway ops scripts into libexec + ansible.builtin.copy: + src: "{{ playbook_dir }}/../../scripts/ops/{{ item }}" + dest: "{{ ucloud_libexec_dir }}/{{ item }}" + owner: root + group: root + mode: "0755" + loop: + - backup_gateway_state.py + - ops_watch.py + +- name: Ensure alerts.env exists without overwriting existing webhooks + ansible.builtin.file: + path: "{{ ucloud_etc_dir }}/alerts.env" + state: touch + owner: root + group: root + mode: "0600" + modification_time: preserve + access_time: preserve + +- name: Ensure backup directories exist + ansible.builtin.file: + path: "{{ item }}" + state: directory + owner: root + group: root + mode: "0700" + loop: + - "{{ ops_backup_dir }}" + - "{{ ops_backup_dir }}/gateway" + - "{{ ops_backup_dir }}/chunk-index" + when: ops_backups_enabled | bool + +- name: Install backup systemd services and timers + when: ops_backups_enabled | bool + block: + - name: Render backup-gateway service + ansible.builtin.template: + src: ucloud-sandbox-backup-gateway.service.j2 + dest: /etc/systemd/system/ucloud-sandbox-backup-gateway.service + owner: root + group: root + mode: "0644" + notify: Reload systemd + + - name: Render backup-gateway timer + ansible.builtin.copy: + dest: /etc/systemd/system/ucloud-sandbox-backup-gateway.timer + owner: root + group: root + mode: "0644" + content: | + [Unit] + Description=Back up gateway PostgreSQL and state (timer) + + [Timer] + OnCalendar=hourly + RandomizedDelaySec=300 + Persistent=true + + [Install] + WantedBy=timers.target + notify: Reload systemd + + - name: Render backup-chunk-index service + ansible.builtin.template: + src: ucloud-sandbox-backup-chunk-index.service.j2 + dest: /etc/systemd/system/ucloud-sandbox-backup-chunk-index.service + owner: root + group: root + mode: "0644" + notify: Reload systemd + + - name: Render backup-chunk-index timer + ansible.builtin.copy: + dest: /etc/systemd/system/ucloud-sandbox-backup-chunk-index.timer + owner: root + group: root + mode: "0644" + content: | + [Unit] + Description=Back up the store node's chunk index (timer) + + [Timer] + OnCalendar=00/6:20 + Persistent=true + + [Install] + WantedBy=timers.target + notify: Reload systemd + + - name: Enable and start backup timers + ansible.builtin.systemd_service: + name: "{{ item }}" + enabled: true + state: started + loop: + - ucloud-sandbox-backup-gateway.timer + - ucloud-sandbox-backup-chunk-index.timer + +- name: Install ops-watch service and timer + when: ops_watch_enabled | bool + block: + - name: Render ops-watch service + ansible.builtin.template: + src: ucloud-sandbox-ops-watch.service.j2 + dest: /etc/systemd/system/ucloud-sandbox-ops-watch.service + owner: root + group: root + mode: "0644" + notify: Reload systemd + + - name: Render ops-watch timer + ansible.builtin.copy: + dest: /etc/systemd/system/ucloud-sandbox-ops-watch.timer + owner: root + group: root + mode: "0644" + content: | + [Unit] + Description=Control plane health watch (timer) + + [Timer] + OnBootSec=2min + OnUnitActiveSec=1min + AccuracySec=5s + Persistent=true + + [Install] + WantedBy=timers.target + notify: Reload systemd + + - name: Enable and start ops-watch timer + ansible.builtin.systemd_service: + name: ucloud-sandbox-ops-watch.timer + enabled: true + state: started diff --git a/infra/ansible/roles/ops/templates/ucloud-sandbox-backup-chunk-index.service.j2 b/infra/ansible/roles/ops/templates/ucloud-sandbox-backup-chunk-index.service.j2 new file mode 100644 index 00000000..da131b0e --- /dev/null +++ b/infra/ansible/roles/ops/templates/ucloud-sandbox-backup-chunk-index.service.j2 @@ -0,0 +1,10 @@ +[Unit] +Description=Back up the store node's chunk index +RequiresMountsFor={{ ops_backup_requires_mounts_for }} +After=postgresql.service + +[Service] +Type=oneshot +Nice=10 +IOSchedulingClass=idle +ExecStart={{ ucloud_venv_dir }}/bin/python {{ ucloud_libexec_dir }}/backup_gateway_state.py chunk-index --ssh-user {{ ops_backup_chunk_index_ssh_user }} --dest {{ ops_backup_dir }}/chunk-index --keep {{ ops_backup_chunk_index_keep }} diff --git a/infra/ansible/roles/ops/templates/ucloud-sandbox-backup-gateway.service.j2 b/infra/ansible/roles/ops/templates/ucloud-sandbox-backup-gateway.service.j2 new file mode 100644 index 00000000..3c06a7b9 --- /dev/null +++ b/infra/ansible/roles/ops/templates/ucloud-sandbox-backup-gateway.service.j2 @@ -0,0 +1,10 @@ +[Unit] +Description=Back up gateway PostgreSQL and state +RequiresMountsFor={{ ops_backup_requires_mounts_for }} +After=postgresql.service + +[Service] +Type=oneshot +Nice=10 +IOSchedulingClass=idle +ExecStart={{ ucloud_venv_dir }}/bin/python {{ ucloud_libexec_dir }}/backup_gateway_state.py gateway --dest {{ ops_backup_dir }}/gateway --keep {{ ops_backup_gateway_keep }} diff --git a/infra/ansible/roles/ops/templates/ucloud-sandbox-ops-watch.service.j2 b/infra/ansible/roles/ops/templates/ucloud-sandbox-ops-watch.service.j2 new file mode 100644 index 00000000..1c222a72 --- /dev/null +++ b/infra/ansible/roles/ops/templates/ucloud-sandbox-ops-watch.service.j2 @@ -0,0 +1,10 @@ +[Unit] +Description=Control plane health watch +RequiresMountsFor={{ ops_backup_requires_mounts_for }} +After=postgresql.service + +[Service] +Type=oneshot +Nice=10 +IOSchedulingClass=idle +ExecStart={{ ucloud_venv_dir }}/bin/python {{ ucloud_libexec_dir }}/ops_watch.py --backups {{ ops_backup_dir }} --public-gateway '{{ gateway_public_url }}' --public-relay '{{ gateway_public_relay_url }}' diff --git a/infra/ansible/roles/store/defaults/main.yml b/infra/ansible/roles/store/defaults/main.yml new file mode 100644 index 00000000..7311c586 --- /dev/null +++ b/infra/ansible/roles/store/defaults/main.yml @@ -0,0 +1,15 @@ +--- +ucloud_user: ucloud +ucloud_group: ucloud +ucloud_install_root: /work/ucloud-sandboxes +ucloud_etc_dir: /etc/ucloud-sandboxes +ucloud_libexec_dir: /usr/local/libexec/ucloud-sandboxes +ucloud_chunk_tokens_dir: /var/lib/ucloud-chunk-index + +store_mounts: [] +store_chunk_serve_binary: "{{ ucloud_libexec_dir }}/ucloud-chunk-serve" +store_chunk_serve_upstream: 127.0.0.1:5191 +store_chunk_config_path: "{{ ucloud_etc_dir }}/chunk-store.json" +store_chunk_env_path: "{{ ucloud_etc_dir }}/chunk-store.env" +store_verify_tokens_match_gateway: true +release_dir: "" diff --git a/infra/ansible/roles/store/handlers/main.yml b/infra/ansible/roles/store/handlers/main.yml new file mode 100644 index 00000000..db2bc913 --- /dev/null +++ b/infra/ansible/roles/store/handlers/main.yml @@ -0,0 +1,14 @@ +--- +- name: Reload systemd + ansible.builtin.systemd_service: + daemon_reload: true + +- name: Restart store services + ansible.builtin.systemd_service: + name: "{{ item }}.service" + state: restarted + loop: + - ucloud-chunk-index + - ucloud-chunk-store + - ucloud-chunk-serve + - ucloud-package-cache diff --git a/infra/ansible/roles/store/tasks/main.yml b/infra/ansible/roles/store/tasks/main.yml new file mode 100644 index 00000000..eab4420b --- /dev/null +++ b/infra/ansible/roles/store/tasks/main.yml @@ -0,0 +1,154 @@ +--- +- name: Ensure core store directories exist + ansible.builtin.file: + path: "{{ item.path }}" + state: directory + owner: "{{ item.owner | default('root') }}" + group: "{{ item.group | default('root') }}" + mode: "{{ item.mode | default('0755') }}" + loop: + - { path: "{{ ucloud_etc_dir }}" } + - { path: "{{ ucloud_libexec_dir }}" } + - { path: "{{ ucloud_install_root }}" } + - { path: "/var/cache/ucloud-sandboxes" } + - { path: "/var/lib/ucloud-package-cache", owner: "{{ ucloud_user }}", group: "{{ ucloud_group }}", mode: "0700" } + when: not (store_upgrade_only | default(false) | bool) + +- name: Ensure declarative store mount points and fstab entries exist + when: + - not (store_upgrade_only | default(false) | bool) + - store_mounts | length > 0 + block: + - name: Create store mount target directories + ansible.builtin.file: + path: "{{ item.path }}" + state: directory + owner: "{{ item.owner | default(omit) }}" + group: "{{ item.group | default(omit) }}" + mode: "{{ item.mode | default(omit) }}" + loop: "{{ store_mounts }}" + + - name: Ensure fstab entries for store mounts + ansible.builtin.lineinfile: + path: /etc/fstab + regexp: "^\\S+\\s+{{ item.path | regex_escape }}\\s+" + line: "{{ item.src }} {{ item.path }} {{ item.fstype }} {{ item.opts }} {{ item.dump | default(0) }} {{ item.passno | default(0) }}" + loop: "{{ store_mounts }}" + + - name: Check mount state for store mounts + ansible.builtin.command: "mountpoint -q {{ item.path }}" + loop: "{{ store_mounts }}" + register: store_mount_checks + changed_when: false + failed_when: false + + - name: Mount unmounted store filesystems + ansible.builtin.command: "mount {{ item.item.path }}" + loop: "{{ store_mount_checks.results }}" + when: item.rc != 0 + changed_when: true + +- name: Deploy store release artifacts when release_dir is provided + when: (release_dir | default('') | length) > 0 + block: + - name: Check if ucloud-chunk-serve exists in release_dir + ansible.builtin.stat: + path: "{{ release_dir }}/ucloud-chunk-serve" + delegate_to: localhost + become: false + register: release_chunk_serve + + - name: Install ucloud-chunk-serve binary from release_dir + ansible.builtin.copy: + src: "{{ release_dir }}/ucloud-chunk-serve" + dest: "{{ store_chunk_serve_binary }}" + owner: root + group: root + mode: "0755" + when: release_chunk_serve.stat.exists + notify: Restart store services + + - name: Locate wheel in release_dir for store python runtime + ansible.builtin.find: + paths: "{{ release_dir }}" + patterns: "*.whl" + delegate_to: localhost + become: false + register: store_release_wheels + + - name: Unpack updated sandboxes package into store install root + when: store_release_wheels.files | length > 0 + block: + - name: Copy wheel to store /tmp + ansible.builtin.copy: + src: "{{ store_release_wheels.files[0].path }}" + dest: "/tmp/{{ store_release_wheels.files[0].path | basename }}" + mode: "0644" + + - name: Install sandboxes wheel into store site-packages + ansible.builtin.command: >- + python3 -m pip install --no-deps --upgrade --target {{ ucloud_install_root }}/site-packages + /tmp/{{ store_release_wheels.files[0].path | basename }} + changed_when: true + notify: Restart store services + +- name: Render store systemd unit files + ansible.builtin.template: + src: "{{ item }}.service.j2" + dest: "/etc/systemd/system/{{ item }}.service" + owner: root + group: root + mode: "0644" + loop: + - ucloud-chunk-index + - ucloud-chunk-store + - ucloud-chunk-serve + - ucloud-package-cache + notify: + - Reload systemd + - Restart store services + +- name: Ensure all store services are enabled and running + ansible.builtin.systemd_service: + name: "{{ item }}.service" + enabled: true + state: started + loop: + - ucloud-chunk-index + - ucloud-chunk-store + - ucloud-chunk-serve + - ucloud-package-cache + +- name: Verify store chunk-index tokens match gateway (prevents split-brain 401s) + when: + - store_verify_tokens_match_gateway | bool + - not (store_upgrade_only | default(false) | bool) + - groups['gateway'] is defined + - groups['gateway'] | length > 0 + - hostvars[groups['gateway'][0]]['gateway_chunk_token_stats'] is defined + block: + - name: Stat store chunk-index read/write tokens + ansible.builtin.stat: + path: "{{ ucloud_chunk_tokens_dir }}/{{ item }}" + checksum_algorithm: sha256 + loop: + - read.token + - write.token + register: store_chunk_token_stats + + - name: Assert store and gateway chunk-index tokens have identical SHA-256 checksums + ansible.builtin.assert: + that: + - store_item.stat.exists + - gw_item.stat.exists + - store_item.stat.checksum == gw_item.stat.checksum + fail_msg: >- + Chunk-index token mismatch between gateway and store for {{ store_item.item }}! + Copy the authoritative token from store to gateway {{ ucloud_chunk_tokens_dir }}/{{ store_item.item }} + and restart gateway services. + loop: "{{ store_chunk_token_stats.results | zip(hostvars[groups['gateway'][0]]['gateway_chunk_token_stats']['results']) | list }}" + loop_control: + label: "{{ store_item.item }}" + vars: + store_item: "{{ item[0] }}" + gw_item: "{{ item[1] }}" diff --git a/infra/ansible/roles/store/templates/ucloud-chunk-index.service.j2 b/infra/ansible/roles/store/templates/ucloud-chunk-index.service.j2 new file mode 100644 index 00000000..8d2df200 --- /dev/null +++ b/infra/ansible/roles/store/templates/ucloud-chunk-index.service.j2 @@ -0,0 +1,22 @@ +[Unit] +Description=UCloud chunk store index on the store node +Wants=network-online.target +After=network-online.target +RequiresMountsFor=/var/lib/ucloud-chunk-store/cache /var/lib/ucloud-chunk-index + +[Service] +Type=simple +User={{ ucloud_user }} +Group={{ ucloud_group }} +EnvironmentFile={{ store_chunk_env_path }} +ExecStart={{ ucloud_install_root }}/bin/sandboxes serve-chunk-index --chunk-store-config {{ store_chunk_config_path }} +Restart=always +RestartSec=2 +# Exit 78: not configured to run here; stay stopped. +SuccessExitStatus=78 +RestartPreventExitStatus=78 +LimitNOFILE=262144 +TasksMax=infinity + +[Install] +WantedBy=multi-user.target diff --git a/infra/ansible/roles/store/templates/ucloud-chunk-serve.service.j2 b/infra/ansible/roles/store/templates/ucloud-chunk-serve.service.j2 new file mode 100644 index 00000000..cd006c31 --- /dev/null +++ b/infra/ansible/roles/store/templates/ucloud-chunk-serve.service.j2 @@ -0,0 +1,22 @@ +[Unit] +Description=UCloud chunk store reads (runtime/chunk_serve) +Wants=network-online.target +After=network-online.target +RequiresMountsFor=/var/lib/ucloud-chunk-store/cache /var/lib/ucloud-chunk-index + +[Service] +Type=simple +User={{ ucloud_user }} +Group={{ ucloud_group }} +EnvironmentFile={{ store_chunk_env_path }} +ExecStart={{ store_chunk_serve_binary }} --config {{ store_chunk_config_path }} --upstream {{ store_chunk_serve_upstream }} +Restart=always +RestartSec=2 +# Exit 78: not configured to run here; stay stopped. +SuccessExitStatus=78 +RestartPreventExitStatus=78 +LimitNOFILE=262144 +TasksMax=infinity + +[Install] +WantedBy=multi-user.target diff --git a/infra/ansible/roles/store/templates/ucloud-chunk-store.service.j2 b/infra/ansible/roles/store/templates/ucloud-chunk-store.service.j2 new file mode 100644 index 00000000..8d71eeb9 --- /dev/null +++ b/infra/ansible/roles/store/templates/ucloud-chunk-store.service.j2 @@ -0,0 +1,22 @@ +[Unit] +Description=UCloud chunk store node (chunk_store.store_node) +Wants=network-online.target +After=network-online.target +RequiresMountsFor=/var/lib/ucloud-chunk-store/cache /var/lib/ucloud-chunk-index + +[Service] +Type=simple +User={{ ucloud_user }} +Group={{ ucloud_group }} +EnvironmentFile={{ store_chunk_env_path }} +ExecStart={{ ucloud_install_root }}/bin/sandboxes serve-chunk-store --chunk-store-config {{ store_chunk_config_path }} +Restart=always +RestartSec=2 +# Exit 78: not configured to run here; stay stopped. +SuccessExitStatus=78 +RestartPreventExitStatus=78 +LimitNOFILE=262144 +TasksMax=infinity + +[Install] +WantedBy=multi-user.target diff --git a/infra/ansible/roles/store/templates/ucloud-package-cache.service.j2 b/infra/ansible/roles/store/templates/ucloud-package-cache.service.j2 new file mode 100644 index 00000000..c93072d4 --- /dev/null +++ b/infra/ansible/roles/store/templates/ucloud-package-cache.service.j2 @@ -0,0 +1,21 @@ +[Unit] +Description=UCloud build package cache (store_node.package_cache) +Wants=network-online.target +After=network-online.target + +[Service] +Type=simple +User={{ ucloud_user }} +Group={{ ucloud_group }} +EnvironmentFile={{ store_chunk_env_path }} +ExecStart={{ ucloud_install_root }}/bin/sandboxes serve-package-cache --chunk-store-config {{ store_chunk_config_path }} +Restart=always +RestartSec=2 +# Exit 78: not configured to run here; stay stopped. +SuccessExitStatus=78 +RestartPreventExitStatus=78 +LimitNOFILE=262144 +TasksMax=infinity + +[Install] +WantedBy=multi-user.target diff --git a/infra/ansible/site.yml b/infra/ansible/site.yml new file mode 100644 index 00000000..fbc4668f --- /dev/null +++ b/infra/ansible/site.yml @@ -0,0 +1,30 @@ +--- +- name: Converge permanent gateway hosts + hosts: gateway + become: true + roles: + - role: common + vars: + common_ucloud_home: "{{ ucloud_data_parent }}" + common_journald_max_use: "{{ gateway_journald_max_use }}" + common_sysctl: "{{ gateway_sysctl }}" + - role: gateway + - role: gateway_nat + when: gateway_nat_enabled | bool + - role: gateway_ingress + when: gateway_ingress_mode == "nginx_tls" + - role: observability + when: observability_enabled | bool + - role: ops + when: (ops_backups_enabled | bool) or (ops_watch_enabled | bool) + +- name: Converge permanent store hosts + hosts: store + become: true + roles: + - role: common + vars: + common_ucloud_home: "{{ store_ucloud_home }}" + common_journald_max_use: "{{ store_journald_max_use }}" + common_sysctl: "{{ store_sysctl }}" + - role: store diff --git a/infra/ansible/upgrade.yml b/infra/ansible/upgrade.yml new file mode 100644 index 00000000..d5c26518 --- /dev/null +++ b/infra/ansible/upgrade.yml @@ -0,0 +1,34 @@ +--- +# Fast application release rollout for already-provisioned gateway and store hosts. +# +# Usage: +# ansible-playbook -i ../../.deploy/prod/inventory.yml upgrade.yml \ +# -e release_dir=../../dist/releases/0.10.13 + +- name: Validate release_dir input + hosts: localhost + connection: local + gather_facts: false + tasks: + - name: Require release_dir variable + ansible.builtin.assert: + that: + - release_dir is defined + - (release_dir | trim | length) > 0 + fail_msg: "Pass -e release_dir=/path/to/release built by scripts/release/build_release.py" + +- name: Roll out gateway release artifacts and reconcile + hosts: gateway + become: true + roles: + - role: gateway + vars: + gateway_upgrade_only: true + +- name: Roll out store release artifacts and restart chunk services + hosts: store + become: true + roles: + - role: store + vars: + store_upgrade_only: true diff --git a/infra/hetzner/.terraform.lock.hcl b/infra/hetzner/.terraform.lock.hcl new file mode 100644 index 00000000..cf557c81 --- /dev/null +++ b/infra/hetzner/.terraform.lock.hcl @@ -0,0 +1,23 @@ +# This file is maintained automatically by "tofu init". +# Manual edits may be lost in future updates. + +provider "registry.opentofu.org/hetznercloud/hcloud" { + version = "1.71.0" + constraints = "~> 1.49" + hashes = [ + "h1:Rq6OzZu+5f6mnbjpzKIDK75FbWtbcFN4yodIicAnUww=", + "zh:01980accbeb167295671b10159dedb7204bac595857577187bf94021eb4af712", + "zh:3097f213d1b5330f8787fd6f790e7bae274feb70c5b5f13ffe4f524157da8cf5", + "zh:53a61f0edb8e01c8c009277df7f1181cbf995a28c3bc8fa54237a55384f2c530", + "zh:57c197a8d507dfc4a84ae6247dc1d56468a38de08a4a5f619eefe777f237fbe9", + "zh:7641e4b828ce880c29b25f89c8264d731de1eaec94a0782f65b49d79ff963f29", + "zh:7c12b800dd54a25df17022e386834a42e896302d69f18c323523f33e768af59f", + "zh:883eeab4468f97be5261439701e3e61da9f10b82deeebea06b7a22b083384645", + "zh:8ac84ab3ccf28f069c0a91553649d15eb6c11f66e2c1d7d11db89385aa9302b7", + "zh:97c98b829ecea2c4904f1fcd558b3c36dc1cc9b129a579467caa05dcdbd22f00", + "zh:a707972184a9a419cf337c1cd1aee4afa8eeede0a0c3a95cadd0d95be903d435", + "zh:c05954badd2a051ea0996f6f612fc9f0f86a7f4ae7bcda9edb9a4aa64231aa9e", + "zh:da938cba1bfc46f2cf0cbbd684a939957dd1fe5a5a62c469c107d2eb12022335", + "zh:f1dbba4e084cbc1c9fa7b350765dffd75ed3b9c4c892048fc636a7c1a9339637", + ] +} diff --git a/infra/hetzner/README.md b/infra/hetzner/README.md new file mode 100644 index 00000000..2977f12d --- /dev/null +++ b/infra/hetzner/README.md @@ -0,0 +1,25 @@ +# Hetzner Cloud Permanent Infrastructure (OpenTofu) + +Manages the permanent Hetzner Cloud resources for a sandboxes deployment: + +- Private network, subnet, and default egress route via the gateway private IP +- Bootstrap SSH key and worker/gateway firewalls +- Protected Primary IPv4 addresses (`auto_delete = false`, `prevent_destroy = true`) +- Protected persistent chunk-store volume (`prevent_destroy = true`) +- Gateway VM and Store VM (default `cpx32`, 4 vCPU / 8 GiB / 160 GiB NVMe) + +Ephemeral sandbox workers and builders remain managed by the gateway autoscaler. + +## Usage + +Keep environment files outside Git (for example under `.deploy//`, which is gitignored): + +```bash +export HCLOUD_TOKEN="$HETZNER_API_KEY" +cd infra/hetzner +tofu init +tofu plan -var-file=../../.deploy/prod/hetzner.tfvars +tofu apply -var-file=../../.deploy/prod/hetzner.tfvars +``` + +To adopt an existing Hetzner deployment with zero downtime, import each existing resource ID once (`tofu import -var-file=...
`) and verify `tofu plan` reports `No changes`. diff --git a/infra/hetzner/main.tf b/infra/hetzner/main.tf new file mode 100644 index 00000000..bffd4a98 --- /dev/null +++ b/infra/hetzner/main.tf @@ -0,0 +1,179 @@ +locals { + foundation_labels = { + "ucloud-sandboxes/foundation" = var.foundation_env + "ucloud-sandboxes/managed" = "true" + } +} + +resource "hcloud_network" "main" { + name = var.name + ip_range = var.network_cidr + expose_routes_to_vswitch = false + labels = local.foundation_labels +} + +resource "hcloud_network_subnet" "main" { + network_id = hcloud_network.main.id + type = "cloud" + network_zone = var.network_zone + ip_range = var.subnet_cidr +} + +resource "hcloud_network_route" "egress" { + network_id = hcloud_network.main.id + destination = "0.0.0.0/0" + gateway = var.gateway_private_ip + + depends_on = [hcloud_network_subnet.main] +} + +resource "hcloud_ssh_key" "init" { + name = "${var.name}-init" + public_key = trimspace(var.ssh_public_key) + labels = local.foundation_labels +} + +resource "hcloud_firewall" "workers" { + name = "${var.name}-workers" + labels = local.foundation_labels +} + +resource "hcloud_firewall" "gateway" { + name = "${var.name}-gateway" + labels = local.foundation_labels + + dynamic "rule" { + for_each = length(var.gateway_ssh_source_cidrs) > 0 ? [1] : [] + content { + description = "Operator SSH" + direction = "in" + protocol = "tcp" + port = "22" + source_ips = var.gateway_ssh_source_cidrs + } + } + + rule { + description = "ACME and HTTPS redirect" + direction = "in" + protocol = "tcp" + port = "80" + source_ips = ["0.0.0.0/0", "::/0"] + } + + rule { + description = "Sandbox SDK HTTPS" + direction = "in" + protocol = "tcp" + port = "443" + source_ips = ["0.0.0.0/0", "::/0"] + } +} + +resource "hcloud_primary_ip" "gateway" { + name = var.gateway_primary_ip_name + location = var.location + type = "ipv4" + auto_delete = false + + lifecycle { + prevent_destroy = true + } +} + +resource "hcloud_primary_ip" "store" { + name = var.store_primary_ip_name + location = var.location + type = "ipv4" + auto_delete = false + + lifecycle { + prevent_destroy = true + } +} + +resource "hcloud_volume" "chunk_store" { + name = "${var.name}-chunk-store" + size = var.chunk_store_volume_size_gb + location = var.location + format = "ext4" + labels = { + "ucloud-sandboxes/manual" = "true" + "ucloud-sandboxes/role" = "store" + } + + lifecycle { + prevent_destroy = true + ignore_changes = [format] + } +} + +resource "hcloud_server" "gateway" { + name = var.gateway_server_name + server_type = var.gateway_server_type + image = var.server_image + location = var.location + ssh_keys = [hcloud_ssh_key.init.id] + firewall_ids = [hcloud_firewall.gateway.id] + keep_disk = true + labels = { + "ucloud-sandboxes/manual" = "true" + "ucloud-sandboxes/role" = "gateway" + } + + public_net { + ipv4_enabled = true + ipv4 = hcloud_primary_ip.gateway.id + ipv6_enabled = false + } + + lifecycle { + ignore_changes = [image, ssh_keys, user_data] + } +} + +resource "hcloud_server_network" "gateway" { + server_id = hcloud_server.gateway.id + network_id = hcloud_network.main.id + ip = var.gateway_private_ip + + depends_on = [hcloud_network_subnet.main] +} + +resource "hcloud_server" "store" { + name = var.store_server_name + server_type = var.store_server_type + image = var.server_image + location = var.location + ssh_keys = [hcloud_ssh_key.init.id] + firewall_ids = [hcloud_firewall.workers.id] + keep_disk = true + labels = { + "ucloud-sandboxes/manual" = "true" + "ucloud-sandboxes/role" = "store" + } + + public_net { + ipv4_enabled = true + ipv4 = hcloud_primary_ip.store.id + ipv6_enabled = false + } + + lifecycle { + ignore_changes = [image, ssh_keys, user_data] + } +} + +resource "hcloud_server_network" "store" { + server_id = hcloud_server.store.id + network_id = hcloud_network.main.id + ip = var.store_private_ip + + depends_on = [hcloud_network_subnet.main] +} + +resource "hcloud_volume_attachment" "chunk_store" { + volume_id = hcloud_volume.chunk_store.id + server_id = hcloud_server.store.id + automount = false +} diff --git a/infra/hetzner/outputs.tf b/infra/hetzner/outputs.tf new file mode 100644 index 00000000..d4c73508 --- /dev/null +++ b/infra/hetzner/outputs.tf @@ -0,0 +1,39 @@ +output "network_id" { + value = hcloud_network.main.id +} + +output "ssh_key_id" { + value = hcloud_ssh_key.init.id +} + +output "worker_firewall_id" { + value = hcloud_firewall.workers.id +} + +output "gateway_firewall_id" { + value = hcloud_firewall.gateway.id +} + +output "gateway_public_ip" { + value = hcloud_primary_ip.gateway.ip_address +} + +output "gateway_private_ip" { + value = var.gateway_private_ip +} + +output "store_public_ip" { + value = hcloud_primary_ip.store.ip_address +} + +output "store_private_ip" { + value = var.store_private_ip +} + +output "chunk_store_volume_id" { + value = hcloud_volume.chunk_store.id +} + +output "chunk_store_volume_device" { + value = hcloud_volume.chunk_store.linux_device +} diff --git a/infra/hetzner/terraform.tfvars.example b/infra/hetzner/terraform.tfvars.example new file mode 100644 index 00000000..55c88a81 --- /dev/null +++ b/infra/hetzner/terraform.tfvars.example @@ -0,0 +1,22 @@ +# Copy this file to a gitignored location (e.g. .deploy/prod/hetzner.tfvars) +# and fill in environment-specific values. Never commit real IPs or keys. + +name = "ucloud-sandboxes-production" +foundation_env = "production" +location = "hel1" +network_zone = "eu-central" +network_cidr = "10.42.0.0/16" +subnet_cidr = "10.42.0.0/24" +gateway_private_ip = "10.42.0.2" +store_private_ip = "10.42.0.200" +gateway_server_type = "cpx32" +store_server_type = "cpx32" +chunk_store_volume_size_gb = 1000 + +# Restrict port 22 to operator CIDRs (empty list disables public SSH). +gateway_ssh_source_cidrs = [ + "203.0.113.10/32", +] + +# Contents of your bootstrap SSH public key (e.g. gateway-init.pub). +ssh_public_key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEXAMPLEKEYMATERIALREPLACEME operator@example" diff --git a/infra/hetzner/variables.tf b/infra/hetzner/variables.tf new file mode 100644 index 00000000..80014c68 --- /dev/null +++ b/infra/hetzner/variables.tf @@ -0,0 +1,113 @@ +variable "hcloud_token" { + description = "Hetzner Cloud API token (defaults to HCLOUD_TOKEN env var when null)." + type = string + default = null + sensitive = true +} + +variable "name" { + description = "Foundation name prefix for network, firewalls, SSH key, and chunk-store volume." + type = string + default = "ucloud-sandboxes-production" +} + +variable "foundation_env" { + description = "Value of the ucloud-sandboxes/foundation label." + type = string + default = "production" +} + +variable "location" { + description = "Hetzner Cloud location for servers, primary IPs, and volumes." + type = string + default = "hel1" +} + +variable "network_zone" { + description = "Hetzner Cloud private network zone." + type = string + default = "eu-central" +} + +variable "network_cidr" { + description = "Private network CIDR." + type = string + default = "10.42.0.0/16" +} + +variable "subnet_cidr" { + description = "Private subnet CIDR." + type = string + default = "10.42.0.0/24" +} + +variable "gateway_private_ip" { + description = "Static private IP of the gateway VM (also used as the network default egress route)." + type = string + default = "10.42.0.2" +} + +variable "store_private_ip" { + description = "Static private IP of the chunk-store VM." + type = string + default = "10.42.0.200" +} + +variable "ssh_public_key" { + description = "SSH public key material for bootstrap access to gateway, store, and workers." + type = string +} + +variable "gateway_ssh_source_cidrs" { + description = "Operator CIDRs allowed to reach SSH (port 22) on the gateway firewall." + type = list(string) + default = [] +} + +variable "server_image" { + description = "Base OS image for newly created permanent VMs." + type = string + default = "ubuntu-26.04" +} + +variable "gateway_server_name" { + description = "Hetzner server name for the gateway VM." + type = string + default = "ucloud-sandboxes-gateway" +} + +variable "gateway_server_type" { + description = "Hetzner server type for the gateway VM." + type = string + default = "cpx32" +} + +variable "store_server_name" { + description = "Hetzner server name for the store VM." + type = string + default = "ucloud-sandboxes-store" +} + +variable "store_server_type" { + description = "Hetzner server type for the store VM." + type = string + default = "cpx32" +} + +variable "chunk_store_volume_size_gb" { + description = "Size in GiB of the persistent Hetzner volume attached to the store VM." + type = number + default = 1000 +} + +variable "gateway_primary_ip_name" { + description = "Hetzner Primary IPv4 resource name for the gateway VM." + type = string + default = "ucloud-sandboxes-gateway-ipv4" +} + +variable "store_primary_ip_name" { + description = "Hetzner Primary IPv4 resource name for the store VM." + type = string + default = "ucloud-sandboxes-store-ipv4" +} diff --git a/infra/hetzner/versions.tf b/infra/hetzner/versions.tf new file mode 100644 index 00000000..96b8ba96 --- /dev/null +++ b/infra/hetzner/versions.tf @@ -0,0 +1,19 @@ +terraform { + required_version = ">= 1.8.0" + + required_providers { + hcloud = { + source = "hetznercloud/hcloud" + version = "~> 1.49" + } + } + + # Optional remote S3 state (e.g., Hetzner Object Storage). + # Pass `-backend-config=.deploy//backend.hcl` to `tofu init`. + # To keep local state while testing, run `tofu init -backend=false` or omit the backend block. +} + +provider "hcloud" { + # Reads HCLOUD_TOKEN from the environment by default. + token = var.hcloud_token +} diff --git a/sandboxes/deploy.py b/sandboxes/deploy.py index d5d3e649..67aeeed4 100644 --- a/sandboxes/deploy.py +++ b/sandboxes/deploy.py @@ -31,6 +31,7 @@ DEFAULT_PROJECT_MOUNT_DIR = "/work/data" SYSTEMD_UNIT_NAMES = ( "ucloud-sandbox-gateway.service", + "ucloud-sandbox-gatewayd.service", "ucloud-sandbox-placement.service", "ucloud-sandbox-relay.service", "ucloud-sandbox-registry.service", diff --git a/sandboxes/systemd.py b/sandboxes/systemd.py index f8dfaac6..1bae4bde 100644 --- a/sandboxes/systemd.py +++ b/sandboxes/systemd.py @@ -34,6 +34,9 @@ REGISTRY_CONFIG_PATH = "/etc/distribution/config.yml" REGISTRY_S3_CHUNK_BYTES = 32 * 1024 * 1024 REGISTRY_SERVICE = "ucloud-sandbox-registry.service" +GATEWAYD_SERVICE = "ucloud-sandbox-gatewayd.service" +GATEWAYD_BINARY = Path("/usr/local/libexec/ucloud-gatewayd") +GATEWAYD_UNIT = Path("/etc/systemd/system") / GATEWAYD_SERVICE CHUNK_INDEX_SERVICE = "ucloud-sandbox-chunk-index.service" # flock(1) in the prune unit locks the same file: ".lock". REGISTRY_MAINTENANCE_LOCK = Path("/run/lock/ucloud-sandbox-registry-maintenance") @@ -402,12 +405,24 @@ def reconcile_gateway_services( config: DeploymentConfig, runner: CommandRunner = subprocess.run, wait_for: HealthWaiter = wait_for_http, + gatewayd_binary: Path = GATEWAYD_BINARY, + gatewayd_unit: Path = GATEWAYD_UNIT, ) -> None: """Converge the provider-independent gateway service graph once.""" def systemctl(*arguments: str, check: bool = True) -> None: runner(["systemctl", *arguments], check=check, text=True) + gatewayd_present = gatewayd_binary.is_file() and gatewayd_unit.is_file() + core_services = ( + "ucloud-sandbox-placement.service", + "ucloud-sandbox-gateway.service", + *((GATEWAYD_SERVICE,) if gatewayd_present else ()), + "ucloud-sandbox-relay.service", + "ucloud-sandbox-autoscaler.service", + "ucloud-sandbox-builds.service", # Exits 78 while sandbox_builds is off. + ) + systemctl("daemon-reload") systemctl("enable", "ucloud-sandbox-registry.service") systemctl("enable", "--now", "ucloud-sandbox-registry-prune.timer") @@ -427,13 +442,7 @@ def systemctl(*arguments: str, check: bool = True) -> None: "ucloud-sandbox-snapshot-gc.service", check=False, ) - for service in ( - "ucloud-sandbox-placement.service", - "ucloud-sandbox-gateway.service", - "ucloud-sandbox-relay.service", - "ucloud-sandbox-autoscaler.service", - "ucloud-sandbox-builds.service", # Exits 78 while sandbox_builds is off. - ): + for service in core_services: systemctl("enable", service) # ucloud-chunk-index (decision 5: on the gateway until C2.6), only once # immutable_environments.chunk_store is configured. @@ -458,13 +467,7 @@ def systemctl(*arguments: str, check: bool = True) -> None: wait_for(f"upstream mirror {upstream.registry}", mirror.local_url(upstream) + "/v2/") systemctl("restart", "ucloud-sandbox-registry.service") wait_for("registry", f"http://127.0.0.1:{config.registry_port}/v2/") - for service in ( - "ucloud-sandbox-placement.service", - "ucloud-sandbox-gateway.service", - "ucloud-sandbox-relay.service", - "ucloud-sandbox-autoscaler.service", - "ucloud-sandbox-builds.service", - ): + for service in core_services: systemctl("restart", service) wait_for("gateway", f"http://127.0.0.1:{config.gateway_port}/healthz") wait_for("relay", f"http://127.0.0.1:{config.relay_port}/healthz") diff --git a/sandboxes/systemd/ucloud-sandbox-gatewayd.service b/sandboxes/systemd/ucloud-sandbox-gatewayd.service new file mode 100644 index 00000000..70ef9a3d --- /dev/null +++ b/sandboxes/systemd/ucloud-sandbox-gatewayd.service @@ -0,0 +1,23 @@ +[Unit] +Description=UCloud Sandbox Go fast-path gateway front door (ucloud-gatewayd) +After=network-online.target ucloud-sandbox-gateway.service +Wants=network-online.target ucloud-sandbox-gateway.service + +[Service] +Type=simple +User=ucloud +Group=ucloud +ExecStart=/usr/local/libexec/ucloud-gatewayd \ + --listen 0.0.0.0:8090 \ + --upstream http://127.0.0.1:18090 \ + --gateway-token-file /var/lib/ucloud-sandboxes/state/gateway-token \ + --sandbox-api-token-file /var/lib/ucloud-sandboxes/state/sandbox-api-token \ + --node-control-token-file /var/lib/ucloud-sandboxes/state/node-control-token \ + --heartbeat-ttl 45s \ + --route-cache-ttl 30s +LimitNOFILE=65536 +Restart=always +RestartSec=1 + +[Install] +WantedBy=multi-user.target diff --git a/scripts/release/build_release.py b/scripts/release/build_release.py new file mode 100644 index 00000000..5bb4bc20 --- /dev/null +++ b/scripts/release/build_release.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +"""Build a digest-pinned control-plane/store release directory for Ansible upgrades. + +Produces one self-contained output directory containing: + - sandboxes--py3-none-any.whl + - ucloud-gatewayd (static Linux Go binary from runtime/gatewayd) + - ucloud-chunk-serve (static Linux Go binary from runtime/chunk_serve) + - manifest.json (version, git sha, SHA-256 digests) +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess + + +REPO_ROOT = Path(__file__).resolve().parents[2] + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _run(cmd: list[str], *, cwd: Path, env: dict[str, str] | None = None) -> None: + subprocess.run(cmd, cwd=str(cwd), env=env, check=True) + + +def _git_sha() -> str: + result = subprocess.run( + ["git", "rev-parse", "--short", "HEAD"], + cwd=str(REPO_ROOT), + capture_output=True, + text=True, + check=False, + ) + return result.stdout.strip() or "unknown" + + +def build_release( + out_dir: Path, + *, + goarch: str = "amd64", + skip_wheel: bool = False, + skip_go: bool = False, +) -> dict[str, object]: + out = out_dir.resolve() + out.mkdir(parents=True, exist_ok=True) + artifacts: dict[str, dict[str, object]] = {} + + if not skip_wheel: + wheel_tmp = out / ".wheel-build" + if wheel_tmp.exists(): + shutil.rmtree(wheel_tmp) + wheel_tmp.mkdir(parents=True) + _run(["uv", "build", "--wheel", "--out-dir", str(wheel_tmp)], cwd=REPO_ROOT) + wheels = sorted(wheel_tmp.glob("*.whl")) + if len(wheels) != 1: + raise RuntimeError(f"expected 1 wheel in {wheel_tmp}, found {len(wheels)}") + target_wheel = out / wheels[0].name + shutil.copy2(wheels[0], target_wheel) + shutil.rmtree(wheel_tmp) + artifacts["wheel"] = { + "filename": target_wheel.name, + "sha256": _sha256(target_wheel), + "bytes": target_wheel.stat().st_size, + } + + if not skip_go: + go_env = { + **os.environ, + "CGO_ENABLED": "0", + "GOOS": "linux", + "GOARCH": goarch, + "GOTOOLCHAIN": "local", + } + for name, rel_dir in ( + ("ucloud-gatewayd", "runtime/gatewayd"), + ("ucloud-chunk-serve", "runtime/chunk_serve"), + ): + target = out / name + _run( + ["go", "build", "-trimpath", "-ldflags=-s -w", "-o", str(target), "."], + cwd=REPO_ROOT / rel_dir, + env=go_env, + ) + target.chmod(0o755) + artifacts[name] = { + "filename": name, + "sha256": _sha256(target), + "bytes": target.stat().st_size, + "goarch": goarch, + } + + manifest: dict[str, object] = { + "schema": 1, + "git_sha": _git_sha(), + "artifacts": artifacts, + } + (out / "manifest.json").write_text( + json.dumps(manifest, indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + return manifest + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out", type=Path, required=True, help="Output release directory") + parser.add_argument("--goarch", default="amd64", help="Target Linux GOARCH (default: amd64)") + parser.add_argument("--skip-wheel", action="store_true") + parser.add_argument("--skip-go", action="store_true") + args = parser.parse_args(argv) + manifest = build_release( + args.out, + goarch=args.goarch, + skip_wheel=args.skip_wheel, + skip_go=args.skip_go, + ) + print(json.dumps(manifest, indent=2, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_systemd.py b/tests/test_systemd.py index 23a1f509..5bdf9cfc 100644 --- a/tests/test_systemd.py +++ b/tests/test_systemd.py @@ -226,6 +226,40 @@ def runner(command: list[str], *, check: bool, text: bool) -> subprocess.Complet self.assertIn(["systemctl", "disable", "--now", "ucloud-sandbox-snapshot-gc.timer"], commands) self.assertEqual(health, ["registry", "gateway", "relay"]) + def test_gateway_reconcile_manages_gatewayd_when_installed(self) -> None: + with TemporaryDirectory() as raw_dir: + root = Path(raw_dir) + binary = root / "ucloud-gatewayd" + unit = root / "ucloud-sandbox-gatewayd.service" + binary.write_text("#!/bin/sh\n", encoding="utf-8") + unit.write_text("[Unit]\n", encoding="utf-8") + + commands: list[list[str]] = [] + reconcile_gateway_services( + config=DeploymentConfig.default("project"), + runner=lambda command, *, check, text: commands.append(command) + or subprocess.CompletedProcess(command, 0, "", ""), + wait_for=lambda _name, _url: None, + gatewayd_binary=binary, + gatewayd_unit=unit, + ) + self.assertIn(["systemctl", "enable", "ucloud-sandbox-gatewayd.service"], commands) + self.assertIn(["systemctl", "restart", "ucloud-sandbox-gatewayd.service"], commands) + gw_idx = commands.index(["systemctl", "restart", "ucloud-sandbox-gateway.service"]) + gd_idx = commands.index(["systemctl", "restart", "ucloud-sandbox-gatewayd.service"]) + self.assertLess(gw_idx, gd_idx) + + commands_without: list[list[str]] = [] + reconcile_gateway_services( + config=DeploymentConfig.default("project"), + runner=lambda command, *, check, text: commands_without.append(command) + or subprocess.CompletedProcess(command, 0, "", ""), + wait_for=lambda _name, _url: None, + gatewayd_binary=root / "missing-gatewayd", + gatewayd_unit=unit, + ) + self.assertNotIn(["systemctl", "restart", "ucloud-sandbox-gatewayd.service"], commands_without) + if __name__ == "__main__": unittest.main() From 03b03c1d93c6caeea3dcc60df935e5e6f976d680 Mon Sep 17 00:00:00 2001 From: Rasmus Larsen Date: Wed, 2 Dec 2026 21:06:14 +0000 Subject: [PATCH 2/2] Absorb observability and ingress natively into Ansible and delete 6 legacy installers --- docs/operations.md | 64 +-- .../roles/gateway_ingress/defaults/main.yml | 8 + .../roles/gateway_ingress/handlers/main.yml | 9 + .../roles/gateway_ingress/tasks/main.yml | 188 ++++++- .../templates/nginx-site.conf.j2 | 133 +++++ .../ucloud-sandbox-certbot-renew.service.j2 | 8 + .../roles/observability/defaults/main.yml | 4 + .../roles/observability/tasks/main.yml | 95 +++- .../observability/templates/collector.yaml.j2 | 49 ++ .../templates/grafana-dashboards.yaml.j2 | 11 + .../templates/grafana-datasources.yaml.j2 | 37 ++ .../observability/templates/scrape.yaml.j2 | 8 + .../observability/templates/tempo.yaml.j2 | 28 + scripts/ops/configure_hetzner_sdk_ingress.sh | 506 ------------------ scripts/ops/install_hetzner_gateway.sh | 400 -------------- scripts/ops/install_ucloud_gateway.sh | 113 ---- .../ops/install_ucloud_observability_stack.sh | 411 -------------- scripts/ops/install_ucloud_ops.sh | 75 --- scripts/ops/setup_hetzner_foundation.py | 394 -------------- tests/test_declarative_infra.py | 86 +++ tests/test_deploy.py | 14 +- tests/test_hetzner_foundation.py | 28 - tests/test_nginx_ingress.py | 125 ----- tests/test_registry_disk.py | 6 +- tests/test_rules_baseline.json | 3 - tests/test_ucloud_observability_stack.py | 44 -- tests/test_upstream_mirror.py | 6 +- 27 files changed, 672 insertions(+), 2181 deletions(-) create mode 100644 infra/ansible/roles/gateway_ingress/handlers/main.yml create mode 100644 infra/ansible/roles/gateway_ingress/templates/nginx-site.conf.j2 create mode 100644 infra/ansible/roles/gateway_ingress/templates/ucloud-sandbox-certbot-renew.service.j2 create mode 100644 infra/ansible/roles/observability/templates/collector.yaml.j2 create mode 100644 infra/ansible/roles/observability/templates/grafana-dashboards.yaml.j2 create mode 100644 infra/ansible/roles/observability/templates/grafana-datasources.yaml.j2 create mode 100644 infra/ansible/roles/observability/templates/scrape.yaml.j2 create mode 100644 infra/ansible/roles/observability/templates/tempo.yaml.j2 delete mode 100755 scripts/ops/configure_hetzner_sdk_ingress.sh delete mode 100755 scripts/ops/install_hetzner_gateway.sh delete mode 100755 scripts/ops/install_ucloud_gateway.sh delete mode 100755 scripts/ops/install_ucloud_observability_stack.sh delete mode 100644 scripts/ops/install_ucloud_ops.sh delete mode 100644 scripts/ops/setup_hetzner_foundation.py create mode 100644 tests/test_declarative_infra.py delete mode 100644 tests/test_hetzner_foundation.py delete mode 100644 tests/test_nginx_ingress.py delete mode 100644 tests/test_ucloud_observability_stack.py diff --git a/docs/operations.md b/docs/operations.md index a6816c66..d56bc462 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -102,14 +102,9 @@ variable, and the UCloud session is a separate file. Apply changes with `/work/ucloud-sandboxes/gateway-venv`, creates missing credentials and the SSH bootstrap key (registering it with UCloud), installs config and units, and runs `gateway-reconcile`. Rerunning it keeps existing credentials. -5. **Install ops tooling** on the gateway: - - ```bash - sudo scripts/ops/install_ucloud_ops.sh --backups \ - --public-gateway --public-relay - sudo scripts/ops/install_ucloud_observability_stack.sh \ - --private-bind-ip 0.0.0.0 --endpoint-host - ``` +5. **Converge ops tooling and observability** on the gateway with Ansible + (`infra/ansible/site.yml` using an inventory based on + `infra/ansible/inventories/ucloud.example/`). 6. **Create the store node**, if the chunk store uses one: steps 1, 3 and 4 of [Store node lost](#store-node-lost), without the restore. @@ -245,13 +240,13 @@ replay. Never repair a node by hand-installing a different artifact. ## Backups -`install_ucloud_ops.sh` installs two timers (it refuses a backup directory -outside `/work`): +The `ops` Ansible role (`infra/ansible/roles/ops/`) installs two timers with +configurable retention (`ops_backup_gateway_keep`, `ops_backup_chunk_index_keep`): -| Timer | Contents | Kept | +| Timer | Contents | Default kept | | --- | --- | --- | -| `ucloud-sandbox-backup-gateway` (hourly) | `postgres.dump`, `state/` (online SQLite copies, tokens, SSH and producer keys, UCloud session), `etc/`, chunk-index tokens, `manifest.json` with SHA-256s | 48 | -| `ucloud-sandbox-backup-chunk-index` (6 h) | The store node's index, `quick_check`ed and gzipped | 8 | +| `ucloud-sandbox-backup-gateway` (hourly) | `postgres.dump`, `state/` (online SQLite copies, tokens, SSH and producer keys, UCloud session), `etc/`, chunk-index tokens, `manifest.json` with SHA-256s | 4 (Hetzner) / 24 (UCloud) | +| `ucloud-sandbox-backup-chunk-index` (6 h) | The store node's index, `quick_check`ed and gzipped | 2 (Hetzner) / 4 (UCloud) | Run either by hand: `backup_gateway_state.py gateway|chunk-index --dest --keep ` as root on the gateway. To verify a snapshot: check the digests in @@ -273,7 +268,7 @@ recovery. Alerts go to `journalctl -u ucloud-sandbox-ops-watch`; set `ALERT_WEBHOOK_URL=` in `/etc/ucloud-sandboxes/alerts.env` (mode 0600) to post them to a Slack-compatible webhook. Thresholds are `ops_watch.py` options. -**Telemetry.** `install_ucloud_observability_stack.sh` runs an OTLP +**Telemetry.** The `observability` Ansible role (`infra/ansible/roles/observability/`) runs an OTLP collector (port 4318), Tempo (72 h), VictoriaMetrics (14 days) and Grafana 13 on the gateway's local disk (never on `/work`); losing the gateway loses it. Grafana and the collector keep running when Tempo or VictoriaMetrics restarts. @@ -291,9 +286,8 @@ Operation counts (`ucloud_platform_operation_count_total`) carry a `status`: exists; the client retries) or `conflict` (a routing transaction rolled back by a serialization conflict and retried). Only `error` is a failure. -Grafana is public at `https:///grafana/` with `--public-url` on -the installer and `--grafana-port 3000` on `configure_hetzner_sdk_ingress.sh`; -otherwise tunnel `-L 3000:127.0.0.1:3000`. Its table actions (drain, evict or +Grafana is public at `https:///grafana/` when `gateway_ingress_mode: nginx_tls` +and `observability_enabled: true` in Ansible; otherwise tunnel `-L 3000:127.0.0.1:3000`. Its table actions (drain, evict or undrain a worker; cancel queued creates and builds) call `/grafana/ops/`, which nginx forwards to the gateway's operator routes with the gateway token, only for a signed-in Grafana session sending `X-UCloud-Ops: 1`. @@ -377,16 +371,9 @@ workers re-register on their next heartbeat. 1. Create a VM like the old gateway: private network, project drive, both public links, the same hostname if possible. 2. `apt-get install ca-certificates curl docker.io nftables openssl python3-venv postgresql-18` -3. Stage the installer's inputs from the newest backup in `$STAGE` (mode 0700): - `state.tar` (`tar -cf state.tar state`), `ucloud.pgdump` (from - `postgres.dump`), `deployment.json`, `postgres.dsn` and `s3.env` (from - `etc/`), `ucloud-session.json` (from `state/`), `release/` with the live - kit's two bundles, and the live kit's wheel. -4. `sudo scripts/ops/install_ucloud_gateway.sh`. It restores PostgreSQL and the - state directory (refusing existing ones), installs venv, units and - drop-ins, and stops before starting services. Copy the chunk-index tokens - from the backup to `/var/lib/ucloud-chunk-index/`. -5. **Only if the hostname changed**, rehome the registry. As the service user, +3. Restore PostgreSQL (`pg_restore` from `postgres.dump`), `state/`, `etc/`, + and `/var/lib/ucloud-chunk-index/{read,write}.token` from the newest backup. +4. **Only if the hostname changed**, rehome the registry. As the service user, with gateway services stopped (review the counts, then add `--execute`): ```bash @@ -397,8 +384,9 @@ workers re-register on their next heartbeat. It rewrites the registry host in every stored image reference. Then update the DNS-named keys listed under [Machines](#machines-and-their-state); clients must change `guest_relay_url`. -6. Run `gateway-reconcile`. -7. Rerun `install_ucloud_ops.sh` and `install_ucloud_observability_stack.sh`. +5. Run `ansible-playbook -i infra/ansible/site.yml -e release_dir=` + (which installs the wheel, `ucloud-gatewayd`, units, ops timers, observability, + and runs `gateway-reconcile`). ## Credentials @@ -449,17 +437,13 @@ Required keys: `scope_id`, `network_id`, `sandbox_image`, `builder_image` (default `HETZNER_API_KEY`). Private-only workers need `enable_private_egress: true`, with the gateway NATing their traffic. -1. `scripts/ops/setup_hetzner_foundation.py --egress-gateway-ip --execute` - (network, SSH key, firewalls). -2. Prepare PostgreSQL as in UCloud step 3. -3. Stage the wheel, `deployment.json`, both bundles, the SSH key pair, the - Hetzner env file and `configure_hetzner_sdk_ingress.sh` in `/tmp`; run - `scripts/ops/install_hetzner_gateway.sh --public-ip `. -4. `scripts/ops/configure_hetzner_sdk_ingress.sh --public-host ` (Nginx - and Let's Encrypt; relay under `/relay/`). -5. `install_ucloud_observability_stack.sh --private-bind-ip 10.42.0.2 - --public-url https:///grafana/`, then rerun step 4 with - `--grafana-port 3000`. +1. Provision network, firewalls, SSH key, protected Primary IPv4s, store volume, + and permanent Gateway/Store VMs with OpenTofu (`infra/hetzner/`). +2. Build a release directory (`uv run python scripts/release/build_release.py --out dist/releases/`). +3. Converge Gateway and Store hosts with Ansible (`infra/ansible/site.yml`, + using an inventory based on `infra/ansible/inventories/hetzner.example/`), + which configures PostgreSQL 18, mounts, `ucloud-gatewayd`, private worker NAT, + Nginx + Let's Encrypt TLS ingress, observability, and backups. Hetzner caps dedicated cores per project; past the cap creates fail with `resource_limit_exceeded` (the autoscaler logs `Create failed:`) and the diff --git a/infra/ansible/roles/gateway_ingress/defaults/main.yml b/infra/ansible/roles/gateway_ingress/defaults/main.yml index fabf1114..1e0991f6 100644 --- a/infra/ansible/roles/gateway_ingress/defaults/main.yml +++ b/infra/ansible/roles/gateway_ingress/defaults/main.yml @@ -1,5 +1,13 @@ --- +ucloud_data_parent: /var/lib/ucloud-sandboxes +ucloud_data_root: "{{ ucloud_data_parent }}/state" +gateway_port: 8090 gateway_public_host: "" gateway_relay_port: 8092 gateway_grafana_port: 3000 observability_enabled: true +gateway_ingress_acme_webroot: /var/lib/ucloud-sandboxes-acme +gateway_ingress_certbot_venv: /opt/ucloud-sandboxes-certbot +gateway_ingress_worker_connections: 4096 +gateway_ingress_worker_rlimit_nofile: 65536 +gateway_ingress_cert_name: "" diff --git a/infra/ansible/roles/gateway_ingress/handlers/main.yml b/infra/ansible/roles/gateway_ingress/handlers/main.yml new file mode 100644 index 00000000..7eb5bbc8 --- /dev/null +++ b/infra/ansible/roles/gateway_ingress/handlers/main.yml @@ -0,0 +1,9 @@ +--- +- name: Reload systemd + ansible.builtin.systemd_service: + daemon_reload: true + +- name: Reload nginx + ansible.builtin.systemd_service: + name: nginx.service + state: reloaded diff --git a/infra/ansible/roles/gateway_ingress/tasks/main.yml b/infra/ansible/roles/gateway_ingress/tasks/main.yml index 7ae45b53..08f78921 100644 --- a/infra/ansible/roles/gateway_ingress/tasks/main.yml +++ b/infra/ansible/roles/gateway_ingress/tasks/main.yml @@ -1,38 +1,187 @@ --- +- name: Require gateway_public_host when nginx_tls ingress is enabled + ansible.builtin.assert: + that: + - (gateway_public_host | default('') | trim | length) > 0 + fail_msg: "gateway_public_host must be set when gateway_ingress_mode == 'nginx_tls'" + - name: Install nginx for TLS ingress ansible.builtin.apt: name: - nginx state: present -- name: Install ingress helper script - ansible.builtin.copy: - src: "{{ playbook_dir }}/../../scripts/ops/configure_hetzner_sdk_ingress.sh" - dest: /usr/local/sbin/configure-hetzner-sdk-ingress +- name: Ensure ACME HTTP-01 webroot exists + ansible.builtin.file: + path: "{{ gateway_ingress_acme_webroot }}" + state: directory owner: root group: root mode: "0755" -- name: Check whether nginx gateway site is already configured +- name: Ensure Certbot virtual environment exists + ansible.builtin.command: "python3 -m venv {{ gateway_ingress_certbot_venv }}" + args: + creates: "{{ gateway_ingress_certbot_venv }}/bin/python" + +- name: Install Certbot into dedicated virtual environment when missing + ansible.builtin.command: "{{ gateway_ingress_certbot_venv }}/bin/pip install --disable-pip-version-check certbot" + args: + creates: "{{ gateway_ingress_certbot_venv }}/bin/certbot" + +- name: Ensure nginx worker_connections is at least {{ gateway_ingress_worker_connections }} + ansible.builtin.replace: + path: /etc/nginx/nginx.conf + regexp: '^(\s*worker_connections\s+)(?:[1-9][0-9]{0,2}|[1-3][0-9]{3});' + replace: '\g<1>{{ gateway_ingress_worker_connections }};' + notify: Reload nginx + +- name: Disable default nginx site + ansible.builtin.file: + path: /etc/nginx/sites-enabled/default + state: absent + notify: Reload nginx + +- name: Sync Grafana ops proxy gateway-token include file + ansible.builtin.shell: | + set -euo pipefail + tok="$(tr -d '\r\n' < "{{ ucloud_data_root }}/gateway-token")" + dest="/etc/nginx/ucloud-sandboxes-ops-token.conf" + tmp="$(mktemp)" + trap 'rm -f "$tmp"' EXIT + printf 'proxy_set_header Authorization "Bearer %s";\n' "$tok" > "$tmp" + if [ ! -f "$dest" ] || ! cmp -s "$tmp" "$dest"; then + install -m 0600 -o root -g root "$tmp" "$dest" + echo CHANGED + fi + args: + executable: /bin/bash + register: nginx_ops_token + changed_when: "'CHANGED' in nginx_ops_token.stdout" + when: observability_enabled | bool + notify: Reload nginx + +- name: Discover existing Let's Encrypt certificate name under /etc/letsencrypt/live + ansible.builtin.find: + paths: /etc/letsencrypt/live + file_type: directory + patterns: "ucloud-sandbox-gateway-*" + register: existing_le_certs + failed_when: false + +- name: Resolve active TLS certificate name + ansible.builtin.set_fact: + gateway_ingress_resolved_cert_name: >- + {{ + gateway_ingress_cert_name + if (gateway_ingress_cert_name | length) > 0 + else ( + (existing_le_certs.files | sort(attribute='path') | first).path | basename + if (existing_le_certs.files | default([]) | length) > 0 + else ('ucloud-sandbox-gateway-' ~ (gateway_public_host | hash('sha256'))[:16]) + ) + }} + +- name: Check whether TLS certificate already exists on disk ansible.builtin.stat: - path: /etc/nginx/sites-enabled/ucloud-sandbox-gateway - register: nginx_site_stat - -- name: Configure TLS ingress when bootstrapping or explicitly requested - ansible.builtin.command: >- - /usr/local/sbin/configure-hetzner-sdk-ingress - --public-host {{ gateway_public_host }} - --relay-port {{ gateway_relay_port }} - {% if observability_enabled | bool %}--grafana-port {{ gateway_grafana_port }}{% endif %} - when: - - (gateway_public_host | length) > 0 - - (not nginx_site_stat.stat.exists) or (configure_ingress | default(false) | bool) - changed_when: true + path: "/etc/letsencrypt/live/{{ gateway_ingress_resolved_cert_name }}/fullchain.pem" + register: tls_cert_stat + +- name: Obtain initial Let's Encrypt certificate via HTTP-01 when absent + when: not tls_cert_stat.stat.exists + block: + - name: Write temporary HTTP-only ACME challenge site + ansible.builtin.copy: + dest: /etc/nginx/sites-available/ucloud-sandbox-gateway + owner: root + group: root + mode: "0644" + content: | + server { + listen 80; + listen [::]:80; + server_name {{ gateway_public_host }}; + server_tokens off; + location ^~ /.well-known/acme-challenge/ { + root {{ gateway_ingress_acme_webroot }}; + default_type text/plain; + } + location / { + return 404; + } + } + + - name: Enable temporary ACME site + ansible.builtin.file: + src: /etc/nginx/sites-available/ucloud-sandbox-gateway + dest: /etc/nginx/sites-enabled/ucloud-sandbox-gateway + state: link + + - name: Reload nginx for ACME challenge + ansible.builtin.systemd_service: + name: nginx.service + state: reloaded + + - name: Request certificate from Let's Encrypt + ansible.builtin.command: >- + {{ gateway_ingress_certbot_venv }}/bin/certbot certonly --non-interactive + --agree-tos --register-unsafely-without-email --webroot + -w {{ gateway_ingress_acme_webroot }} + --cert-name {{ gateway_ingress_resolved_cert_name }} + {% if gateway_public_host is match('^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$') %} + --preferred-profile shortlived --ip-address {{ gateway_public_host }} + {% else %} + -d {{ gateway_public_host }} + {% endif %} + changed_when: true + +- name: Render HTTPS nginx gateway site configuration + ansible.builtin.template: + src: nginx-site.conf.j2 + dest: /etc/nginx/sites-available/ucloud-sandbox-gateway + owner: root + group: root + mode: "0644" + notify: Reload nginx + +- name: Enable HTTPS nginx gateway site symlink + ansible.builtin.file: + src: /etc/nginx/sites-available/ucloud-sandbox-gateway + dest: /etc/nginx/sites-enabled/ucloud-sandbox-gateway + state: link + notify: Reload nginx - name: Validate nginx configuration ansible.builtin.command: nginx -t changed_when: false - when: nginx_site_stat.stat.exists + +- name: Install Certbot renewal systemd service + ansible.builtin.template: + src: ucloud-sandbox-certbot-renew.service.j2 + dest: /etc/systemd/system/ucloud-sandbox-certbot-renew.service + owner: root + group: root + mode: "0644" + notify: Reload systemd + +- name: Install Certbot renewal systemd timer + ansible.builtin.copy: + dest: /etc/systemd/system/ucloud-sandbox-certbot-renew.timer + owner: root + group: root + mode: "0644" + content: | + [Unit] + Description=Renew UCloud sandbox gateway TLS certificate twice daily + + [Timer] + OnCalendar=*-*-* 00,12:00:00 + RandomizedDelaySec=1h + Persistent=true + + [Install] + WantedBy=timers.target + notify: Reload systemd - name: Ensure nginx and certbot renewal timer are enabled and active ansible.builtin.systemd_service: @@ -42,4 +191,3 @@ loop: - nginx.service - ucloud-sandbox-certbot-renew.timer - when: nginx_site_stat.stat.exists diff --git a/infra/ansible/roles/gateway_ingress/templates/nginx-site.conf.j2 b/infra/ansible/roles/gateway_ingress/templates/nginx-site.conf.j2 new file mode 100644 index 00000000..d4c58b60 --- /dev/null +++ b/infra/ansible/roles/gateway_ingress/templates/nginx-site.conf.j2 @@ -0,0 +1,133 @@ +# The aiohttp relay releases request admission between keep-alive requests. +# Cache only a small idle pool per nginx worker, below its five-second timeout. +# The threaded gateway deliberately closes responses and is not pooled here. +upstream ucloud_model_relay { + server 127.0.0.1:{{ gateway_relay_port }}; + keepalive 8; + keepalive_requests 100; + keepalive_timeout 1s; +} + +# The model relay is published under /relay/ for inference workers outside +# the private network. The raw request URI is forwarded without the prefix: +# nginx must not decode percent-encoded rollout ids in tunnel paths. +map $request_uri $ucloud_relay_uri { + ~^/relay(?/.*)$ $rest; + default /; +} + +map $http_upgrade $ucloud_connection_upgrade { + default upgrade; + '' close; +} + +server { + listen 80; + listen [::]:80; + server_name {{ gateway_public_host }}; + server_tokens off; + + location ^~ /.well-known/acme-challenge/ { + root {{ gateway_ingress_acme_webroot }}; + default_type text/plain; + } + + location / { + return 308 https://$host$request_uri; + } +} + +server { + listen 443 ssl; + listen [::]:443 ssl; + server_name {{ gateway_public_host }}; + server_tokens off; + + ssl_certificate /etc/letsencrypt/live/{{ gateway_ingress_resolved_cert_name }}/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/{{ gateway_ingress_resolved_cert_name }}/privkey.pem; + ssl_protocols TLSv1.2 TLSv1.3; + ssl_session_timeout 1d; + ssl_session_cache shared:UCloudSandboxTLS:10m; + ssl_session_tickets off; + + client_max_body_size 256m; + proxy_request_buffering off; + proxy_buffering off; + proxy_connect_timeout 10s; + proxy_send_timeout 3600s; + proxy_read_timeout 3600s; + + location /relay/ { + proxy_pass http://ucloud_model_relay$ucloud_relay_uri; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-Proto https; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header Proxy-Authorization ""; + } +{% if observability_enabled | bool %} + + location /grafana/ { + proxy_pass http://127.0.0.1:{{ gateway_grafana_port }}; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $ucloud_connection_upgrade; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-Proto https; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + } + + location = /_ucloud_grafana_session { + internal; + proxy_pass http://127.0.0.1:{{ gateway_grafana_port }}/grafana/api/user; + proxy_pass_request_body off; + proxy_set_header Content-Length ""; + proxy_set_header Host $host; + # Grafana marks panel actions' requests with this header and refuses + # them on its own API (405), the session check included. + proxy_set_header X-Grafana-Action ""; + } + + # Panel actions send only GET or POST: POST .../undrain is DELETE .../drain. + location ~ ^/grafana/ops/v1/nodes/(?[^/]+)/undrain$ { + if ($http_x_ucloud_ops != 1) { + return 403; + } + auth_request /_ucloud_grafana_session; + include /etc/nginx/ucloud-sandboxes-ops-token.conf; + proxy_method DELETE; + proxy_pass http://127.0.0.1:{{ gateway_port }}/v1/nodes/$ucloud_ops_job/drain; + proxy_pass_request_body off; + proxy_http_version 1.1; + proxy_set_header Content-Length ""; + proxy_set_header Host $host; + proxy_set_header Cookie ""; + proxy_set_header X-Forwarded-Proto https; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + } + + location ~ ^/grafana/ops(?/v1/(?:nodes/[^/]+/drain|creates|creates:cancel|images/builds|images/builds/[^/]+:cancel))$ { + if ($http_x_ucloud_ops != 1) { + return 403; + } + auth_request /_ucloud_grafana_session; + include /etc/nginx/ucloud-sandboxes-ops-token.conf; + proxy_pass http://127.0.0.1:{{ gateway_port }}$ucloud_ops_path$is_args$args; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header Cookie ""; + proxy_set_header X-Forwarded-Proto https; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + } +{% endif %} + + location / { + proxy_pass http://127.0.0.1:{{ gateway_port }}; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-Proto https; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header Proxy-Authorization ""; + } +} diff --git a/infra/ansible/roles/gateway_ingress/templates/ucloud-sandbox-certbot-renew.service.j2 b/infra/ansible/roles/gateway_ingress/templates/ucloud-sandbox-certbot-renew.service.j2 new file mode 100644 index 00000000..03f6f759 --- /dev/null +++ b/infra/ansible/roles/gateway_ingress/templates/ucloud-sandbox-certbot-renew.service.j2 @@ -0,0 +1,8 @@ +[Unit] +Description=Renew UCloud sandbox gateway TLS certificate +After=network-online.target nginx.service +Wants=network-online.target + +[Service] +Type=oneshot +ExecStart={{ gateway_ingress_certbot_venv }}/bin/certbot renew --quiet --deploy-hook "/usr/bin/systemctl reload nginx.service" diff --git a/infra/ansible/roles/observability/defaults/main.yml b/infra/ansible/roles/observability/defaults/main.yml index e6f06db1..a9b55cd4 100644 --- a/infra/ansible/roles/observability/defaults/main.yml +++ b/infra/ansible/roles/observability/defaults/main.yml @@ -1,12 +1,15 @@ --- ucloud_data_parent: /var/lib/ucloud-sandboxes +ucloud_data_root: "{{ ucloud_data_parent }}/state" ucloud_etc_dir: /etc/ucloud-sandboxes gateway_private_ip: 10.42.0.2 +gateway_port: 8090 gateway_public_host: "" gateway_public_url: "" gateway_grafana_port: 3000 observability_private_bind_ip: "{{ gateway_private_ip }}" +observability_gateway_scrape_target: "{{ gateway_private_ip }}:{{ gateway_port }}" observability_data_root: "{{ ucloud_data_parent }}/telemetry" observability_config_root: "{{ ucloud_etc_dir }}/telemetry" observability_collector_image: "otel/opentelemetry-collector-contrib:0.153.0" @@ -20,6 +23,7 @@ observability_victoria_min_free_disk: 20GB observability_tempo_image: "grafana/tempo:2.10.7" observability_tempo_memory: 768m observability_tempo_cpus: "0.60" +observability_tempo_retention: 72h observability_grafana_image: "grafana/grafana:13.2.4" observability_grafana_memory: 768m observability_grafana_cpus: "1.0" diff --git a/infra/ansible/roles/observability/tasks/main.yml b/infra/ansible/roles/observability/tasks/main.yml index b9fde3d2..42ddd2c8 100644 --- a/infra/ansible/roles/observability/tasks/main.yml +++ b/infra/ansible/roles/observability/tasks/main.yml @@ -1,4 +1,10 @@ --- +- name: Refuse storing telemetry data on shared network mounts + ansible.builtin.assert: + that: + - not (observability_data_root is match('^(/work/|/mnt/ucloud/)')) + fail_msg: "observability_data_root must live on the gateway local disk, not under /work/ or /mnt/ucloud/" + - name: Ensure telemetry data and config directories exist ansible.builtin.file: path: "{{ item.path }}" @@ -12,19 +18,84 @@ - { path: "{{ observability_data_root }}/tempo", mode: "0700" } - { path: "{{ observability_data_root }}/grafana", owner: "{{ omit }}", group: "{{ omit }}", mode: "0750" } - { path: "{{ observability_config_root }}" } + - { path: "{{ observability_config_root }}/grafana" } + - { path: "{{ observability_config_root }}/grafana/dashboards" } + - { path: "{{ observability_config_root }}/grafana/provisioning" } + - { path: "{{ observability_config_root }}/grafana/provisioning/dashboards" } + - { path: "{{ observability_config_root }}/grafana/provisioning/datasources" } + +- name: Ensure Grafana data directory is owned by container UID 472 on fresh hosts + ansible.builtin.command: "chown 472:0 {{ observability_data_root }}/grafana" + args: + creates: "{{ observability_data_root }}/grafana/grafana.db" + changed_when: false -- name: Check if observability config files are bootstrapped - ansible.builtin.stat: - path: "{{ observability_config_root }}/collector.yaml" - register: obs_collector_cfg +- name: Sync read-only gateway-token copy for VictoriaMetrics and Grafana + ansible.builtin.shell: | + set -euo pipefail + src="{{ ucloud_data_root }}/gateway-token" + changed=0 + for entry in "{{ observability_config_root }}/gateway-token:0:0" "{{ observability_config_root }}/grafana/gateway-token:472:0"; do + dest="${entry%%:*}" + ug="${entry#*:}" + if [ ! -f "$dest" ] || ! cmp -s "$src" "$dest"; then + install -m 0400 "$src" "$dest" + chown "$ug" "$dest" + changed=1 + fi + done + if [ "$changed" -eq 1 ]; then echo CHANGED; fi + args: + executable: /bin/bash + register: telemetry_token_sync + changed_when: "'CHANGED' in telemetry_token_sync.stdout" + notify: Restart telemetry stack -- name: Bootstrap observability config files when missing - ansible.builtin.command: >- - {{ playbook_dir }}/../../scripts/ops/install_ucloud_observability_stack.sh - --private-bind-ip {{ observability_private_bind_ip }} - {% if (gateway_public_url | length) > 0 %}--public-url {{ gateway_public_url }}/grafana/{% endif %} - when: not obs_collector_cfg.stat.exists - changed_when: true +- name: Ensure Grafana admin credentials file exists without overwriting + ansible.builtin.shell: | + set -euo pipefail + env_file="{{ observability_config_root }}/grafana.env" + if [ ! -s "$env_file" ]; then + pw="$(openssl rand -base64 24 | tr -d '\n')" + (umask 077 && printf 'GF_SECURITY_ADMIN_USER=admin\nGF_SECURITY_ADMIN_PASSWORD=%s\n' "$pw" > "$env_file") + chmod 0600 "$env_file" + echo CHANGED + fi + args: + executable: /bin/bash + register: grafana_env_gen + changed_when: "'CHANGED' in grafana_env_gen.stdout" + +- name: Render observability service configuration files + ansible.builtin.template: + src: "{{ item.src }}" + dest: "{{ item.dest }}" + owner: root + group: root + mode: "0644" + loop: + - { src: collector.yaml.j2, dest: "{{ observability_config_root }}/collector.yaml" } + - { src: tempo.yaml.j2, dest: "{{ observability_config_root }}/tempo.yaml" } + - { src: scrape.yaml.j2, dest: "{{ observability_config_root }}/scrape.yaml" } + - { src: grafana-dashboards.yaml.j2, dest: "{{ observability_config_root }}/grafana/provisioning/dashboards/ucloud.yaml" } + - { src: grafana-datasources.yaml.j2, dest: "{{ observability_config_root }}/grafana/provisioning/datasources/ucloud.yaml" } + notify: Restart telemetry stack + +- name: Install Grafana Sandboxes dashboard JSON + ansible.builtin.copy: + src: "{{ playbook_dir }}/../../scripts/ops/grafana/dashboards/sandboxes.json" + dest: "{{ observability_config_root }}/grafana/dashboards/sandboxes.json" + owner: root + group: root + mode: "0644" + +- name: Install ucloud-observability-report CLI + ansible.builtin.copy: + src: "{{ playbook_dir }}/../../scripts/ops/ucloud_observability_report.py" + dest: /usr/local/bin/ucloud-observability-report + owner: root + group: root + mode: "0755" - name: Render declarative telemetry systemd units with resource caps ansible.builtin.template: @@ -38,7 +109,6 @@ - ucloud-telemetry-victoria - ucloud-telemetry-tempo - ucloud-telemetry-grafana - when: obs_collector_cfg.stat.exists notify: - Reload systemd - Restart telemetry stack @@ -53,4 +123,3 @@ - ucloud-telemetry-victoria - ucloud-telemetry-tempo - ucloud-telemetry-grafana - when: obs_collector_cfg.stat.exists diff --git a/infra/ansible/roles/observability/templates/collector.yaml.j2 b/infra/ansible/roles/observability/templates/collector.yaml.j2 new file mode 100644 index 00000000..f07025cf --- /dev/null +++ b/infra/ansible/roles/observability/templates/collector.yaml.j2 @@ -0,0 +1,49 @@ +extensions: + health_check: + endpoint: 0.0.0.0:13133 +receivers: + otlp: + protocols: + http: + endpoint: 0.0.0.0:4318 +processors: + memory_limiter: + check_interval: 1s + limit_mib: 192 + spike_limit_mib: 48 + batch: + send_batch_size: 512 + timeout: 2s +exporters: + otlp_grpc/tempo: + endpoint: ucloud-telemetry-tempo:4317 + tls: + insecure: true + sending_queue: + enabled: true + queue_size: 2048 + retry_on_failure: + enabled: true + max_elapsed_time: 60s + prometheusremotewrite/victoria: + endpoint: http://ucloud-telemetry-victoria:8428/api/v1/write + resource_to_telemetry_conversion: + enabled: true + remote_write_queue: + enabled: true + queue_size: 2048 + max_batch_request_parallelism: 1 +service: + extensions: [health_check] + pipelines: + traces: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlp_grpc/tempo] + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [prometheusremotewrite/victoria] + telemetry: + metrics: + level: normal diff --git a/infra/ansible/roles/observability/templates/grafana-dashboards.yaml.j2 b/infra/ansible/roles/observability/templates/grafana-dashboards.yaml.j2 new file mode 100644 index 00000000..75d3116b --- /dev/null +++ b/infra/ansible/roles/observability/templates/grafana-dashboards.yaml.j2 @@ -0,0 +1,11 @@ +apiVersion: 1 +providers: + - name: UCloud + orgId: 1 + folder: UCloud + type: file + disableDeletion: false + updateIntervalSeconds: 30 + allowUiUpdates: false + options: + path: /var/lib/grafana/dashboards diff --git a/infra/ansible/roles/observability/templates/grafana-datasources.yaml.j2 b/infra/ansible/roles/observability/templates/grafana-datasources.yaml.j2 new file mode 100644 index 00000000..2215f5f2 --- /dev/null +++ b/infra/ansible/roles/observability/templates/grafana-datasources.yaml.j2 @@ -0,0 +1,37 @@ +apiVersion: 1 +datasources: + - name: UCloud Metrics + uid: ucloud-metrics + type: prometheus + access: proxy + url: http://ucloud-telemetry-victoria:8428 + isDefault: true + editable: false + jsonData: + httpMethod: POST + timeInterval: 5s + - name: UCloud Traces + uid: ucloud-traces + type: tempo + access: proxy + url: http://ucloud-telemetry-tempo:3200 + editable: false + jsonData: + tracesToMetrics: + datasourceUid: ucloud-metrics + serviceMap: + datasourceUid: ucloud-metrics + nodeGraph: + enabled: true + # Live lists (queued creates, builds) straight from the gateway's API. + - name: Gateway + uid: ucloud-gateway + type: yesoreyeram-infinity-datasource + access: proxy + url: http://{{ observability_gateway_scrape_target }} + editable: false + jsonData: + allowedHosts: ["http://{{ observability_gateway_scrape_target }}"] + httpHeaderName1: Authorization + secureJsonData: + httpHeaderValue1: "Bearer $__file{/etc/grafana/gateway-token}" diff --git a/infra/ansible/roles/observability/templates/scrape.yaml.j2 b/infra/ansible/roles/observability/templates/scrape.yaml.j2 new file mode 100644 index 00000000..5ff73007 --- /dev/null +++ b/infra/ansible/roles/observability/templates/scrape.yaml.j2 @@ -0,0 +1,8 @@ +scrape_configs: + - job_name: ucloud-gateway + scrape_interval: 15s + scrape_timeout: 10s + metrics_path: /v1/metrics/prometheus + bearer_token_file: /etc/victoria/gateway-token + static_configs: + - targets: ["{{ observability_gateway_scrape_target }}"] diff --git a/infra/ansible/roles/observability/templates/tempo.yaml.j2 b/infra/ansible/roles/observability/templates/tempo.yaml.j2 new file mode 100644 index 00000000..b2cba917 --- /dev/null +++ b/infra/ansible/roles/observability/templates/tempo.yaml.j2 @@ -0,0 +1,28 @@ +stream_over_http_enabled: true +server: + http_listen_port: 3200 + grpc_listen_port: 9095 +distributor: + receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 +ingester: + max_block_duration: 5m + complete_block_timeout: 10m + flush_all_on_shutdown: true +compactor: + compaction: + block_retention: {{ observability_tempo_retention }} +storage: + trace: + backend: local + wal: + path: /var/tempo/wal + local: + path: /var/tempo/blocks +usage_report: + reporting_enabled: false diff --git a/scripts/ops/configure_hetzner_sdk_ingress.sh b/scripts/ops/configure_hetzner_sdk_ingress.sh deleted file mode 100755 index 9fc581da..00000000 --- a/scripts/ops/configure_hetzner_sdk_ingress.sh +++ /dev/null @@ -1,506 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -usage() { - cat >&2 <<'EOF' -usage: configure_hetzner_sdk_ingress.sh --public-host [options] - -Options: - --gateway-port Loopback gateway port (default: 8090) - --relay-port Loopback model relay port, published under /relay/ - (default: 8092) - --grafana-port Publish loopback Grafana under /grafana/ and its - operator controls under /grafana/ops/ (signed-in - Grafana sessions only; nginx adds the gateway token) - --gateway-token-file - Token /grafana/ops/ forwards with (default: - /var/lib/ucloud-sandboxes/state/gateway-token) - --email
ACME account email (recommended) - --staging Use Let's Encrypt staging for a non-trusted test cert -EOF -} - -public_host="" -gateway_port=8090 -relay_port=8092 -grafana_port="" -gateway_token_file=/var/lib/ucloud-sandboxes/state/gateway-token -email="" -staging=false -while (($#)); do - case "$1" in - --public-host) - if (($# < 2)); then - usage - exit 2 - fi - public_host="${2:-}" - shift 2 - ;; - --gateway-port) - if (($# < 2)); then - usage - exit 2 - fi - gateway_port="${2:-}" - shift 2 - ;; - --relay-port) - if (($# < 2)); then - usage - exit 2 - fi - relay_port="${2:-}" - shift 2 - ;; - --grafana-port) - if (($# < 2)); then - usage - exit 2 - fi - grafana_port="${2:-}" - shift 2 - ;; - --gateway-token-file) - if (($# < 2)); then - usage - exit 2 - fi - gateway_token_file="${2:-}" - shift 2 - ;; - --email) - if (($# < 2)); then - usage - exit 2 - fi - email="${2:-}" - shift 2 - ;; - --staging) - staging=true - shift - ;; - -h|--help) - usage - exit 0 - ;; - *) - usage - exit 2 - ;; - esac -done - -if [[ "$EUID" -ne 0 ]]; then - echo "SDK ingress configuration must run as root" >&2 - exit 2 -fi -if [[ ! "$gateway_port" =~ ^[0-9]+$ ]] \ - || ((gateway_port < 1 || gateway_port > 65535)); then - echo "gateway port must be between 1 and 65535" >&2 - exit 2 -fi -if [[ ! "$relay_port" =~ ^[0-9]+$ ]] \ - || ((relay_port < 1 || relay_port > 65535)); then - echo "relay port must be between 1 and 65535" >&2 - exit 2 -fi -if [[ -n "$grafana_port" ]] && { [[ ! "$grafana_port" =~ ^[0-9]+$ ]] \ - || ((grafana_port < 1 || grafana_port > 65535)); }; then - echo "grafana port must be between 1 and 65535" >&2 - exit 2 -fi -if [[ -n "$grafana_port" && ! -s "$gateway_token_file" ]]; then - echo "--gateway-token-file must name the gateway token" >&2 - exit 2 -fi -if [[ -z "$public_host" || "$public_host" == *:* || "$public_host" == */* ]]; then - echo "public host must be one DNS name or IPv4 address without a scheme or port" >&2 - exit 2 -fi - -host_kind="$({ - python3 - "$public_host" <<'PY' -import ipaddress -import re -import sys - -value = sys.argv[1] -try: - address = ipaddress.ip_address(value) -except ValueError: - address = None -if address is not None: - if address.version != 4 or not address.is_global: - raise SystemExit("the public IP must be a globally routable IPv4 address") - print("ip") -elif ( - len(value) <= 253 - and "." in value - and all( - re.fullmatch(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?", label) - for label in value.rstrip(".").split(".") - ) -): - print("dns") -else: - raise SystemExit("public host is not a valid DNS name or IPv4 address") -PY -} 2>&1)" || { - echo "$host_kind" >&2 - exit 2 -} -if [[ "$host_kind" == dns ]]; then - public_host="${public_host%.}" -fi - -export DEBIAN_FRONTEND=noninteractive -apt-get -o DPkg::Lock::Timeout=600 update -apt-get -o DPkg::Lock::Timeout=600 install -y --no-install-recommends \ - ca-certificates nginx python3-venv - -certbot_root=/opt/ucloud-sandboxes-certbot -if [[ ! -x "$certbot_root/bin/python" ]]; then - python3 -m venv "$certbot_root" -fi -"$certbot_root/bin/pip" install \ - --disable-pip-version-check \ - 'certbot>=5.4,<6' - -acme_webroot=/var/lib/ucloud-sandboxes-acme -install -d -m 0755 "$acme_webroot/.well-known/acme-challenge" -rm -f /etc/nginx/sites-enabled/default - -nginx_site=/etc/nginx/sites-available/ucloud-sandbox-gateway -nginx_enabled=/etc/nginx/sites-enabled/ucloud-sandbox-gateway -nginx_main=/etc/nginx/nginx.conf -temporary_site="$(mktemp)" -temporary_main="$(mktemp /etc/nginx/nginx.conf.ucloud.XXXXXX)" -previous_site="$(mktemp)" -trap 'rm -f "$temporary_site" "$temporary_main" "$previous_site"' EXIT - -install_nginx_site() { - # These limits apply per worker. Shrinking worker_processes=auto must not - # shrink ingress below the sockets needed by 500 agents and their proxies. - # Preserve the rest of the administrator's nginx configuration verbatim. - python3 - "$nginx_main" "$temporary_main" <<'PY_NGINX_CAPACITY' -from pathlib import Path -import re -import sys - -source = Path(sys.argv[1]).read_text() -tokens = list(re.finditer(r'''"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\#[^\n]*|[{};]|[^\s{};\#]+''', source)) -contexts, statement, edits = [], [], [] -found = set() -events_open = None -for token in tokens: - word = token.group() - if word.startswith("#"): - continue - if word == "{": - name = statement[0].group() if statement else "" - if not contexts and name == "events": - if events_open is not None: - raise SystemExit("nginx configuration has multiple events blocks") - events_open = token.end() - contexts.append(name) - statement = [] - elif word == "}": - if not contexts: - raise SystemExit("nginx configuration has an unmatched closing brace") - contexts.pop() - statement = [] - elif word == ";": - name = statement[0].group() if statement else "" - target = ((not contexts and name == "worker_rlimit_nofile") - or (contexts == ["events"] and name == "worker_connections")) - if target: - if name in found or len(statement) != 2: - raise SystemExit("nginx capacity directive is ambiguous: " + name) - found.add(name) - if not statement[1].group().isdigit(): - raise SystemExit("nginx capacity directive must be numeric: " + name) - minimum = 65536 if name == "worker_rlimit_nofile" else 4096 - value = str(max(minimum, int(statement[1].group()))) - edits.append((statement[1].start(), statement[1].end(), value)) - statement = [] - else: - statement.append(token) -if contexts or events_open is None: - raise SystemExit("nginx configuration must contain one complete events block") -if "worker_connections" not in found: - edits.append((events_open, events_open, "\n worker_connections 4096;")) -if "worker_rlimit_nofile" not in found: - edits.append((len(source), len(source), "\nworker_rlimit_nofile 65536;\n")) -for start, end, replacement in sorted(edits, reverse=True): - source = source[:start] + replacement + source[end:] -Path(sys.argv[2]).write_text(source) -PY_NGINX_CAPACITY - - local site_existed=false - if [[ -f "$nginx_site" ]]; then - cp -p "$nginx_site" "$previous_site" - site_existed=true - if ! cmp -s "$nginx_site" "$temporary_site"; then - local site_backup - site_backup="$(mktemp "${nginx_site}.ucloud-backup.XXXXXX")" - cp -p "$nginx_site" "$site_backup" - fi - fi - install -m 0644 "$temporary_site" "$nginx_site" - ln -sfn "$nginx_site" "$nginx_enabled" - # The running nginx keeps its old configuration throughout validation. - # Validate the new site and limits together before replacing nginx.conf. - if ! nginx -t -c "$temporary_main"; then - if [[ "$site_existed" == true ]]; then - cp -p "$previous_site" "$nginx_site" - else - rm -f "$nginx_site" "$nginx_enabled" - fi - return 1 - fi - if ! cmp -s "$nginx_main" "$temporary_main"; then - local main_backup - main_backup="$(mktemp "${nginx_main}.ucloud-backup.XXXXXX")" - cp -p "$nginx_main" "$main_backup" - install -m 0644 "$temporary_main" "$nginx_main" - fi -} - -cat >"$temporary_site" <"$ops_token_conf") - observability_maps=" -map \$http_upgrade \$ucloud_connection_upgrade { - default upgrade; - '' close; -} -" - # /grafana/ops/ carries Grafana panel actions to the gateway's operator - # routes (under /grafana/, where Grafana's session cookie is sent): only a - # signed-in session (auth_request) with the X-UCloud-Ops header reaches the - # few routes listed, and nginx adds the gateway token. Grafana never sees them. - observability_locations=" - location /grafana/ { - proxy_pass http://127.0.0.1:$grafana_port; - proxy_http_version 1.1; - proxy_set_header Upgrade \$http_upgrade; - proxy_set_header Connection \$ucloud_connection_upgrade; - proxy_set_header Host \$host; - proxy_set_header X-Forwarded-Proto https; - proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; - } - - location = /_ucloud_grafana_session { - internal; - proxy_pass http://127.0.0.1:$grafana_port/grafana/api/user; - proxy_pass_request_body off; - proxy_set_header Content-Length \"\"; - proxy_set_header Host \$host; - # Grafana marks panel actions' requests with this header and refuses - # them on its own API (405), the session check included. - proxy_set_header X-Grafana-Action \"\"; - } - - # Panel actions send only GET or POST: POST .../undrain is DELETE .../drain. - location ~ ^/grafana/ops/v1/nodes/(?[^/]+)/undrain\$ { - if (\$http_x_ucloud_ops != 1) { - return 403; - } - auth_request /_ucloud_grafana_session; - include $ops_token_conf; - proxy_method DELETE; - proxy_pass http://127.0.0.1:$gateway_port/v1/nodes/\$ucloud_ops_job/drain; - proxy_pass_request_body off; - proxy_http_version 1.1; - proxy_set_header Content-Length \"\"; - proxy_set_header Host \$host; - proxy_set_header Cookie \"\"; - proxy_set_header X-Forwarded-Proto https; - proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; - } - - location ~ ^/grafana/ops(?/v1/(?:nodes/[^/]+/drain|creates|creates:cancel|images/builds|images/builds/[^/]+:cancel))\$ { - if (\$http_x_ucloud_ops != 1) { - return 403; - } - auth_request /_ucloud_grafana_session; - include $ops_token_conf; - proxy_pass http://127.0.0.1:$gateway_port\$ucloud_ops_path\$is_args\$args; - proxy_http_version 1.1; - proxy_set_header Host \$host; - proxy_set_header Cookie \"\"; - proxy_set_header X-Forwarded-Proto https; - proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; - } -" -fi - -cat >"$temporary_site" </.*)\$ \$rest; - default /; -} -$observability_maps -server { - listen 80; - listen [::]:80; - server_name $public_host; - server_tokens off; - - location ^~ /.well-known/acme-challenge/ { - root $acme_webroot; - default_type text/plain; - } - - location / { - return 308 https://\$host\$request_uri; - } -} - -server { - listen 443 ssl; - listen [::]:443 ssl; - server_name $public_host; - server_tokens off; - - ssl_certificate $certificate_dir/fullchain.pem; - ssl_certificate_key $certificate_dir/privkey.pem; - ssl_protocols TLSv1.2 TLSv1.3; - ssl_session_timeout 1d; - ssl_session_cache shared:UCloudSandboxTLS:10m; - ssl_session_tickets off; - - client_max_body_size 256m; - proxy_request_buffering off; - proxy_buffering off; - proxy_connect_timeout 10s; - proxy_send_timeout 3600s; - proxy_read_timeout 3600s; - - location /relay/ { - proxy_pass http://ucloud_model_relay\$ucloud_relay_uri; - proxy_http_version 1.1; - proxy_set_header Connection ""; - proxy_set_header Host \$host; - proxy_set_header X-Forwarded-Proto https; - proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; - proxy_set_header Proxy-Authorization ""; - } -$observability_locations - location / { - proxy_pass http://127.0.0.1:$gateway_port; - proxy_http_version 1.1; - proxy_set_header Host \$host; - proxy_set_header X-Forwarded-Proto https; - proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; - proxy_set_header Proxy-Authorization ""; - } -} -EOF -install_nginx_site - -install -d -m 0755 /etc/systemd/system -cat >/etc/systemd/system/ucloud-sandbox-certbot-renew.service </etc/systemd/system/ucloud-sandbox-certbot-renew.timer <<'EOF' -[Unit] -Description=Renew UCloud sandbox gateway TLS certificate twice daily - -[Timer] -OnCalendar=*-*-* 00,12:00:00 -RandomizedDelaySec=1h -Persistent=true - -[Install] -WantedBy=timers.target -EOF - -nginx -t -systemctl daemon-reload -systemctl enable --now nginx.service ucloud-sandbox-certbot-renew.timer -systemctl reload nginx.service - -curl --fail --silent --show-error "https://$public_host/healthz" >/dev/null -curl --fail --silent --show-error "https://$public_host/relay/healthz" >/dev/null -printf 'sdk_url=https://%s\n' "$public_host" -printf 'relay_url=https://%s/relay\n' "$public_host" -printf 'tls_certificate=%s\n' "$certificate_dir/fullchain.pem" -printf 'gateway_upstream=http://127.0.0.1:%s\n' "$gateway_port" -if [[ -n "$grafana_port" ]]; then - printf 'grafana_url=https://%s/grafana/\n' "$public_host" -fi diff --git a/scripts/ops/install_hetzner_gateway.sh b/scripts/ops/install_hetzner_gateway.sh deleted file mode 100755 index f20ce4a1..00000000 --- a/scripts/ops/install_hetzner_gateway.sh +++ /dev/null @@ -1,400 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -usage() { - cat >&2 <<'EOF' -usage: install_hetzner_gateway.sh --public-ip [--volume-device ] - ---volume-device is required only when registry_store.kind=filesystem. - -The following release inputs must already be staged on the gateway: - /tmp/ucloud-sandboxes.whl - /tmp/ucloud-sandboxes-deployment.json - /tmp/ucloud-sandboxes-sandbox-node-package.tar.gz - /tmp/ucloud-sandboxes-builder-node-package.tar.gz - /tmp/ucloud-sandboxes-gateway-init - /tmp/ucloud-sandboxes-gateway-init.pub - /tmp/ucloud-sandboxes-hetzner.env - /tmp/configure_hetzner_sdk_ingress.sh - -Optional, for an upstream_mirror upstream with a credentials_file: - /tmp/ucloud-sandboxes-upstream-mirror-.env -EOF -} - -public_ip="" -volume_device="" -while (($#)); do - case "$1" in - --public-ip) - if (($# < 2)); then usage; exit 2; fi - public_ip="$2" - shift 2 - ;; - --volume-device) - if (($# < 2)); then usage; exit 2; fi - volume_device="$2" - shift 2 - ;; - -h|--help) - usage - exit 0 - ;; - *) - usage - exit 2 - ;; - esac -done - -if [[ "$EUID" -ne 0 ]]; then - echo "Hetzner gateway installation must run as root" >&2 - exit 2 -fi -if [[ ! "$public_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then - echo "--public-ip must be an IPv4 address" >&2 - exit 2 -fi -wheel=/tmp/ucloud-sandboxes.whl -deployment=/tmp/ucloud-sandboxes-deployment.json -sandbox_node_bundle=/tmp/ucloud-sandboxes-sandbox-node-package.tar.gz -builder_node_bundle=/tmp/ucloud-sandboxes-builder-node-package.tar.gz -init_key=/tmp/ucloud-sandboxes-gateway-init -init_public_key=/tmp/ucloud-sandboxes-gateway-init.pub -provider_env=/tmp/ucloud-sandboxes-hetzner.env -ingress=/tmp/configure_hetzner_sdk_ingress.sh -for required in \ - "$wheel" \ - "$deployment" \ - "$sandbox_node_bundle" \ - "$builder_node_bundle" \ - "$init_key" \ - "$init_public_key" \ - "$provider_env" \ - "$ingress"; do - if [[ ! -s "$required" ]]; then - echo "missing staged gateway input: $required" >&2 - exit 2 - fi -done - -python3 - "$sandbox_node_bundle" sandbox "$builder_node_bundle" builder <<'PY' -import json -import sys -import tarfile - -for raw_path, expected_role in zip(sys.argv[1::2], sys.argv[2::2], strict=True): - with tarfile.open(raw_path, "r:*") as archive: - manifests = [ - member - for member in archive.getmembers() - if member.name.lstrip("./") == "package-bundle.json" and member.isfile() - ] - if len(manifests) != 1: - raise SystemExit(f"{raw_path}: expected exactly one package-bundle.json") - source = archive.extractfile(manifests[0]) - if source is None: - raise SystemExit(f"{raw_path}: cannot read package-bundle.json") - manifest = json.load(source) - runtime = manifest.get("runtime") if isinstance(manifest, dict) else None - actual_role = runtime.get("role") if isinstance(runtime, dict) else None - if manifest.get("version") != 1 or actual_role != expected_role: - raise SystemExit( - f"{raw_path}: expected role={expected_role}, found role={actual_role}" - ) -PY - -registry_store_kind="$(python3 - "$deployment" <<'PY' -import json -import sys - -with open(sys.argv[1], encoding="utf-8") as source: - payload = json.load(source) -store = payload.get("registry_store") -if isinstance(store, dict): - print(store.get("kind", "")) -else: - # Schema 1-3 deployments used the filesystem registry implicitly. - print("filesystem") -PY -)" -if [[ "$registry_store_kind" != filesystem && "$registry_store_kind" != s3 ]]; then - echo "deployment registry_store.kind must be filesystem or s3" >&2 - exit 2 -fi -if [[ "$registry_store_kind" == filesystem && \ - ( -z "$volume_device" || "$volume_device" != /dev/* ) ]]; then - echo "--volume-device must be an absolute /dev path for filesystem registry storage" >&2 - exit 2 -fi - -# OS packages are updated only through explicit maintenance. -install -d -m 0755 /etc/apt/apt.conf.d -cat > /etc/apt/apt.conf.d/99zz-ucloud-no-unattended-upgrades <<'EOF' -APT::Periodic::Enable "0"; -APT::Periodic::Update-Package-Lists "0"; -APT::Periodic::Unattended-Upgrade "0"; -EOF -systemctl disable --now apt-daily.timer apt-daily-upgrade.timer -systemctl mask apt-daily.timer apt-daily-upgrade.timer apt-daily.service apt-daily-upgrade.service unattended-upgrades.service - -export DEBIAN_FRONTEND=noninteractive -apt-get -o DPkg::Lock::Timeout=600 update -apt-get -o DPkg::Lock::Timeout=600 install -y --no-install-recommends \ - ca-certificates curl docker.io nftables openssl python3-venv -systemctl enable --now docker.service - -registry_mount=/mnt/ucloud-registry -if [[ "$registry_store_kind" == filesystem ]]; then - for attempt in $(seq 1 60); do - if [[ -b "$volume_device" ]]; then break; fi - if [[ "$attempt" == 60 ]]; then - echo "registry Volume did not appear: $volume_device" >&2 - exit 1 - fi - sleep 1 - done - if [[ "$(blkid -o value -s TYPE "$volume_device")" != ext4 ]]; then - echo "registry Volume is not the expected preformatted ext4 filesystem" >&2 - exit 1 - fi - install -d -m 0755 "$registry_mount" - volume_uuid="$(blkid -o value -s UUID "$volume_device")" - if ! grep -qF "UUID=$volume_uuid $registry_mount " /etc/fstab; then - printf 'UUID=%s %s ext4 defaults,nofail,x-systemd.device-timeout=30s 0 2\n' \ - "$volume_uuid" "$registry_mount" >>/etc/fstab - fi - mount "$registry_mount" 2>/dev/null || mountpoint -q "$registry_mount" - mountpoint -q "$registry_mount" - install -d -m 0755 "$registry_mount/docker-registry" -fi - -if ! id ucloud >/dev/null 2>&1; then - useradd --system --create-home \ - --home-dir /var/lib/ucloud-sandboxes \ - --shell /usr/sbin/nologin \ - ucloud -fi - -install_root=/work/ucloud-sandboxes -release_dir="$install_root/release" -venv_dir="$install_root/gateway-venv" -data_root=/var/lib/ucloud-sandboxes/state -install -d -m 0755 "$install_root" "$release_dir" /etc/ucloud-sandboxes -install -d -m 0700 -o ucloud -g ucloud "$data_root" "$data_root/ssh" -install -m 0644 \ - "$sandbox_node_bundle" "$release_dir/sandbox-node-package.tar.gz" -install -m 0644 \ - "$builder_node_bundle" "$release_dir/builder-node-package.tar.gz" -install -m 0644 "$deployment" /etc/ucloud-sandboxes/deployment.json -install -m 0600 "$provider_env" /etc/ucloud-sandboxes/hetzner.env -install -m 0600 "$provider_env" /etc/ucloud-sandboxes/snapshot-store.env -install -m 0600 "$provider_env" /etc/ucloud-sandboxes/registry-store.env -# Opt-in upstream pull-through mirror (C2.15). An upstream with a -# credentials_file takes it from /tmp/ucloud-sandboxes-upstream-mirror-.env -# when staged, or keeps the one already installed; it is root-only either way. -# gateway-reconcile starts one ucloud-sandbox-upstream-mirror@ each. -mirror_credentials="$(python3 - "$deployment" <<'PY' -import json -import sys - -with open(sys.argv[1], encoding="utf-8") as source: - mirror = json.load(source).get("upstream_mirror") or {} -for upstream in mirror.get("upstreams", []): - if upstream.get("credentials_file"): - print(upstream["registry"] + "\t" + upstream["credentials_file"]) -PY -)" -while IFS=$'\t' read -r mirror_registry mirror_credentials_file; do - [[ -n "$mirror_registry" ]] || continue - staged_credentials="/tmp/ucloud-sandboxes-upstream-mirror-$mirror_registry.env" - if [[ -s "$staged_credentials" ]]; then - install -D -m 0600 -o root -g root "$staged_credentials" "$mirror_credentials_file" - rm -f "$staged_credentials" - fi - if [[ ! -s "$mirror_credentials_file" ]]; then - echo "missing upstream mirror credentials for $mirror_registry: $mirror_credentials_file" >&2 - exit 2 - fi - chown root:root "$mirror_credentials_file" - chmod 0600 "$mirror_credentials_file" -done <<< "$mirror_credentials" -install -m 0600 -o ucloud -g ucloud "$init_key" "$data_root/ssh/gateway-init" -install -m 0644 -o ucloud -g ucloud \ - "$init_public_key" "$data_root/ssh/gateway-init.pub" - -python3 -m venv "$venv_dir" -# pip requires a wheel filename that encodes its distribution and version. -wheel_name="$(python3 - "$wheel" <<'PY' -import sys -import zipfile - -with zipfile.ZipFile(sys.argv[1]) as archive: - metadata = next(name for name in archive.namelist() if name.endswith(".dist-info/METADATA")) - fields = dict( - line.split(": ", 1) - for line in archive.read(metadata).decode().splitlines() - if ": " in line - ) -print(f"{fields['Name'].replace('-', '_')}-{fields['Version']}-py3-none-any.whl") -PY -)" -wheel_dir="$(mktemp -d)" -cp "$wheel" "$wheel_dir/$wheel_name" -wheel="$wheel_dir/$wheel_name" -relay_extra="$(python3 -c 'import json,sys; print("[postgres]" if json.load(open(sys.argv[1])).get("relay_postgres") else "")' "$deployment")" -"$venv_dir/bin/pip" install --disable-pip-version-check --force-reinstall "$wheel$relay_extra" - -for name in \ - gateway-token \ - sandbox-api-token \ - heartbeat-token \ - node-control-token \ - relay-sandbox-token \ - relay-worker-token; do - token_path="$data_root/$name" - if [[ ! -s "$token_path" ]]; then - # Subshell: a leaked umask 077 made later webroots unreadable to nginx. - (umask 077 && openssl rand -hex 32 >"$token_path") - fi - chown ucloud:ucloud "$token_path" - chmod 0600 "$token_path" -done - -systemd_source="$($venv_dir/bin/python - <<'PY' -from importlib import resources -print(resources.files("sandboxes").joinpath("systemd")) -PY -)" -for unit in \ - ucloud-sandbox-autoscaler.service \ - ucloud-sandbox-gateway.service \ - ucloud-sandbox-placement.service \ - ucloud-sandbox-registry-gc.service \ - ucloud-sandbox-registry-gc.timer \ - ucloud-sandbox-registry-pressure.service \ - ucloud-sandbox-registry-pressure.timer \ - ucloud-sandbox-snapshot-gc.service \ - ucloud-sandbox-snapshot-gc.timer \ - ucloud-sandbox-chunk-index.service \ - ucloud-sandbox-registry-prune.service \ - ucloud-sandbox-registry-prune.timer \ - ucloud-sandbox-registry.service \ - ucloud-sandbox-relay.service \ - ucloud-sandbox-upstream-mirror@.service \ - ucloud-sandbox-upstream-mirror-trim.service \ - ucloud-sandbox-upstream-mirror-trim.timer; do - install -m 0644 "$systemd_source/$unit" "/etc/systemd/system/$unit" -done - -install -d -m 0755 \ - /etc/systemd/system/ucloud-sandbox-autoscaler.service.d \ - /etc/systemd/system/ucloud-sandbox-registry.service.d \ - /etc/systemd/system/ucloud-sandbox-registry-gc.service.d \ - /etc/systemd/system/ucloud-sandbox-registry-pressure.service.d \ - /etc/systemd/system/ucloud-sandbox-upstream-mirror@.service.d \ - /etc/systemd/system/ucloud-sandbox-upstream-mirror-trim.service.d -cat >/etc/systemd/system/ucloud-sandbox-autoscaler.service.d/hetzner.conf <<'EOF' -[Service] -EnvironmentFile=/etc/ucloud-sandboxes/hetzner.env -EOF -for unit in \ - ucloud-sandbox-registry.service \ - ucloud-sandbox-registry-gc.service \ - ucloud-sandbox-registry-pressure.service \ - ucloud-sandbox-upstream-mirror@.service \ - ucloud-sandbox-upstream-mirror-trim.service; do - if [[ "$registry_store_kind" == filesystem ]]; then - cat >"/etc/systemd/system/$unit.d/volume.conf" <<'EOF' -[Unit] -RequiresMountsFor=/mnt/ucloud-registry - -[Service] -ExecStartPre=/usr/bin/mountpoint -q /mnt/ucloud-registry -EOF - else - rm -f "/etc/systemd/system/$unit.d/volume.conf" - fi -done - -cat >/usr/local/sbin/ucloud-sandboxes-nat <<'EOF' -#!/usr/bin/env bash -set -euo pipefail -public_if="$(ip -4 route show default | awk 'NR == 1 {print $5}')" -private_if="$(ip -o -4 address show | awk '$4 ~ /^10\.42\.0\.2\// {print $2; exit}')" -if [[ -z "$public_if" || -z "$private_if" ]]; then - echo "could not resolve Hetzner public/private interfaces" >&2 - exit 1 -fi -nft delete table inet ucloud_sandboxes_nat 2>/dev/null || true -nft -f - </dev/null || true -iptables -F UCLOUD-SANDBOXES -iptables -A UCLOUD-SANDBOXES \ - -i "$private_if" -o "$public_if" -s 10.42.0.0/24 -j ACCEPT -iptables -A UCLOUD-SANDBOXES \ - -i "$public_if" -o "$private_if" -d 10.42.0.0/24 \ - -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT -iptables -A UCLOUD-SANDBOXES -j RETURN -if ! iptables -C DOCKER-USER -j UCLOUD-SANDBOXES 2>/dev/null; then - iptables -I DOCKER-USER 1 -j UCLOUD-SANDBOXES -fi -EOF -chmod 0755 /usr/local/sbin/ucloud-sandboxes-nat -cat >/etc/sysctl.d/90-ucloud-sandboxes-gateway.conf <<'EOF' -net.ipv4.ip_forward=1 -EOF -cat >/etc/systemd/system/ucloud-sandboxes-nat.service <<'EOF' -[Unit] -Description=UCloud Sandboxes private worker NAT -After=docker.service network-online.target -Wants=docker.service network-online.target - -[Service] -Type=oneshot -ExecStart=/usr/local/sbin/ucloud-sandboxes-nat -RemainAfterExit=yes - -[Install] -WantedBy=multi-user.target -EOF -sysctl --system >/dev/null - -systemctl enable --now ucloud-sandboxes-nat.service -"$venv_dir/bin/python" -m sandboxes.systemd \ - gateway-reconcile --config /etc/ucloud-sandboxes/deployment.json - -install -m 0755 "$ingress" /usr/local/sbin/configure-hetzner-sdk-ingress -relay_port="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("relay_port", 8092))' /etc/ucloud-sandboxes/deployment.json)" -/usr/local/sbin/configure-hetzner-sdk-ingress --public-host "$public_ip" --relay-port "$relay_port" - -rm -f \ - "$wheel" \ - "$deployment" \ - "$sandbox_node_bundle" \ - "$builder_node_bundle" \ - "$init_key" \ - "$init_public_key" \ - "$provider_env" \ - "$ingress" - -systemctl --no-pager --full status \ - ucloud-sandbox-registry.service \ - ucloud-sandbox-gateway.service \ - ucloud-sandbox-relay.service \ - ucloud-sandbox-autoscaler.service \ - ucloud-sandboxes-nat.service -printf 'sdk_url=https://%s\n' "$public_ip" -printf 'sdk_token_file=%s\n' "$data_root/sandbox-api-token" diff --git a/scripts/ops/install_ucloud_gateway.sh b/scripts/ops/install_ucloud_gateway.sh deleted file mode 100755 index a60de729..00000000 --- a/scripts/ops/install_ucloud_gateway.sh +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env bash -# Install a gateway on a UCloud VM from a backup (or a moved deployment's state). -# Run as root after apt installs ca-certificates curl docker.io nftables openssl -# python3-venv postgresql-18. Inputs staged by the operator in $S (mode 0700): -# sandboxes--py3-none-any.whl deployment.json state.tar -# postgres.dsn ucloud.pgdump s3.env ucloud-session.json -# release/ (the node bundles node_package_root names) -# A gateway backup (scripts/ops/backup_gateway_state.py) holds all but the wheel and -# release: postgres.dump, state/, etc/. Registry data must already be at -# registry_store.data_root (it lives on /work/data). If the gateway's private -# address changed, run scripts/ops/rehome_registry_host.py before starting services. -# Ends before gateway-reconcile, which starts the services. Never prints secrets. -set -euo pipefail -S=${STAGE:-/home/ucloud/stage} -wheel="$(ls "$S"/sandboxes-*-py3-none-any.whl)" -[[ $EUID -eq 0 ]] || { echo "run as root" >&2; exit 2; } -for f in deployment.json state.tar postgres.dsn \ - ucloud.pgdump s3.env ucloud-session.json release/sandbox-node-package.tar.gz \ - release/builder-node-package.tar.gz; do - [[ -s "$S/$f" ]] || { echo "missing $S/$f" >&2; exit 2; } -done -mountpoint -q /work/data || { echo "/work/data is not mounted" >&2; exit 1; } - -# OS packages are updated only through explicit maintenance. -cat > /etc/apt/apt.conf.d/99zz-ucloud-no-unattended-upgrades <<'EOF' -APT::Periodic::Enable "0"; -APT::Periodic::Update-Package-Lists "0"; -APT::Periodic::Unattended-Upgrade "0"; -EOF -systemctl disable --now apt-daily.timer apt-daily-upgrade.timer || true -systemctl mask apt-daily.timer apt-daily-upgrade.timer apt-daily.service apt-daily-upgrade.service unattended-upgrades.service -systemctl enable --now docker.service - -# PostgreSQL 18: same tuning as Hetzner, role and database from the DSN, then the dump. -cat > /etc/postgresql/18/main/conf.d/ucloud.conf <<'EOF' -max_connections = 200 -shared_buffers = 1GB -effective_cache_size = 4GB -wal_compression = on -checkpoint_timeout = 15min -max_wal_size = 4GB -EOF -systemctl restart postgresql -# The DSN is the local socket with peer auth (host=/var/run/postgresql dbname=ucloud user=ucloud). -grep -qx 'host=/var/run/postgresql dbname=ucloud user=ucloud' "$S/postgres.dsn" || { echo "unexpected DSN shape" >&2; exit 1; } -db=ucloud -if runuser -u postgres -- psql -qAt -c "select 1 from pg_database where datname = 'ucloud'" | grep -q 1; then - echo "database ucloud already exists; refusing to restore over it" >&2; exit 1 -fi -runuser -u postgres -- psql -v ON_ERROR_STOP=1 -q -c 'CREATE ROLE ucloud LOGIN' -c 'CREATE DATABASE ucloud OWNER ucloud' -install -m 0644 "$S/ucloud.pgdump" /tmp/ucloud.pgdump -runuser -u postgres -- pg_restore --exit-on-error -d "$db" /tmp/ucloud.pgdump -rm -f /tmp/ucloud.pgdump - -# Gateway state restored from Hetzner; services run as the VM's ucloud user. -data_root=/var/lib/ucloud-sandboxes/state -[[ ! -e "$data_root" ]] || { echo "$data_root already exists" >&2; exit 1; } -install -d -m 0750 -o ucloud -g ucloud /var/lib/ucloud-sandboxes -tar -C /var/lib/ucloud-sandboxes --no-same-owner -xf "$S/state.tar" -install -m 0600 "$S/ucloud-session.json" "$data_root/ucloud-session.json" -chown -R ucloud:ucloud /var/lib/ucloud-sandboxes - -install -d -m 0755 /etc/ucloud-sandboxes -install -m 0644 "$S/deployment.json" /etc/ucloud-sandboxes/deployment.json -install -m 0600 -o ucloud -g ucloud "$S/postgres.dsn" /etc/ucloud-sandboxes/postgres.dsn -install -m 0600 "$S/s3.env" /etc/ucloud-sandboxes/s3.env - -install_root=/work/ucloud-sandboxes -release_dir="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["node_package_root"])' "$S/deployment.json")" -venv_dir="$install_root/gateway-venv" -install -d -m 0755 "$install_root" "$release_dir" -cp -a "$S/release/." "$release_dir/" -chown -R root:root "$release_dir" -chmod -R u+rwX,go+rX,go-w "$release_dir" - -registry_root="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["registry_store"]["data_root"])' "$S/deployment.json")" -install -d -m 0755 "$registry_root" - -python3 -m venv "$venv_dir" -# bin/python -m pip, as upgrades install: scripts keep the same shebang across releases. -"$venv_dir/bin/python" -m pip install -q --disable-pip-version-check --force-reinstall "${wheel}[postgres]" - -systemd_source="$("$venv_dir/bin/python" -c 'from importlib import resources; print(resources.files("sandboxes").joinpath("systemd"))')" -for unit in \ - ucloud-sandbox-autoscaler.service ucloud-sandbox-gateway.service ucloud-sandbox-placement.service \ - ucloud-sandbox-registry-gc.service ucloud-sandbox-registry-gc.timer \ - ucloud-sandbox-registry-pressure.service ucloud-sandbox-registry-pressure.timer \ - ucloud-sandbox-snapshot-gc.service ucloud-sandbox-snapshot-gc.timer \ - ucloud-sandbox-chunk-index.service \ - ucloud-sandbox-registry-prune.service ucloud-sandbox-registry-prune.timer \ - ucloud-sandbox-registry.service ucloud-sandbox-relay.service \ - ucloud-sandbox-upstream-mirror@.service \ - ucloud-sandbox-upstream-mirror-trim.service ucloud-sandbox-upstream-mirror-trim.timer; do - install -m 0644 "$systemd_source/$unit" "/etc/systemd/system/$unit" -done -# The autoscaler publishes environments to the chunk store (Hetzner S3). -install -d -m 0755 /etc/systemd/system/ucloud-sandbox-autoscaler.service.d -cat > /etc/systemd/system/ucloud-sandbox-autoscaler.service.d/s3.conf <<'EOF' -[Service] -EnvironmentFile=/etc/ucloud-sandboxes/s3.env -EOF -# The registry lives on the project drive. -for unit in ucloud-sandbox-registry.service ucloud-sandbox-registry-gc.service \ - ucloud-sandbox-registry-pressure.service ucloud-sandbox-registry-prune.service \ - ucloud-sandbox-gateway.service ucloud-sandbox-autoscaler.service; do - install -d -m 0755 "/etc/systemd/system/$unit.d" - cat > "/etc/systemd/system/$unit.d/project-drive.conf" <<'EOF' -[Unit] -RequiresMountsFor=/work/data -EOF -done -systemctl daemon-reload -echo "installed; registry data must be in $registry_root before gateway-reconcile" diff --git a/scripts/ops/install_ucloud_observability_stack.sh b/scripts/ops/install_ucloud_observability_stack.sh deleted file mode 100755 index 5a38b310..00000000 --- a/scripts/ops/install_ucloud_observability_stack.sh +++ /dev/null @@ -1,411 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -usage() { - cat >&2 <<'EOF' -usage: install_ucloud_observability_stack.sh \ - --private-bind-ip \ - [--endpoint-host ] \ - [--data-root ] \ - [--public-url https:///grafana/] \ - [--gateway-url http://:] \ - [--gateway-token-file ] - -Installs a bounded single-gateway observability stack for UCloud. OTLP/HTTP is -exposed only on the supplied private IP, or with 0.0.0.0 on every interface of -a gateway whose only non-loopback network is the private one (UCloud VMs: the -private address changes when the VM restarts; workers then reach the collector -at --endpoint-host, the gateway's DNS name). Grafana, Tempo, and -VictoriaMetrics query ports remain loopback-only. With --public-url, Grafana -serves under that sub-path for a TLS proxy in front of it (anonymous access is -always off). VictoriaMetrics scrapes the gateway's fleet metrics -(/v1/metrics/prometheus at --gateway-url, default http://:8090) -with the gateway token, which Grafana's gateway data source also reads; both -read it from a root-owned copy, never from a dashboard. -EOF -} - -private_bind_ip="" -endpoint_host="" -data_root=/var/lib/ucloud-sandboxes/telemetry -public_url="" -gateway_url="" -gateway_token_file=/var/lib/ucloud-sandboxes/state/gateway-token -while (($#)); do - case "$1" in - --private-bind-ip) private_bind_ip="${2:-}"; shift 2 ;; - --endpoint-host) endpoint_host="${2:-}"; shift 2 ;; - --data-root) data_root="${2:-}"; shift 2 ;; - --public-url) public_url="${2:-}"; shift 2 ;; - --gateway-url) gateway_url="${2:-}"; shift 2 ;; - --gateway-token-file) gateway_token_file="${2:-}"; shift 2 ;; - -h|--help) usage; exit 0 ;; - *) usage; exit 2 ;; - esac -done - -if [[ "$EUID" -ne 0 ]]; then - echo "UCloud observability installation must run as root" >&2 - exit 2 -fi -if [[ ! "$private_bind_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then - echo "--private-bind-ip must be an IPv4 address" >&2 - exit 2 -fi -if [[ "$private_bind_ip" != 0.0.0.0 ]] && ! ip -4 address show | grep -Fq " $private_bind_ip/"; then - echo "--private-bind-ip is not assigned to this gateway" >&2 - exit 2 -fi -endpoint_host="${endpoint_host:-$private_bind_ip}" -if [[ "$endpoint_host" == 0.0.0.0 || ! "$endpoint_host" =~ ^[A-Za-z0-9.-]+$ ]]; then - echo "--endpoint-host must name this gateway when binding 0.0.0.0" >&2 - exit 2 -fi -if [[ "$data_root" != /* ]]; then - echo "--data-root must be absolute" >&2 - exit 2 -fi -case "$data_root/" in - /work/*|/mnt/ucloud/*) - echo "--data-root must use gateway-local storage, not shared UCloud storage" >&2 - exit 2 - ;; -esac - -gateway_url="${gateway_url:-http://$endpoint_host:8090}" -if [[ ! "$gateway_url" =~ ^http://[A-Za-z0-9.-]+:[0-9]+$ ]]; then - echo "--gateway-url must be http://:" >&2 - exit 2 -fi -if [[ -n "$public_url" && ! "$public_url" =~ ^https://[A-Za-z0-9.-]+/[A-Za-z0-9._-]+/$ ]]; then - echo "--public-url must be https:////" >&2 - exit 2 -fi -if [[ ! -s "$gateway_token_file" ]]; then - echo "--gateway-token-file must name the gateway token" >&2 - exit 2 -fi -grafana_domain=127.0.0.1 -grafana_public_env="" -grafana_health=http://127.0.0.1:3000/api/health -if [[ -n "$public_url" ]]; then - grafana_domain="${public_url#https://}" - grafana_domain="${grafana_domain%%/*}" - grafana_public_env="-e GF_SERVER_ROOT_URL=$public_url -e GF_SERVER_SERVE_FROM_SUB_PATH=true -e GF_SECURITY_COOKIE_SECURE=true -e GF_SECURITY_COOKIE_SAMESITE=strict" - grafana_health="http://127.0.0.1:3000/${public_url#https://*/}api/health" -fi - -config_root=/etc/ucloud-sandboxes/telemetry -grafana_provisioning="$config_root/grafana/provisioning" -grafana_env="$config_root/grafana.env" -installer_dir="$(cd "$(dirname "$0")" && pwd)" -report_source="$installer_dir/ucloud_observability_report.py" - -install -d -m 0755 \ - "$config_root" \ - "$grafana_provisioning/datasources" \ - "$grafana_provisioning/dashboards" \ - "$config_root/grafana/dashboards" \ - "$data_root/tempo" \ - "$data_root/victoria-metrics" \ - "$data_root/grafana" -chmod 0700 "$data_root/tempo" "$data_root/victoria-metrics" -chown -R 472:0 "$data_root/grafana" -chmod 0750 "$data_root/grafana" -# The scraper runs as root and Grafana as uid 472; each gets its own copy. -install -m 0400 -o root -g root "$gateway_token_file" "$config_root/gateway-token" -install -m 0400 "$gateway_token_file" "$config_root/grafana/gateway-token" -chown 472:0 "$config_root/grafana/gateway-token" -cat >"$config_root/scrape.yaml" <"$config_root/tempo.yaml" <<'EOF' -stream_over_http_enabled: true -server: - http_listen_port: 3200 - grpc_listen_port: 9095 -distributor: - receivers: - otlp: - protocols: - grpc: - endpoint: 0.0.0.0:4317 - http: - endpoint: 0.0.0.0:4318 -ingester: - max_block_duration: 5m - complete_block_timeout: 10m - flush_all_on_shutdown: true -compactor: - compaction: - block_retention: 72h -storage: - trace: - backend: local - wal: - path: /var/tempo/wal - local: - path: /var/tempo/blocks -usage_report: - reporting_enabled: false -EOF - -cat >"$config_root/collector.yaml" <<'EOF' -extensions: - health_check: - endpoint: 0.0.0.0:13133 -receivers: - otlp: - protocols: - http: - endpoint: 0.0.0.0:4318 -processors: - memory_limiter: - check_interval: 1s - limit_mib: 192 - spike_limit_mib: 48 - batch: - send_batch_size: 512 - timeout: 2s -exporters: - otlp_grpc/tempo: - endpoint: ucloud-telemetry-tempo:4317 - tls: - insecure: true - sending_queue: - enabled: true - queue_size: 2048 - retry_on_failure: - enabled: true - max_elapsed_time: 60s - prometheusremotewrite/victoria: - endpoint: http://ucloud-telemetry-victoria:8428/api/v1/write - resource_to_telemetry_conversion: - enabled: true - remote_write_queue: - enabled: true - queue_size: 2048 - max_batch_request_parallelism: 1 -service: - extensions: [health_check] - pipelines: - traces: - receivers: [otlp] - processors: [memory_limiter, batch] - exporters: [otlp_grpc/tempo] - metrics: - receivers: [otlp] - processors: [memory_limiter, batch] - exporters: [prometheusremotewrite/victoria] - telemetry: - metrics: - level: normal -EOF - -cat >"$grafana_provisioning/datasources/ucloud.yaml" <"$grafana_provisioning/dashboards/ucloud.yaml" <<'EOF' -apiVersion: 1 -providers: - - name: UCloud - orgId: 1 - folder: UCloud - type: file - disableDeletion: false - updateIntervalSeconds: 30 - allowUiUpdates: false - options: - path: /var/lib/grafana/dashboards -EOF - -# Dashboards are files beside this installer (scripts/ops/grafana/dashboards). -for dashboard in "$installer_dir"/grafana/dashboards/*.json; do - install -m 0644 "$dashboard" "$config_root/grafana/dashboards/" -done -# Retired dashboards: a removed file deletes its dashboard, and fleet.json shares -# the new dashboard's uid. -rm -f -- "$config_root/grafana/dashboards/fleet.json" "$config_root/grafana/dashboards/platform-hot-paths.json" - -if [[ ! -s "$grafana_env" ]]; then - umask 077 - { - printf 'GF_SECURITY_ADMIN_USER=admin\n' - printf 'GF_SECURITY_ADMIN_PASSWORD=%s\n' "$(openssl rand -hex 24)" - printf 'GF_SECURITY_SECRET_KEY=%s\n' "$(openssl rand -hex 32)" - } >"$grafana_env" -fi -chmod 0600 "$grafana_env" -if [[ -f "$report_source" ]]; then - install -m 0755 "$report_source" /usr/local/bin/ucloud-observability-report -else - echo "warning: ucloud_observability_report.py was not beside the installer" >&2 -fi - -install -d -m 0755 /etc/systemd/system -cat >/etc/systemd/system/ucloud-telemetry-tempo.service </etc/systemd/system/ucloud-telemetry-victoria.service </etc/systemd/system/ucloud-telemetry-collector.service </etc/systemd/system/ucloud-telemetry-grafana.service </dev/null; then break; fi - if [[ "$attempt" == 90 ]]; then - systemctl --no-pager --full status \ - ucloud-telemetry-tempo.service \ - ucloud-telemetry-victoria.service \ - ucloud-telemetry-collector.service \ - ucloud-telemetry-grafana.service - exit 1 - fi - sleep 1 - done -done - -printf 'otlp_endpoint=http://%s:4318\n' "$endpoint_host" -printf 'grafana_url=%s\n' "${public_url:-http://127.0.0.1:3000/ (ssh -L 3000:127.0.0.1:3000)}" -printf 'grafana_admin_credentials=%s\n' "$grafana_env" -printf 'tempo_retention=72h\nmetrics_retention=14d\n' diff --git a/scripts/ops/install_ucloud_ops.sh b/scripts/ops/install_ucloud_ops.sh deleted file mode 100644 index 54cdac6a..00000000 --- a/scripts/ops/install_ucloud_ops.sh +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env bash -# Install the control plane's backups and health watch on a UCloud gateway. -# -# install_ucloud_ops.sh --backups [--public-gateway URL] [--public-relay URL] -# -# Backups (scripts/ops/backup_gateway_state.py): the gateway hourly, keeping 48; -# the store node's chunk index every 6 hours, keeping 8. The watch -# (scripts/ops/ops_watch.py) runs every minute; put ALERT_WEBHOOK_URL= in /etc/ucloud-sandboxes/alerts.env to receive alerts. -set -euo pipefail -backups="" -public_gateway="" -public_relay="" -while (($#)); do - case "$1" in - --backups) backups="${2:-}"; shift 2 ;; - --public-gateway) public_gateway="${2:-}"; shift 2 ;; - --public-relay) public_relay="${2:-}"; shift 2 ;; - *) echo "usage: $0 --backups [--public-gateway URL] [--public-relay URL]" >&2; exit 2 ;; - esac -done -[[ "$EUID" -eq 0 ]] || { echo "run as root" >&2; exit 2; } -case "$backups" in - /work/*) ;; - *) echo "--backups must be on durable UCloud storage (/work/...), not the gateway's own disk" >&2; exit 2 ;; -esac -source_dir="$(cd "$(dirname "$0")" && pwd)" -libexec=/usr/local/libexec/ucloud-sandboxes -python=/work/ucloud-sandboxes/gateway-venv/bin/python -install -d -m 0755 "$libexec" -install -m 0755 "$source_dir/backup_gateway_state.py" "$source_dir/ops_watch.py" "$libexec/" -install -d -m 0700 -o root -g root "$backups" "$backups/gateway" "$backups/chunk-index" -[[ -e /etc/ucloud-sandboxes/alerts.env ]] || install -m 0600 /dev/null /etc/ucloud-sandboxes/alerts.env - -unit() { # name, description, ExecStart, timer spec - cat >"/etc/systemd/system/$1.service" <"/etc/systemd/system/$1.timer" < argparse.ArgumentParser: - result = argparse.ArgumentParser(description=__doc__) - result.add_argument("--execute", action="store_true") - result.add_argument("--name", default=DEFAULT_NAME) - result.add_argument("--network-cidr", default=DEFAULT_NETWORK_CIDR) - result.add_argument("--subnet-cidr", default=DEFAULT_SUBNET_CIDR) - result.add_argument("--network-zone", default=DEFAULT_NETWORK_ZONE) - result.add_argument("--public-key-file", type=Path, default=DEFAULT_PUBLIC_KEY_FILE) - result.add_argument("--state-file", type=Path, default=DEFAULT_STATE_FILE) - result.add_argument("--api-token-env", default="HETZNER_API_KEY") - result.add_argument( - "--gateway-ssh-source-cidr", - action="append", - default=[], - help=( - "CIDR allowed to SSH to the gateway; repeat for multiple operator " - "networks. With none, the gateway firewall exposes only HTTP(S)." - ), - ) - result.add_argument( - "--egress-gateway-ip", - help=( - "Private IP of the NAT gateway; adds or verifies the Network " - "default route used by enable_private_egress workers" - ), - ) - return result - - -def main(argv: list[str] | None = None) -> int: - args = parser().parse_args(argv) - if not _NAME_RE.fullmatch(args.name): - raise ValueError("foundation name must be a valid Hetzner resource name") - public_key = _read_public_key(args.public_key_file) - gateway_ssh_sources = _ip_networks(args.gateway_ssh_source_cidr) - gateway_firewall_rules = _gateway_firewall_rules(gateway_ssh_sources) - labels = { - "ucloud-sandboxes/foundation": "production", - "ucloud-sandboxes/managed": "true", - } - client = HetznerClient(api_token_env=args.api_token_env) - - network = _existing(client, "/networks", "networks", args.name) - ssh_key = _existing(client, "/ssh_keys", "ssh_keys", f"{args.name}-init") - firewall = _existing(client, "/firewalls", "firewalls", f"{args.name}-workers") - gateway_firewall = _existing( - client, "/firewalls", "firewalls", f"{args.name}-gateway" - ) - if network is not None: - _verify_network( - network, - network_cidr=args.network_cidr, - subnet_cidr=args.subnet_cidr, - network_zone=args.network_zone, - ) - egress_gateway_ip = _egress_gateway_ip( - args.egress_gateway_ip, - subnet_cidr=args.subnet_cidr, - ) - if egress_gateway_ip is None: - egress_route = "not_requested" - elif network is None: - egress_route = "create" - else: - egress_route = _egress_route_state(network, egress_gateway_ip) - if ( - ssh_key is not None - and str(ssh_key.get("public_key") or "").strip() != public_key - ): - raise ValueError("existing Hetzner SSH key has different key material") - if firewall is not None and firewall.get("rules") != []: - raise ValueError("existing worker firewall is not deny-inbound/allow-outbound") - gateway_firewall_needs_update = ( - gateway_firewall is not None - and gateway_firewall.get("rules") != gateway_firewall_rules - ) - - plan = { - "execute": bool(args.execute), - "resources": { - "network": "existing" if network else "create", - "ssh_key": "existing" if ssh_key else "create", - "firewall": "existing" if firewall else "create", - "gateway_firewall": ( - "create" - if gateway_firewall is None - else "update" - if gateway_firewall_needs_update - else "existing" - ), - "egress_route": egress_route, - }, - } - if not args.execute: - print(json.dumps(plan, indent=2, sort_keys=True)) - return 0 - - if network is None: - response = client.request_json( - "POST", - "/networks", - json_body={ - "name": args.name, - "ip_range": args.network_cidr, - "subnets": [ - { - "type": "cloud", - "ip_range": args.subnet_cidr, - "network_zone": args.network_zone, - } - ], - "labels": labels, - "expose_routes_to_vswitch": False, - }, - ) - network = _response_object(response, "network") - _verify_network( - network, - network_cidr=args.network_cidr, - subnet_cidr=args.subnet_cidr, - network_zone=args.network_zone, - ) - if egress_gateway_ip is not None: - egress_route = _egress_route_state(network, egress_gateway_ip) - if egress_route == "create": - client.request_json( - "POST", - f"/networks/{_positive_id(network, 'network')}/actions/add_route", - json_body={ - "destination": "0.0.0.0/0", - "gateway": egress_gateway_ip, - }, - ) - network = _existing(client, "/networks", "networks", args.name) - if ( - network is None - or _egress_route_state(network, egress_gateway_ip) != "existing" - ): - raise ValueError("Hetzner Network did not retain the egress route") - if ssh_key is None: - response = client.request_json( - "POST", - "/ssh_keys", - json_body={ - "name": f"{args.name}-init", - "public_key": public_key, - "labels": labels, - }, - ) - ssh_key = _response_object(response, "ssh_key") - if firewall is None: - response = client.request_json( - "POST", - "/firewalls", - json_body={ - "name": f"{args.name}-workers", - "rules": [], - "labels": labels, - }, - ) - firewall = _response_object(response, "firewall") - if gateway_firewall is None: - response = client.request_json( - "POST", - "/firewalls", - json_body={ - "name": f"{args.name}-gateway", - "rules": gateway_firewall_rules, - "labels": labels, - }, - ) - gateway_firewall = _response_object(response, "firewall") - elif gateway_firewall_needs_update: - gateway_firewall_id = _positive_id(gateway_firewall, "gateway firewall") - client.request_json( - "POST", - f"/firewalls/{gateway_firewall_id}/actions/set_rules", - json_body={"rules": gateway_firewall_rules}, - ) - gateway_firewall = _existing( - client, - "/firewalls", - "firewalls", - f"{args.name}-gateway", - ) - if ( - gateway_firewall is None - or gateway_firewall.get("rules") != gateway_firewall_rules - ): - raise ValueError("Hetzner gateway firewall did not retain ingress rules") - - state = { - "schema": 1, - "name": args.name, - "network_cidr": args.network_cidr, - "subnet_cidr": args.subnet_cidr, - "network_zone": args.network_zone, - "network_id": _positive_id(network, "network"), - "ssh_key_ids": [_positive_id(ssh_key, "ssh_key")], - "firewall_ids": [_positive_id(firewall, "firewall")], - "gateway_firewall_ids": [_positive_id(gateway_firewall, "gateway firewall")], - "gateway_ssh_source_cidrs": gateway_ssh_sources, - "private_key_file": str(args.public_key_file.with_suffix("")), - } - if egress_gateway_ip is not None: - state["egress_gateway_ip"] = egress_gateway_ip - _write_state(args.state_file, state) - print(json.dumps({**plan, "state": state}, indent=2, sort_keys=True)) - return 0 - - -def _existing( - client: HetznerClient, - path: str, - response_key: str, - name: str, -) -> dict[str, Any] | None: - payload = client.request_json( - "GET", path, params={"name": name, "page": 1, "per_page": 50} - ) - if not isinstance(payload, dict) or not isinstance(payload.get(response_key), list): - raise ValueError(f"invalid Hetzner {response_key} list response") - matches = [item for item in payload[response_key] if isinstance(item, dict)] - if len(matches) > 1: - raise ValueError(f"multiple Hetzner resources have name {name!r}") - return matches[0] if matches else None - - -def _verify_network( - network: dict[str, Any], - *, - network_cidr: str, - subnet_cidr: str, - network_zone: str, -) -> None: - if network.get("ip_range") != network_cidr: - raise ValueError("existing Hetzner network has a different IP range") - subnets = network.get("subnets") - if not isinstance(subnets, list) or not any( - isinstance(item, dict) - and item.get("type") == "cloud" - and item.get("ip_range") == subnet_cidr - and item.get("network_zone") == network_zone - for item in subnets - ): - raise ValueError("existing Hetzner network has a different cloud subnet") - - -def _egress_gateway_ip(value: object, *, subnet_cidr: str) -> str | None: - if value in (None, ""): - return None - if not isinstance(value, str): - raise ValueError("egress gateway IP must be an IPv4 address") - try: - address = ipaddress.ip_address(value.strip()) - subnet = ipaddress.ip_network(subnet_cidr) - except ValueError as exc: - raise ValueError("egress gateway IP or subnet is invalid") from exc - if address.version != 4 or subnet.version != 4 or address not in subnet.hosts(): - raise ValueError("egress gateway IP must be a host address in the cloud subnet") - return str(address) - - -def _egress_route_state( - network: dict[str, Any], - gateway_ip: str, -) -> str: - routes = network.get("routes") - if not isinstance(routes, list): - raise ValueError("existing Hetzner network has invalid routes") - defaults = [ - item - for item in routes - if isinstance(item, dict) and item.get("destination") == "0.0.0.0/0" - ] - if not defaults: - return "create" - if len(defaults) != 1 or defaults[0].get("gateway") != gateway_ip: - raise ValueError("existing Hetzner network has a different default route") - return "existing" - - -def _response_object(payload: object, key: str) -> dict[str, Any]: - if not isinstance(payload, dict) or not isinstance(payload.get(key), dict): - raise ValueError(f"invalid Hetzner create response for {key}") - return payload[key] - - -def _positive_id(payload: dict[str, Any], label: str) -> int: - value = payload.get("id") - if isinstance(value, bool) or not isinstance(value, int) or value <= 0: - raise ValueError(f"Hetzner {label} response has no positive id") - return value - - -def _read_public_key(path: Path) -> str: - try: - value = path.read_text(encoding="utf-8").strip() - except OSError as exc: - raise ValueError(f"cannot read bootstrap public key: {path}") from exc - if "\n" in value or "\r" in value or not value.startswith("ssh-ed25519 "): - raise ValueError("bootstrap public key must be one Ed25519 OpenSSH key") - return value - - -def _ip_networks(values: list[str]) -> list[str]: - result: list[str] = [] - for value in values: - try: - network = ipaddress.ip_network(value, strict=False) - except ValueError as exc: - raise ValueError(f"invalid gateway SSH source CIDR: {value}") from exc - normalized = str(network) - if normalized not in result: - result.append(normalized) - return result - - -def _gateway_firewall_rules(ssh_sources: list[str]) -> list[dict[str, Any]]: - rules: list[dict[str, Any]] = [] - if ssh_sources: - rules.append( - { - "direction": "in", - "protocol": "tcp", - "port": "22", - "source_ips": ssh_sources, - "destination_ips": [], - "description": "Operator SSH", - } - ) - for port, description in ( - ("80", "ACME and HTTPS redirect"), - ("443", "Sandbox SDK HTTPS"), - ): - rules.append( - { - "direction": "in", - "protocol": "tcp", - "port": port, - "source_ips": ["0.0.0.0/0", "::/0"], - "destination_ips": [], - "description": description, - } - ) - return rules - - -def _write_state(path: Path, payload: dict[str, Any]) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp") - encoded = (json.dumps(payload, indent=2, sort_keys=True) + "\n").encode("utf-8") - descriptor = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) - try: - os.write(descriptor, encoded) - os.fsync(descriptor) - finally: - os.close(descriptor) - os.replace(temporary, path) - os.chmod(path, 0o600) - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tests/test_declarative_infra.py b/tests/test_declarative_infra.py new file mode 100644 index 00000000..7856c7bb --- /dev/null +++ b/tests/test_declarative_infra.py @@ -0,0 +1,86 @@ +"""Invariants for the declarative permanent infrastructure under infra/.""" + +from pathlib import Path +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +HETZNER_TF = ROOT / "infra" / "hetzner" / "main.tf" +ANSIBLE_ROOT = ROOT / "infra" / "ansible" + + +class DeclarativeInfraInvariantTests(unittest.TestCase): + def test_hetzner_tofu_protects_stateful_resources_and_firewalls(self) -> None: + tf = HETZNER_TF.read_text(encoding="utf-8") + # Primary IPs and the persistent chunk-store volume must never be destroyed accidentally. + self.assertGreaterEqual(tf.count("prevent_destroy = true"), 3) + self.assertGreaterEqual(tf.count("auto_delete = false"), 2) + # Gateway firewall exposes HTTP/HTTPS and gates SSH behind an explicit CIDR variable. + self.assertIn('port = "80"', tf) + self.assertIn('port = "443"', tf) + self.assertIn('port = "22"', tf) + self.assertIn("var.gateway_ssh_source_cidrs", tf) + # Worker firewall stays deny-inbound (no rules block). + self.assertIn('resource "hcloud_firewall" "workers"', tf) + + def test_observability_role_is_pinned_bounded_private_and_local(self) -> None: + role = ANSIBLE_ROOT / "roles" / "observability" + combined = "\n".join( + path.read_text(encoding="utf-8") + for path in sorted(role.rglob("*")) + if path.is_file() + ) + for required in ( + "grafana/tempo:2.10.7", + "victoriametrics/victoria-metrics:v1.148.0", + "otel/opentelemetry-collector-contrib:0.153.0", + "grafana/grafana:13.2.4", + "yesoreyeram-infinity-datasource@4.1.1", + "GF_PLUGINS_PREINSTALL_AUTO_UPDATE=false", + "-promscrape.config=/etc/victoria/scrape.yaml", + "metrics_path: /v1/metrics/prometheus", + "-p 127.0.0.1:3200:3200", + "-p 127.0.0.1:8428:8428", + "-p 127.0.0.1:{{ gateway_grafana_port }}:3000", + "block_retention: {{ observability_tempo_retention }}", + "--cpu-shares 256", + "GF_AUTH_ANONYMOUS_ENABLED=false", + "/usr/local/bin/ucloud-observability-report", + ): + self.assertIn(required, combined) + self.assertNotIn("-p 0.0.0.0:", combined) + self.assertNotIn("GF_AUTH_ANONYMOUS_ENABLED=true", combined) + # A store crash loop must not restart Grafana and the collector with it. + self.assertNotIn("Requires=ucloud-telemetry-", combined) + self.assertIn("/work/|/mnt/ucloud/", combined) + + def test_nginx_ingress_template_enforces_tls_and_grafana_ops_auth(self) -> None: + site = ( + ANSIBLE_ROOT / "roles" / "gateway_ingress" / "templates" / "nginx-site.conf.j2" + ).read_text(encoding="utf-8") + for required in ( + "ssl_protocols TLSv1.2 TLSv1.3;", + "server_tokens off;", + "proxy_request_buffering off;", + "proxy_buffering off;", + "auth_request /_ucloud_grafana_session;", + "if ($http_x_ucloud_ops != 1)", + "include /etc/nginx/ucloud-sandboxes-ops-token.conf;", + "proxy_set_header Proxy-Authorization \"\";", + ): + self.assertIn(required, site) + + def test_gateway_and_store_roles_wire_gatewayd_and_token_verification(self) -> None: + gw_tasks = (ANSIBLE_ROOT / "roles" / "gateway" / "tasks" / "main.yml").read_text(encoding="utf-8") + gw_handlers = (ANSIBLE_ROOT / "roles" / "gateway" / "handlers" / "main.yml").read_text(encoding="utf-8") + store_tasks = (ANSIBLE_ROOT / "roles" / "store" / "tasks" / "main.yml").read_text(encoding="utf-8") + self.assertIn("ucloud-sandbox-gatewayd.service", gw_tasks) + self.assertIn("gateway-reconcile", gw_handlers) + self.assertIn("ucloud-sandbox-registry-pressure.service", gw_tasks) + self.assertIn("ucloud-sandbox-upstream-mirror@.service", gw_tasks) + self.assertIn("ucloud-sandbox-upstream-mirror-trim.service", gw_tasks) + self.assertIn("store_item.stat.checksum == gw_item.stat.checksum", store_tasks) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_deploy.py b/tests/test_deploy.py index 7649be2c..56186c51 100644 --- a/tests/test_deploy.py +++ b/tests/test_deploy.py @@ -244,12 +244,18 @@ def test_gateway_service_convergence_is_shared_with_hetzner(self) -> None: ) self.assertNotIn("SNAPSHOT_STORE_KIND=", script) - hetzner_installer = ( - Path(__file__).parents[1] / "scripts" / "ops" / "install_hetzner_gateway.sh" + gateway_handlers = ( + Path(__file__).parents[1] + / "infra" + / "ansible" + / "roles" + / "gateway" + / "handlers" + / "main.yml" ).read_text(encoding="utf-8") self.assertIn( - "gateway-reconcile --config", - hetzner_installer, + "gateway-reconcile", + gateway_handlers, ) def test_stage_file_atomically_replaces_root_owned_release_artifact(self) -> None: diff --git a/tests/test_hetzner_foundation.py b/tests/test_hetzner_foundation.py deleted file mode 100644 index 1fa9924d..00000000 --- a/tests/test_hetzner_foundation.py +++ /dev/null @@ -1,28 +0,0 @@ -import unittest -from pathlib import Path -import subprocess - -from scripts.ops import setup_hetzner_foundation as foundation - - -class HetznerFoundationTests(unittest.TestCase): - def test_gateway_firewall_defaults_and_operator_access(self) -> None: - defaults = foundation._gateway_firewall_rules([]) - self.assertEqual([rule["port"] for rule in defaults], ["80", "443"]) - - sources = foundation._ip_networks( - ["198.51.100.24/32", "2001:db8::17/64", "198.51.100.24/32"] - ) - self.assertEqual(sources, ["198.51.100.24/32", "2001:db8::/64"]) - rules = foundation._gateway_firewall_rules(sources) - self.assertEqual((rules[0]["port"], rules[0]["source_ips"]), ("22", sources)) - with self.assertRaisesRegex(ValueError, "gateway SSH source CIDR"): - foundation._ip_networks(["not-a-network"]) - - def test_gateway_installer_has_valid_bash_syntax(self) -> None: - installer = Path(__file__).parents[1] / "scripts" / "ops" / "install_hetzner_gateway.sh" - subprocess.run(["bash", "-n", str(installer)], check=True) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_nginx_ingress.py b/tests/test_nginx_ingress.py deleted file mode 100644 index a7d0ae2c..00000000 --- a/tests/test_nginx_ingress.py +++ /dev/null @@ -1,125 +0,0 @@ -from pathlib import Path -import subprocess -import sys -from tempfile import TemporaryDirectory -import unittest - -TEST_TIER = "contract" - - -SCRIPT = Path(__file__).resolve().parents[1] / "scripts/ops/configure_hetzner_sdk_ingress.sh" - - -def capacity_renderer(): - return SCRIPT.read_text().split("<<'PY_NGINX_CAPACITY'\n", 1)[1].split( - "\nPY_NGINX_CAPACITY", 1 - )[0] - - -class NginxCapacityTests(unittest.TestCase): - def install(self, root, *, valid): - body = SCRIPT.read_text().split("install_nginx_site() {\n", 1)[1].split( - '\n}\n\ncat >"$temporary_site"', 1 - )[0] - code = '''set -euo pipefail -nginx_main="$1/main.conf" -nginx_site="$1/site.conf" -nginx_enabled="$1/enabled.conf" -temporary_main="$1/candidate-main.conf" -temporary_site="$1/candidate-site.conf" -previous_site="$1/previous-site.conf" -nginx() { return "$2"; } -'''.replace('nginx() { return "$2"; }', f"nginx() {{ return {0 if valid else 1}; }}") - code += "install_nginx_site() {\n" + body + "\n}\ninstall_nginx_site\n" - result = subprocess.run(["bash", "-c", code, "fixture", str(root)], - capture_output=True, text=True) - self.assertEqual(result.returncode == 0, valid, result.stderr) - - def test_installer_validates_backs_up_and_is_idempotent(self): - with TemporaryDirectory() as raw: - root = Path(raw) - original = "events { worker_connections 768; }\nhttp {}\n" - (root / "main.conf").write_text(original) - (root / "site.conf").write_text("previous site") - (root / "candidate-site.conf").write_text("new site") - self.install(root, valid=True) - self.assertIn("worker_connections 4096", (root / "main.conf").read_text()) - self.assertIn("worker_rlimit_nofile 65536", (root / "main.conf").read_text()) - self.assertEqual((root / "site.conf").read_text(), "new site") - self.assertEqual(next(root.glob("main.conf.ucloud-backup.*")).read_text(), original) - self.assertEqual(next(root.glob("site.conf.ucloud-backup.*")).read_text(), "previous site") - self.install(root, valid=True) - self.assertEqual(len(list(root.glob("main.conf.ucloud-backup.*"))), 1) - self.assertEqual(len(list(root.glob("site.conf.ucloud-backup.*"))), 1) - - def test_failed_validation_restores_site_and_never_changes_main(self): - for existing_site in (False, True): - with self.subTest(existing_site=existing_site), TemporaryDirectory() as raw: - root = Path(raw) - original = "events { worker_connections 768; }\nhttp {}\n" - (root / "main.conf").write_text(original) - (root / "candidate-site.conf").write_text("invalid new site") - if existing_site: - (root / "site.conf").write_text("previous site") - self.install(root, valid=False) - self.assertEqual((root / "main.conf").read_text(), original) - self.assertEqual(list(root.glob("main.conf.ucloud-backup.*")), []) - if existing_site: - self.assertEqual((root / "site.conf").read_text(), "previous site") - else: - self.assertFalse((root / "site.conf").exists()) - self.assertFalse((root / "enabled.conf").is_symlink()) - - def render(self, source, *, succeeds=True): - with TemporaryDirectory() as raw: - original, candidate = Path(raw) / "original.conf", Path(raw) / "candidate.conf" - original.write_text(source) - result = subprocess.run( - [sys.executable, "-", str(original), str(candidate)], - input=capacity_renderer(), capture_output=True, text=True, - ) - self.assertEqual(original.read_text(), source) - self.assertEqual(result.returncode == 0, succeeds, result.stderr) - if succeeds: - return candidate.read_text() - self.assertFalse(candidate.exists()) - - def test_capacity_edit_preserves_comments_quoted_text_and_other_directives(self): - source = '''# worker_rlimit_nofile 123; -worker_processes auto; -worker_rlimit_nofile 1024; # custom comment -events { worker_connections 768; multi_accept on; } -http { - log_format fixture 'events { worker_connections 5; } # text'; - keepalive_timeout 30; - include /etc/nginx/sites-enabled/*; -} -''' - expected = source.replace("worker_rlimit_nofile 1024", "worker_rlimit_nofile 65536") - expected = expected.replace("worker_connections 768", "worker_connections 4096") - self.assertEqual(self.render(source), expected) - self.assertEqual(self.render(expected), expected) - - def test_missing_directives_are_added_and_larger_limits_are_retained(self): - source = "worker_processes auto;\nevents { }\nhttp { }\n" - candidate = self.render(source) - self.assertIn("worker_connections 4096;", candidate) - self.assertIn("worker_rlimit_nofile 65536;", candidate) - self.assertEqual(self.render(candidate), candidate) - larger = "worker_rlimit_nofile 131072;\nevents { worker_connections 8192; }\n" - self.assertEqual(self.render(larger), larger) - - def test_ambiguous_or_incomplete_config_does_not_produce_a_candidate(self): - for source in ( - "http {}", - "events { worker_connections 1; worker_connections 2; }", - "events {} events {}", - "events { worker_connections 768;", - "events {} worker_rlimit_nofile unexpected;", - ): - with self.subTest(source=source): - self.render(source, succeeds=False) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_registry_disk.py b/tests/test_registry_disk.py index 45272a73..f48badb9 100644 --- a/tests/test_registry_disk.py +++ b/tests/test_registry_disk.py @@ -450,8 +450,10 @@ def test_prune_waits_for_the_lock_hourly_and_pressure_runs_every_minute(self) -> self.assertNotIn("Requires=ucloud-sandbox-registry.service", units[name]) self.assertIn("ucloud-sandbox-registry-pressure.timer", SYSTEMD_UNIT_NAMES) self.assertIn("ucloud-sandbox-registry-pressure.service", REGISTRY_STORAGE_SYSTEMD_UNITS) - installer = (Path(__file__).parents[1] / "scripts/ops/install_hetzner_gateway.sh").read_text() - self.assertIn("ucloud-sandbox-registry-pressure.timer", installer) + gateway_role = ( + Path(__file__).parents[1] / "infra/ansible/roles/gateway/tasks/main.yml" + ).read_text() + self.assertIn("ucloud-sandbox-registry-pressure.service", gateway_role) def test_gateway_reconcile_enables_the_pressure_timer(self) -> None: commands: list[list[str]] = [] diff --git a/tests/test_rules_baseline.json b/tests/test_rules_baseline.json index 1082af08..4a9b757e 100644 --- a/tests/test_rules_baseline.json +++ b/tests/test_rules_baseline.json @@ -190,9 +190,6 @@ "sleep": 7, "test_import": 1 }, - "test_hetzner_foundation.py": { - "private": 4 - }, "test_hibernation.py": { "private": 2, "private_patch": 1 diff --git a/tests/test_ucloud_observability_stack.py b/tests/test_ucloud_observability_stack.py deleted file mode 100644 index a420cd46..00000000 --- a/tests/test_ucloud_observability_stack.py +++ /dev/null @@ -1,44 +0,0 @@ -import subprocess -import unittest -from pathlib import Path - - -SCRIPT = ( - Path(__file__).parents[1] / "scripts" / "ops" / "install_ucloud_observability_stack.sh" -) - - -class UCloudObservabilityStackTests(unittest.TestCase): - def test_stack_is_pinned_bounded_private_and_locally_persistent(self) -> None: - script = SCRIPT.read_text(encoding="utf-8") - for required in ( - "grafana/tempo:2.10.7", - "victoriametrics/victoria-metrics:v1.148.0", - "otel/opentelemetry-collector-contrib:0.153.0", - "grafana/grafana:13.2.4", - "yesoreyeram-infinity-datasource@4.1.1", - "GF_PLUGINS_PREINSTALL_AUTO_UPDATE=false", - "-promscrape.config=/etc/victoria/scrape.yaml", - "metrics_path: /v1/metrics/prometheus", - "-p $private_bind_ip:4318:4318", - "-p 127.0.0.1:3200:3200", - "-p 127.0.0.1:8428:8428", - "-p 127.0.0.1:3000:3000", - "-storage.minFreeDiskSpaceBytes=20GB", - "block_retention: 72h", - "-retentionPeriod=14d", - "--cpu-shares 256", - "GF_AUTH_ANONYMOUS_ENABLED=false", - "/usr/local/bin/ucloud-observability-report", - ): - self.assertIn(required, script) - self.assertNotIn("-p 0.0.0.0:", script) - self.assertNotIn("GF_AUTH_ANONYMOUS_ENABLED=true", script) - # A store crash loop must not restart Grafana and the collector with it (2026-11-05). - self.assertNotIn("Requires=ucloud-telemetry-", script) - self.assertIn("/work/*|/mnt/ucloud/*", script) - subprocess.run(["bash", "-n", str(SCRIPT)], check=True) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_upstream_mirror.py b/tests/test_upstream_mirror.py index c7f3ceda..15ca9767 100644 --- a/tests/test_upstream_mirror.py +++ b/tests/test_upstream_mirror.py @@ -82,9 +82,9 @@ def test_units_are_packaged_gated_on_the_volume_and_installed(self): self.assertIn("OnCalendar=hourly", units["ucloud-sandbox-upstream-mirror-trim.timer"]) self.assertIn("ucloud-sandbox-upstream-mirror-trim.timer", SYSTEMD_UNIT_NAMES) self.assertIn("ucloud-sandbox-upstream-mirror@.service", REGISTRY_STORAGE_SYSTEMD_UNITS) - installer = (ROOT / "scripts/ops/install_hetzner_gateway.sh").read_text() - self.assertIn("ucloud-sandbox-upstream-mirror@.service \\\n ucloud-sandbox-upstream-mirror-trim.service; do", installer) - self.assertIn('install -D -m 0600 -o root -g root "$staged_credentials" "$mirror_credentials_file"', installer) + gateway_role = (ROOT / "infra/ansible/roles/gateway/tasks/main.yml").read_text() + self.assertIn("ucloud-sandbox-upstream-mirror@.service", gateway_role) + self.assertIn("ucloud-sandbox-upstream-mirror-trim.service", gateway_role) def test_proxy_environment_keeps_credentials_out_of_arguments(self): config = mirrored()