diff --git a/services/docs/content/en/apex/concepts/architecture.md b/services/docs/content/en/apex/concepts/architecture.md index c822b18..33e4e04 100644 --- a/services/docs/content/en/apex/concepts/architecture.md +++ b/services/docs/content/en/apex/concepts/architecture.md @@ -53,15 +53,13 @@ Listing (`apex --help`) never imports action modules; summaries and disabled ma ## The capture-up model {#capture-up} -Node repositories are ledgers, not just sources: the host itself records what it runs. +`apex sync/repository` records the working tree and commons pin in a +`sync/` branch, rebases onto `origin/main`, and pushes with +`--force-with-lease`. It refuses to run when commons has uncommitted changes +or the `compositions/` directory is missing. A rebase conflict aborts the sync. -1. A scheduled `sync/repository` run on the host commits the working tree to a `sync/` branch (including the commons submodule pointer), rebases it onto `origin/main`, and pushes with `--force-with-lease`. -2. A scheduled CI job in the node repository merges `sync/` back into `main` under a bot identity. - -This [capture-up](/apex/glossary#capture-up) loop means drift on a host becomes a commit — visible, diffable, and revertable — instead of silent divergence. The sync aborts rather than committing when the commons submodule is dirty or the `compositions/` tree is missing, so a broken checkout never becomes the recorded state. - -> [!NOTE] -> The CI merge job checks out the repository *without* submodules: the commons submodule uses an SSH URL that the default CI token cannot fetch, and the merge only moves the gitlink pointer anyway. +Review and integration of that branch are repository policies. APEX does not +supply a CI merge workflow or require a particular repository hosting setup. ## Design constraints {#constraints} diff --git a/services/docs/content/en/apex/concepts/compositions.md b/services/docs/content/en/apex/concepts/compositions.md index 8bbabf3..bb9009c 100644 --- a/services/docs/content/en/apex/concepts/compositions.md +++ b/services/docs/content/en/apex/concepts/compositions.md @@ -44,7 +44,7 @@ Opt-in services, gated by compose profiles a node enables in `COMPOSE_PROFILE |---|---|---| | `xray` | xray | Host-network proxy edge for the enclave. | | `adguard` | adguard | DNS filtering, sharing traefik's network namespace; routed at `/adguard` on the node FQDN. | -| `alloy` | alloy | Per-node observability agent (Grafana Alloy). Collects host + container metrics and journal + container logs and **pushes** them outbound to a central Prometheus and Loki (see [Concept: Security model](/apex/concepts/security-model#observability)). Its container `hostname` is set to `APEX_NODE_HOST`, and that value stamps the `node` and `instance` labels on every metric and log stream. | +| `alloy` | alloy | Optional Grafana Alloy agent. Sends host/container metrics and journal/container logs to configured compatible endpoints. See [observability configuration](/apex/concepts/security-model#observability). | | `manual` | resticontainer | One-shot label-driven backup runner (`ghcr.io/deytenit/resticontainer`) — never starts with `up`; invoked by the `backup/run` action, which discovers per-service backup intent from `restic.*` compose labels. | ## Networks {#networks} diff --git a/services/docs/content/en/apex/concepts/node-identity.md b/services/docs/content/en/apex/concepts/node-identity.md index 358ed0c..b00063e 100644 --- a/services/docs/content/en/apex/concepts/node-identity.md +++ b/services/docs/content/en/apex/concepts/node-identity.md @@ -21,7 +21,7 @@ It declares identity explicitly through these keys: ```ini {filename="node.env"} APEX_NODE_FQDN=node1.example.com APEX_NODE_HOST=node1.example.com -APEX_SUBNET=198.18.16.0/24 +APEX_SUBNET=198.18.0.0/24 ``` ### The OS hostname diff --git a/services/docs/content/en/apex/concepts/security-model.md b/services/docs/content/en/apex/concepts/security-model.md index c6ea2cc..c288f87 100644 --- a/services/docs/content/en/apex/concepts/security-model.md +++ b/services/docs/content/en/apex/concepts/security-model.md @@ -34,7 +34,11 @@ The [core composition](/apex/glossary#core-composition) encodes container-level ## Observability {#observability} -Observability is an **outbound push**, not an exposed route. The optional `alloy` core service (Grafana Alloy, one agent per node) collects host metrics (a `node_exporter`-equivalent), container metrics (cadvisor), the systemd journal, and docker container logs, and pushes them to a **central** Prometheus and Loki that live on a designated node — the metrics via `prometheus.remote_write` to `APEX_PROM_PUSH_URL`, the logs via `loki.write` to `APEX_LOKI_PUSH_URL`. Both targets are authenticated with HTTP basic auth using `APEX_OBS_BASIC_AUTH_USER` / `APEX_OBS_BASIC_AUTH_PASS`. Because the push is outbound, Alloy attaches to the `direct` network (which has egress) rather than the `internal` `enclave`; there is no node-local log store and no `/loki` route to protect. +The optional `alloy` service sends host and container metrics to +`APEX_PROM_PUSH_URL` and logs to `APEX_LOKI_PUSH_URL`. Configure compatible +endpoints and HTTP basic-auth credentials through `APEX_OBS_BASIC_AUTH_USER` +and `APEX_OBS_BASIC_AUTH_PASS`. The service requires outbound connectivity to +those endpoints; their hosting and access policy are deployment choices. ## Secrets boundary {#secrets} diff --git a/services/docs/content/en/apex/glossary.md b/services/docs/content/en/apex/glossary.md index 9f22736..d66182a 100644 --- a/services/docs/content/en/apex/glossary.md +++ b/services/docs/content/en/apex/glossary.md @@ -16,7 +16,7 @@ Terminology used within the apex fleet operations framework. ## Capture-up {#capture-up} -**Capture-up** - The flow that records a host's live state back into its repository: a scheduled commit to the `sync/` branch, rebased onto `main` and folded back by CI. Drift becomes a diff instead of divergence. +**Capture-up** — Recording a host's working state in a `sync/` branch through `apex sync/repository`. The repository's own policy determines review and integration. ## Commons {#commons} diff --git a/services/docs/content/en/apex/guides/host-operations.md b/services/docs/content/en/apex/guides/host-operations.md index f3c4642..131046e 100644 --- a/services/docs/content/en/apex/guides/host-operations.md +++ b/services/docs/content/en/apex/guides/host-operations.md @@ -12,7 +12,8 @@ weight: 24 | Step | Effect | |---|---| -| `configure/base` | Ensures a Debian base: package index update, essential packages (`curl`, `wget`, `git`, `rsyslog`), rsyslog running, `ufw` installed, and the `ufw-docker` helper at `~/.local/bin/ufw-docker`. | +| `configure/base` | Installs missing Debian packages after checking that APT's simulation contains no upgrades or removals, ensures rsyslog is running, and verifies the pinned `/usr/local/bin/ufw-docker` before privileged execution. Avoid concurrent package operations. | +| `configure/timezone` | Applies `configs/timezone` when present and refreshes active cron after a timezone change. Supports `--dry-run`. | | `configure/ufw` | Applies host rules, injects the managed kernel-rule blocks, applies container rules via `ufw-docker`. Supports `--dry-run`. | | `configure/crowdsec` | Installs CrowdSec if absent, deploys `configs/crowdsec/` to `/etc/crowdsec/`, installs collections, and the firewall bouncer when configured. Supports `--dry-run`. | | `configure/cron` | Renders `configs/cron/crontab` through the template layer and installs it — with preview, empty-render refusal (exit `65`), and rollback on a failed install. Supports `--dry-run`. | @@ -27,10 +28,39 @@ After `configure/ufw`, restart `ufw` deliberately (`sudo systemctl restart ufw`) apex compose up # core first, then services alphabetically apex compose down # reverse order apex compose restart -apex compose up --dry-run # print the commands only +apex compose --dry-run up # print the commands only +apex compose -p apex restart traefik +apex compose -p app up -d ``` -Extra arguments pass through to `docker compose` per project. Each project's `.env` and `apex.env` are supplied automatically when present. +Put wrapper options (`-p` and `--dry-run`) before the action. Extra arguments pass +through to Docker Compose for the selected project. Each project's `.env` and +`apex.env` are supplied automatically when present. Positional targeting remains +available as `apex compose restart apex traefik` or `apex compose up -d apex`; +prefer `-p` when arguments could also name a composition. + +Replace `app` with a composition defined in your repository. When a mount or +other container definition changes, use targeted `up -d` to recreate it: +`restart` retains the existing definition. + +### Direct core Compose commands + +```bash +apex env --sync +cd compositions/apex +docker compose config --quiet +docker compose restart traefik +``` + +Sync preserves existing secret and UID/GID text in `.env` and its tier-storage +symlink. A managed block loads committed `apex.env` settings, including profiles, +then synthesized node/path values. Writes use mode `0600`. Resync after changing +those settings or paths; do not hand-edit the managed block. Docker's shell +environment still overrides file values. + +`eval "$(apex env)"`, `apex env --dotenv`, and `apex env --write generated.env` +export or save generated APEX values only. They do not load composition secrets +or replace the full `--sync` bridge. Output modes are mutually exclusive. ## Backups {#backups} @@ -46,7 +76,7 @@ Runs [resticontainer](https://github.com/deytenit/resticontainer) one-shot under apex sync/repository ``` -Commits the live checkout to `sync/`, rebases onto `origin/main`, and force-pushes with lease; CI folds the branch back into `main`. The action refuses to run — with a paged error — when the commons submodule is dirty or the `compositions/` tree is missing, and aborts cleanly on a rebase conflict (manual intervention required). See [Concept: Framework architecture](/apex/concepts/architecture#capture-up) for the model. +Commits the live checkout to `sync/`, rebases onto `origin/main`, and force-pushes with lease. The action refuses to run — with a paged error — when the commons submodule is dirty or the `compositions/` tree is missing, and aborts cleanly on a rebase conflict (manual intervention required). See [Concept: Framework architecture](/apex/concepts/architecture#capture-up) for the model. ## Update awareness {#updates} diff --git a/services/docs/content/en/apex/guides/node-repository.md b/services/docs/content/en/apex/guides/node-repository.md index deed2d1..5ed123c 100644 --- a/services/docs/content/en/apex/guides/node-repository.md +++ b/services/docs/content/en/apex/guides/node-repository.md @@ -25,7 +25,7 @@ The gitlink pins the exact engine version the node runs. Upgrading later mean ```ini {filename="node.env"} APEX_NODE_FQDN=node1.example.com APEX_NODE_HOST=node1.example.com -APEX_SUBNET=198.18.16.0/24 +APEX_SUBNET=198.18.0.0/24 APEX_GIT_AUTHOR_NAME=apex [bot] APEX_GIT_AUTHOR_EMAIL=apex@localhost ``` @@ -41,7 +41,7 @@ include: ``` ```ini {filename="compositions/apex/apex.env"} -APEX_TRAEFIK_DIRECT_IP=198.18.16.10 +APEX_TRAEFIK_DIRECT_IP=198.18.0.10 APEX_RESTIC_REPOSITORY=s3:// COMPOSE_PROFILES=adguard,xray,alloy # observability push targets (only when the alloy profile is enabled) @@ -77,9 +77,12 @@ __pycache__/ Create `compositions/ADDRESSING.md` with the node's subnet (`APEX_SUBNET`) and the reserved ranges (`.10`–`.19` core, `.20`+ services). Every [anchor IP](/apex/glossary#anchor-ip) allocated later is recorded here. -### Wire capture-up CI +### Choose a sync review policy -Add a scheduled workflow that merges `sync/` into `main` when the branch exists, committing under a bot identity. Check out **without** submodules — the merge only moves the commons pointer, and an SSH submodule URL is not fetchable with the default CI token. See [Concept: Framework architecture](/apex/concepts/architecture) for the full [capture-up](/apex/glossary#capture-up) loop. +Decide how to review and integrate the `sync/` branch produced by +`apex sync/repository`. If you automate integration, configure repository +permissions and submodule access for that workflow. See the +[capture-up model](/apex/concepts/architecture#capture-up). ### Validate diff --git a/services/docs/content/en/apex/guides/service-composition.md b/services/docs/content/en/apex/guides/service-composition.md index 456336b..7c1ff0f 100644 --- a/services/docs/content/en/apex/guides/service-composition.md +++ b/services/docs/content/en/apex/guides/service-composition.md @@ -28,7 +28,7 @@ services: - ./@tier2//data:/data networks: direct: - ipv4_address: 198.18.16.20 + ipv4_address: 198.18.0.20 enclave: {} labels: - "traefik.enable=true" diff --git a/services/docs/content/en/apex/reference/actions.md b/services/docs/content/en/apex/reference/actions.md index ae1233b..e63a482 100644 --- a/services/docs/content/en/apex/reference/actions.md +++ b/services/docs/content/en/apex/reference/actions.md @@ -4,7 +4,7 @@ description: "Every commons action: arguments and behavior." weight: 32 --- -The sixteen [commons](/apex/glossary#commons) actions, by group. Arguments are shown as the parser accepts them; optional arguments are bracketed. Exit codes follow the [engine convention](/apex/reference/cli#exit-codes). +The [commons](/apex/glossary#commons) actions, by group. Arguments are shown as the parser accepts them; optional arguments are bracketed. Exit codes follow the [engine convention](/apex/reference/cli#exit-codes). ## configure {#configure} @@ -12,13 +12,19 @@ The sixteen [commons](/apex/glossary#commons) actions, by group. Arguments are `apex configure [--dry-run]` -Runs the whole suite in fixed order — `base`, `ufw`, `crowdsec`, `cron`, `systemd`, `routing` — and stops at the first failing step, propagating its exit code. `--dry-run` is forwarded to the steps that support it. +Runs the suite in order: `base`, `timezone`, `ufw`, `crowdsec`, `cron`, `systemd`, `routing`, then additional node actions. A failing step contributes a nonzero exit status; later steps may still run. `--dry-run` is forwarded only to steps that support it, so it is not a guarantee that the entire umbrella command is read-only. ### configure/base `apex configure/base` -Debian-only guard (exit `1` elsewhere). Updates the package index, installs the essential packages (`curl`, `wget`, `git`, `rsyslog`), ensures rsyslog is running, installs `ufw` when absent, and downloads the `ufw-docker` helper to `~/.local/bin/ufw-docker` (skipped when already present). +Debian-only guard (exit `1` elsewhere). Checks installed package state for `curl`, `wget`, `git`, `rsyslog`, and `ufw`; installs missing packages and ensures rsyslog is running. Refuses an APT simulation containing upgrades or removals and uses `--no-upgrade --no-remove`. Avoid concurrent package operations: simulation and installation are separate transactions. Verifies the immutable revision and SHA-256 of `/usr/local/bin/ufw-docker` before running it as root. Unsafe paths and unverified downloads are rejected; an executable file alone is not trusted. + +### configure/timezone + +`apex configure/timezone [--dry-run]` + +Applies the IANA zone named in `configs/timezone` and refreshes active cron after a change. An absent declaration preserves the current timezone; an invalid zone fails before changing it. ### configure/ufw @@ -110,9 +116,19 @@ Two passes: (1) [anchor-IP](/apex/glossary#anchor-ip) validation over `compositi ### compose -`apex compose [--dry-run] [extra...]` +`apex compose [-p ] [--dry-run] [extra...]` -Orchestrates `docker compose ` across the node: the core project first, then services alphabetically (reversed for `down`). `up` implies `-d`; `.env`/`apex.env` are passed per project when present; extra arguments pass through; `--dry-run` (accepted in any position) prints commands instead of executing. +Without a target, visits core first and other compositions alphabetically, reversed for `down`. `-p` selects one composition or `all`; `up` defaults to detached mode. `.env` then `apex.env` are passed per project, with generated identity/path values in the process environment. Remaining arguments pass through to Docker Compose. Wrapper options precede the action; `--dry-run` prints commands without executing them. + +Compatibility forms include `apex compose restart apex traefik` and `apex compose up -d apex`. Use explicit `-p` to distinguish a composition from a service or option value. + +## env {#env} + +`apex env [--export | --dotenv | --write | --sync]` + +Default output is shell-quoted APEX exports for `eval "$(apex env)"`. `--dotenv` emits dotenv syntax; `--write` writes generated values to a separate file, including a relative filename. These modes do not read composition credentials or merge `apex.env`. + +`--sync` preserves existing `compositions/apex/.env` text and updates only its managed block: committed `apex.env` settings first, generated identity/path values last. This includes non-APEX settings such as `COMPOSE_PROFILES` and `TZ`, allowing bare Docker Compose commands in the core directory. Existing tier symlinks remain intact, and synchronized files use mode `0600`. Resync after changing source settings or tier paths. Malformed managed markers fail without rewriting uncertain content. Shell environment values still have Docker Compose precedence. --- diff --git a/services/docs/content/ru/apex/concepts/architecture.md b/services/docs/content/ru/apex/concepts/architecture.md index 32f0420..13b1915 100644 --- a/services/docs/content/ru/apex/concepts/architecture.md +++ b/services/docs/content/ru/apex/concepts/architecture.md @@ -53,15 +53,14 @@ flowchart TD ## Модель «capture-up» {#capture-up} -Репозитории узлов служат реестрами состояния, а не просто источниками конфигурации: хост сам фиксирует то, что выполняет на практике. +Команда `apex sync/repository` фиксирует рабочее дерево и версию commons +в ветке `sync/`, выполняет rebase на `origin/main` и отправляет ветку +с флагом `--force-with-lease`. Если в commons есть незакоммиченные изменения +или каталог `compositions/` отсутствует, команда отказывается работать. +Конфликт rebase прерывает синхронизацию. -1. Регулярная задача `sync/repository` на хосте коммитит рабочее дерево в ветку `sync/` (включая указатель субмодуля commons), делает rebase поверх `origin/main` и выполняет push с флагом `--force-with-lease`. -2. Запланированное CI-задание в репозитории узла вливает ветку `sync/` обратно в `main` от имени бота. - -Благодаря циклу [«capture-up»](/apex/glossary#capture-up) любой дрейф конфигурации на хосте превращается в коммит: изменение наглядно отображается в diff и легко откатывается, исключая незаметные расхождения. Если субмодуль commons имеет незакоммиченные изменения («грязный») или каталог `compositions/` отсутствует, синхронизация прерывается без коммита, поэтому повреждённое состояние чекаута никогда не попадёт в историю. - -> [!NOTE] -> CI-задание слияния клонирует репозиторий *без* субмодулей: субмодуль commons подключён по SSH-URL, недоступному стандартному токену CI, а самому слиянию требуется лишь обновить указатель gitlink. +Проверку и слияние этой ветки определяют правила репозитория. APEX не поставляет +CI-сценарий слияния и не требует определённого способа размещения репозиториев. ## Проектные ограничения {#constraints} diff --git a/services/docs/content/ru/apex/concepts/compositions.md b/services/docs/content/ru/apex/concepts/compositions.md index 374aa31..dfa9445 100644 --- a/services/docs/content/ru/apex/concepts/compositions.md +++ b/services/docs/content/ru/apex/concepts/compositions.md @@ -44,7 +44,7 @@ include: |---|---|---| | `xray` | xray | Прокси-шлюз с режимом host-network для анклава. | | `adguard` | adguard | DNS-фильтрация в сетевом пространстве имён traefik; маршрутизируется по пути `/adguard` на FQDN узла. | -| `alloy` | alloy | Агент наблюдаемости на каждом узле (Grafana Alloy). Собирает метрики хоста и контейнеров, а также логи systemd journal и контейнеров, после чего **проталкивает** их исходящим потоком в центральные Prometheus и Loki (см. [Концепция: Модель безопасности](/apex/concepts/security-model#observability)). Имя хоста (`hostname`) контейнера совпадает с `APEX_NODE_HOST`, благодаря чему метки `node` и `instance` автоматически проставляются на всех метриках и потоках логов. | +| `alloy` | alloy | Необязательный агент Grafana Alloy. Отправляет метрики хоста и контейнеров, системный журнал и логи контейнеров на заданные совместимые конечные точки. См. [настройку наблюдаемости](/apex/concepts/security-model#observability). | | `manual` | resticontainer | Одноразовый контейнер резервного копирования на основе меток (`ghcr.io/deytenit/resticontainer`). Никогда не запускается командой `up`; вызывается действием `backup/run`, которое определяет необходимость бэкапа каждого сервиса по compose-меткам `restic.*`. | ## Сети {#networks} diff --git a/services/docs/content/ru/apex/concepts/node-identity.md b/services/docs/content/ru/apex/concepts/node-identity.md index 7270d52..127919f 100644 --- a/services/docs/content/ru/apex/concepts/node-identity.md +++ b/services/docs/content/ru/apex/concepts/node-identity.md @@ -21,7 +21,7 @@ weight: 12 ```ini {filename="node.env"} APEX_NODE_FQDN=node1.example.com APEX_NODE_HOST=node1.example.com -APEX_SUBNET=198.18.16.0/24 +APEX_SUBNET=198.18.0.0/24 ``` ### Имя хоста ОС diff --git a/services/docs/content/ru/apex/concepts/security-model.md b/services/docs/content/ru/apex/concepts/security-model.md index de10cdb..d55c450 100644 --- a/services/docs/content/ru/apex/concepts/security-model.md +++ b/services/docs/content/ru/apex/concepts/security-model.md @@ -34,7 +34,11 @@ weight: 18 ## Наблюдаемость {#observability} -Система мониторинга построена по модели **исходящей отправки (push)**, а не входящих опросов. Опциональный сервис `alloy` (Grafana Alloy, один агент на узел) собирает метрики хоста (аналог `node_exporter`), метрики контейнеров (cadvisor), системный журнал systemd journal и логи docker-контейнеров, после чего передаёт их в **центральные** хранилища Prometheus и Loki на выделенном узле. Метрики отправляются через `prometheus.remote_write` на адрес `APEX_PROM_PUSH_URL`, логи — через `loki.write` на `APEX_LOKI_PUSH_URL`. Обе конечные точки защищены базовой аутентификацией HTTP basic auth (`APEX_OBS_BASIC_AUTH_USER` / `APEX_OBS_BASIC_AUTH_PASS`). Поскольку трафик отправляется наружу, Alloy подключён к сети `direct` с доступом в интернет, а не к закрытой сети `enclave`. На самих узлах логи не накапливаются, и открывать внешний доступ к эндпоинтам сервисов не требуется. +Необязательный сервис `alloy` отправляет метрики хоста и контейнеров на адрес +`APEX_PROM_PUSH_URL`, а логи — на `APEX_LOKI_PUSH_URL`. Укажите совместимые +конечные точки и учётные данные HTTP basic auth в `APEX_OBS_BASIC_AUTH_USER` +и `APEX_OBS_BASIC_AUTH_PASS`. Сервису нужен исходящий доступ к этим адресам. +Размещение хранилищ и правила доступа определяет оператор. ## Изоляция секретов {#secrets} diff --git a/services/docs/content/ru/apex/glossary.md b/services/docs/content/ru/apex/glossary.md index 1c2ea3a..ff935b1 100644 --- a/services/docs/content/ru/apex/glossary.md +++ b/services/docs/content/ru/apex/glossary.md @@ -16,7 +16,7 @@ weight: 100 ## Capture-up {#capture-up} -**Capture-up** — механизм фиксации состояния хоста в репозитории: регулярный коммит в ветку `sync/`, который перебазируется на `main` и сливается средствами CI. В результате любой дрейф конфигурации становится наглядным diff, а не скрытым расхождением. +**Capture-up** — фиксация рабочего состояния хоста в ветке `sync/` командой `apex sync/repository`. Проверку и слияние определяют правила репозитория. ## Commons {#commons} diff --git a/services/docs/content/ru/apex/guides/host-operations.md b/services/docs/content/ru/apex/guides/host-operations.md index 3cbffc7..ef23ed9 100644 --- a/services/docs/content/ru/apex/guides/host-operations.md +++ b/services/docs/content/ru/apex/guides/host-operations.md @@ -12,7 +12,8 @@ weight: 24 | Шаг | Эффект | |---|---| -| `configure/base` | Готовит базовую систему Debian: обновляет списки пакетов, ставит базовые утилиты (`curl`, `wget`, `git`, `rsyslog`), запускает службу rsyslog, устанавливает `ufw` и вспомогательный скрипт `ufw-docker` в `~/.local/bin/ufw-docker`. | +| `configure/base` | Устанавливает недостающие пакеты Debian после проверки плана APT на обновления и удаления, запускает rsyslog и проверяет закреплённую версию `/usr/local/bin/ufw-docker` перед запуском от root. Не запускайте другие пакетные операции одновременно. | +| `configure/timezone` | Применяет `configs/timezone`, если файл есть, и перезапускает активную службу cron после смены часового пояса. Поддерживает `--dry-run`. | | `configure/ufw` | Применяет правила хоста, настраивает цепочки правил ядра и пробрасывает правила для контейнеров через `ufw-docker`. Поддерживает флаг `--dry-run`. | | `configure/crowdsec` | Устанавливает CrowdSec (если он ещё не поставлен), копирует `configs/crowdsec/` в `/etc/crowdsec/`, ставит коллекции и firewall bouncer (если включён в настройках). Поддерживает флаг `--dry-run`. | | `configure/cron` | Рендерит `configs/cron/crontab` через шаблонизатор и устанавливает расписание. Предусмотрены предпросмотр, аварийная остановка при пустом результате (код выхода 65) и откат при ошибке установки. Поддерживает флаг `--dry-run`. | @@ -27,10 +28,39 @@ weight: 24 apex compose up # сначала core, затем сервисы по алфавиту apex compose down # обратный порядок apex compose restart -apex compose up --dry-run # только напечатать команды +apex compose --dry-run up # только напечатать команды +apex compose -p apex restart traefik +apex compose -p app up -d ``` -Все дополнительные аргументы движок передаёт напрямую в `docker compose` каждого проекта. Файлы `.env` и `apex.env` проектных каталогов подставляются автоматически при их наличии. +Указывайте параметры APEX (`-p` и `--dry-run`) перед действием. Остальные аргументы +передаются Docker Compose для выбранного проекта. Файлы `.env` и `apex.env` +подключаются автоматически, если существуют. Формы `apex compose restart apex traefik` +и `apex compose up -d apex` сохраняются; если имя сервиса или значение параметра +совпадает с именем композиции, выбирайте цель через `-p`. + +Замените `app` именем композиции из своего репозитория. После изменения +монтирования или конфигурации контейнера используйте `up -d` для нужной +композиции; `restart` сохраняет прежнюю конфигурацию контейнера. + +### Прямой запуск Compose для core + +```bash +apex env --sync +cd compositions/apex +docker compose config --quiet +docker compose restart traefik +``` + +Синхронизация сохраняет текст секретов и UID/GID в `.env`, а также ссылку +на файл в хранилище tier. Управляемый блок содержит настройки `apex.env`, включая +профили, затем вычисленные значения узла и путей. Файл записывается с правами +`0600`. Повторите синхронизацию после изменения настроек или путей; не редактируйте +управляемый блок вручную. Переменные оболочки сохраняют приоритет Docker Compose. + +`eval "$(apex env)"`, `apex env --dotenv` и `apex env --write generated.env` +выводят или записывают только вычисленные значения APEX. Они не загружают секреты +композиции и не заменяют `--sync`. Выбирайте один режим вывода за вызов. ## Резервные копии {#backups} @@ -53,7 +83,7 @@ apex backup/run "$(cat )" apex sync/repository ``` -Действие фиксирует изменения рабочей копии в ветке `sync/`, выполняет rebase на `origin/main` и отправляет ветку через force-push с lease. Затем CI автоматически вливает изменения обратно в `main`. Этот механизм (capture-up) сохраняет актуальное состояние узла в репозиторий. +Действие фиксирует изменения рабочей копии в ветке `sync/`, выполняет rebase на `origin/main` и отправляет ветку через force-push с lease. Этот механизм (capture-up) сохраняет актуальное состояние узла в репозиторий. Действие прерывается с подробным сообщением, если подмодуль commons содержит незакоммиченные изменения или каталог `compositions/` отсутствует. При конфликтах rebase выполнение останавливается для ручного вмешательства. Подробнее архитектурная модель описана в разделе [Concept: Framework architecture](/apex/concepts/architecture#capture-up). diff --git a/services/docs/content/ru/apex/guides/node-repository.md b/services/docs/content/ru/apex/guides/node-repository.md index 37ce70e..25c9aca 100644 --- a/services/docs/content/ru/apex/guides/node-repository.md +++ b/services/docs/content/ru/apex/guides/node-repository.md @@ -25,7 +25,7 @@ mkdir -p proprietaries/actions proprietaries/lib configs compositions/apex .gith ```ini {filename="node.env"} APEX_NODE_FQDN=node1.example.com APEX_NODE_HOST=node1.example.com -APEX_SUBNET=198.18.16.0/24 +APEX_SUBNET=198.18.0.0/24 APEX_GIT_AUTHOR_NAME=apex [bot] APEX_GIT_AUTHOR_EMAIL=apex@localhost ``` @@ -46,7 +46,7 @@ include: ``` ```ini {filename="compositions/apex/apex.env"} -APEX_TRAEFIK_DIRECT_IP=198.18.16.10 +APEX_TRAEFIK_DIRECT_IP=198.18.0.10 APEX_RESTIC_REPOSITORY=s3:// COMPOSE_PROFILES=adguard,xray,alloy # цели push-наблюдаемости (только когда включён профиль alloy) @@ -84,9 +84,12 @@ __pycache__/ Создайте файл `compositions/ADDRESSING.md` с подсетью узла (`APEX_SUBNET`) и схемой распределения адресов: диапазоны `.10`–`.19` зарезервированы за базовыми сервисами (core), а `.20` и выше выделяются под проекты. Все назначаемые в будущем [якорные IP](/apex/glossary#anchor-ip) фиксируются в этом документе. -### Подключите CI capture-up +### Определите правила проверки синхронизации -Настройте периодический CI-workflow, который автоматически вливает ветку `sync/` в `main` (если ветка существует) с авторством бота. Шаг checkout должен выполняться **без** загрузки подмодулей: слияние только сдвигает указатель `commons`, а SSH-ссылка на подмодуль недоступна по стандартному CI-токену. Полный цикл описан в разделе [Concept: Framework architecture](/apex/concepts/architecture) ([capture-up](/apex/glossary#capture-up)). +Решите, как проверять и вливать ветку `sync/`, которую создаёт +`apex sync/repository`. Для автоматического слияния настройте разрешения +репозитория и доступ к субмодулям под выбранный сценарий. +См. [модель capture-up](/apex/concepts/architecture#capture-up). ### Проверьте работу diff --git a/services/docs/content/ru/apex/guides/service-composition.md b/services/docs/content/ru/apex/guides/service-composition.md index 8cff85b..4f91690 100644 --- a/services/docs/content/ru/apex/guides/service-composition.md +++ b/services/docs/content/ru/apex/guides/service-composition.md @@ -28,7 +28,7 @@ services: - ./@tier2//data:/data networks: direct: - ipv4_address: 198.18.16.20 + ipv4_address: 198.18.0.20 enclave: {} labels: - "traefik.enable=true" diff --git a/services/docs/content/ru/apex/reference/actions.md b/services/docs/content/ru/apex/reference/actions.md index 69acd4f..292db50 100644 --- a/services/docs/content/ru/apex/reference/actions.md +++ b/services/docs/content/ru/apex/reference/actions.md @@ -4,7 +4,7 @@ description: "Каждое действие commons: аргументы и по weight: 32 --- -Шестнадцать действий [«commons»](/apex/glossary#commons) (общего репозитория), разбитых по группам. Аргументы показаны в том виде, в котором их принимает парсер; необязательные аргументы заключены в квадратные скобки. Коды возврата следуют [соглашению движка](/apex/reference/cli#exit-codes). +Действия [commons](/apex/glossary#commons) по группам. Аргументы показаны в том виде, в котором их принимает парсер; необязательные аргументы заключены в квадратные скобки. Коды возврата следуют [соглашению движка](/apex/reference/cli#exit-codes). ## configure {#configure} @@ -12,13 +12,19 @@ weight: 32 `apex configure [--dry-run]` -Запускает весь набор в фиксированном порядке (`base`, `ufw`, `crowdsec`, `cron`, `systemd`, `routing`) и останавливается на первом неудачном шаге, возвращая его код возврата. Флаг `--dry-run` передаётся шагам, которые его поддерживают. +Запускает `base`, `timezone`, `ufw`, `crowdsec`, `cron`, `systemd`, `routing`, затем дополнительные действия узла. Ошибка шага даёт ненулевой итоговый код; последующие шаги могут продолжить работу. Флаг `--dry-run` передаётся только тем шагам, которые его поддерживают, поэтому не гарантирует отсутствие изменений для всей команды. ### configure/base `apex configure/base` -Проверяет, что операционная система — Debian (иначе завершается с кодом `1`). Обновляет индекс пакетов, устанавливает необходимые пакеты (`curl`, `wget`, `git`, `rsyslog`), проверяет статус службы `rsyslog`, устанавливает `ufw`, если его нет, и загружает вспомогательную утилиту `ufw-docker` в `~/.local/bin/ufw-docker` (если утилита уже есть, загрузка пропускается). +Проверяет, что операционная система — Debian; иначе завершается с кодом `1`. Проверяет состояние пакетов `curl`, `wget`, `git`, `rsyslog` и `ufw`, устанавливает недостающие и запускает rsyslog. Отклоняет план APT с обновлениями или удалениями и использует `--no-upgrade --no-remove`. Не запускайте другие пакетные операции одновременно: проверка плана и установка выполняются отдельно. Перед запуском `/usr/local/bin/ufw-docker` от root проверяет закреплённую ревизию и SHA-256. Небезопасные пути и непроверенные загрузки отклоняются; одних прав на исполнение недостаточно. + +### configure/timezone + +`apex configure/timezone [--dry-run]` + +Применяет часовой пояс IANA из `configs/timezone` и перезапускает активную службу cron после изменения. Если файла нет, сохраняет текущий пояс; неверное имя приводит к ошибке до внесения изменений. ### configure/ufw @@ -110,9 +116,19 @@ weight: 32 ### compose -`apex compose [--dry-run] [extra...]` +`apex compose [-p ] [--dry-run] [extra...]` -Оркеструет запуск `docker compose ` по всему узлу: сначала основной проект, затем сервисы в алфавитном порядке (в обратном — для команды `down`). Команда `up` по умолчанию использует ключ `-d`; файлы `.env` и `apex.env` подключаются для каждого проекта при их наличии; дополнительные аргументы пробрасываются дальше; флаг `--dry-run` (принимается в любой позиции) выводит сформированные команды без их выполнения. +Без цели обходит сначала core, затем остальные композиции по алфавиту; для `down` порядок обратный. Параметр `-p` выбирает одну композицию или `all`. Команда `up` по умолчанию добавляет `-d`; файлы `.env` и `apex.env` подключаются в этом порядке, вычисленные значения узла и путей передаются через окружение. Параметры APEX ставятся перед действием, остальные аргументы передаются Docker Compose. Флаг `--dry-run` печатает команды без запуска. + +Сохраняются формы `apex compose restart apex traefik` и `apex compose up -d apex`. Используйте `-p`, чтобы явно отличить композицию от сервиса или значения параметра. + +## env {#env} + +`apex env [--export | --dotenv | --write | --sync]` + +По умолчанию выводит экспорты APEX для `eval "$(apex env)"` с экранированием оболочки. `--dotenv` выводит формат dotenv; `--write` записывает вычисленные значения в отдельный файл, в том числе по относительному пути. Эти режимы не читают секреты композиции и не объединяют `apex.env`. + +Режим `--sync` сохраняет пользовательский текст `compositions/apex/.env` и обновляет управляемый блок: сначала настройки `apex.env`, затем вычисленные значения. В блок входят `COMPOSE_PROFILES` и `TZ`, поэтому Compose можно запускать напрямую из каталога core. Ссылки tier сохраняются, файл получает права `0600`. Повторяйте синхронизацию после изменения исходных настроек или путей. Некорректные маркеры останавливают запись; переменные оболочки сохраняют приоритет Docker Compose. ---