docs(orchestrator): adopt enduro doc canon + CLAUDE.md + ADR (ORCH-9)
All checks were successful
CI / test (pull_request) Successful in 9s
All checks were successful
CI / test (pull_request) Successful in 9s
This commit is contained in:
90
docs/operations/DEPLOY_HOOK.md
Normal file
90
docs/operations/DEPLOY_HOOK.md
Normal file
@@ -0,0 +1,90 @@
|
||||
# Orchestrator Deploy Hook
|
||||
|
||||
`scripts/orchestrator-deploy-hook.sh` — хост-скрипт деплоя orchestrator с health-чеком и авто-rollback.
|
||||
|
||||
## Как работает
|
||||
|
||||
### Режим `--deploy` (по умолчанию)
|
||||
|
||||
1. **Захват текущего образа** — до рестарта записывает ID образа работающего контейнера в `$PREV_IMAGE_FILE` (best-effort, не падает если сервис не запущен).
|
||||
2. **git pull** — обновляет код репозитория.
|
||||
3. **Рестарт контейнера** — `docker compose --profile $COMPOSE_PROFILE up -d --no-build $TARGET_SERVICE`.
|
||||
4. **Health-цикл** — 10 попыток × 6с = до 60с. Критерий: HTTP 200 + тело содержит `"status":"ok"`.
|
||||
- **Успех** → `exit 0`, лог "Deploy SUCCESS".
|
||||
- **Провал** → авто-rollback (шаг 5).
|
||||
5. **Авто-rollback** — восстанавливает образ из `$PREV_IMAGE_FILE`, рестарт, повторный health 5×3с.
|
||||
- Если восстановился → `exit 1` (деплой провалился, откат успешен).
|
||||
- Если и откат не помог → `exit 2` (критично).
|
||||
|
||||
### Режим `--rollback`
|
||||
|
||||
Вручную откатывает сервис на предыдущий образ из `$PREV_IMAGE_FILE`.
|
||||
|
||||
## Переменные окружения
|
||||
|
||||
| Переменная | Дефолт | Описание |
|
||||
|------------------|-----------------------------------|-----------------------------------------------|
|
||||
| `TARGET_SERVICE` | `orchestrator-staging` | Имя docker-compose сервиса |
|
||||
| `TARGET_PORT` | `8501` | Порт health-check |
|
||||
| `TARGET_IMAGE` | `orchestrator-orchestrator-staging` | Имя образа для retag при rollback |
|
||||
| `COMPOSE_PROFILE`| `staging` | Docker compose profile (пусто = без профиля) |
|
||||
| `PREV_IMAGE_FILE`| `$REPO/.deploy-prev-image-staging`| Файл для сохранения предыдущего образа |
|
||||
| `LOG` | `/var/log/orchestrator/deploy-hook.log` | Лог-файл (fallback: `$REPO/deploy-hook.log`) |
|
||||
|
||||
> ⚠️ **Дефолт — всегда STAGING**. Прод активируется только явным переопределением env.
|
||||
|
||||
## Примеры запуска
|
||||
|
||||
### Staging (дефолт, безопасно)
|
||||
|
||||
```bash
|
||||
cd /home/slin/repos/orchestrator
|
||||
bash scripts/orchestrator-deploy-hook.sh --deploy
|
||||
# или просто:
|
||||
bash scripts/orchestrator-deploy-hook.sh
|
||||
```
|
||||
|
||||
### Прод (осознанный шаг, Этап 5)
|
||||
|
||||
```bash
|
||||
TARGET_SERVICE=orchestrator \
|
||||
TARGET_PORT=8500 \
|
||||
TARGET_IMAGE=orchestrator-orchestrator \
|
||||
COMPOSE_PROFILE="" \
|
||||
PREV_IMAGE_FILE=/home/slin/repos/orchestrator/.deploy-prev-image-prod \
|
||||
bash scripts/orchestrator-deploy-hook.sh --deploy
|
||||
```
|
||||
|
||||
### Ручной rollback staging
|
||||
|
||||
```bash
|
||||
bash scripts/orchestrator-deploy-hook.sh --rollback
|
||||
```
|
||||
|
||||
## Коды выхода
|
||||
|
||||
| Код | Значение |
|
||||
|-----|------------------------------------------------------|
|
||||
| `0` | Деплой успешен, сервис здоров |
|
||||
| `1` | Деплой провалился; откат выполнен (или пропущен) |
|
||||
| `2` | Деплой провалился И откат тоже провалился (критично) |
|
||||
|
||||
## Логи
|
||||
|
||||
```
|
||||
/var/log/orchestrator/deploy-hook.log
|
||||
```
|
||||
|
||||
Каждая строка с UTC-таймстампом в формате `[2026-06-05T06:30:00Z]`.
|
||||
|
||||
## Разница с enduro-deploy-hook.sh
|
||||
|
||||
| Функция | enduro-deploy-hook.sh | orchestrator-deploy-hook.sh |
|
||||
|----------------------|-----------------------|-----------------------------|
|
||||
| Захват PREV_IMG | ✅ | ✅ |
|
||||
| git pull | ✅ | ✅ |
|
||||
| Рестарт | ✅ | ✅ |
|
||||
| Health-цикл (60с) | ❌ | ✅ 10×6с |
|
||||
| Авто-rollback | ❌ | ✅ |
|
||||
| Параметризация (env) | ❌ хардкод | ✅ дефолт=staging |
|
||||
| Compose profile | ❌ | ✅ --profile staging |
|
||||
96
docs/operations/INFRA.md
Normal file
96
docs/operations/INFRA.md
Normal file
@@ -0,0 +1,96 @@
|
||||
# INFRA.md — инфраструктура и эксплуатация оркестратора
|
||||
|
||||
> RUNBOOK. Топология, контейнеры, порты, переменные окружения, границы.
|
||||
> **Секреты тут НЕ хранятся** — только дескрипторы. Реальные значения — в `.env` на хосте.
|
||||
|
||||
## Топология
|
||||
|
||||
```
|
||||
host: mva154 (slin@82.22.50.71), network_mode: host
|
||||
┌──────────────────────────────────────────────────────────────────────┐
|
||||
│ orchestrator (PROD) :8500 env_file .env │
|
||||
│ БД: ./data/orchestrator.db (обслуживает ВСЕ прод-проекты) │
|
||||
│ │
|
||||
│ orchestrator-staging (STAGING) :8501 env_file .env.staging │
|
||||
│ БД: ./data/staging/orchestrator.db (изолирована, только sandbox) │
|
||||
│ profile: staging — НЕ стартует обычным `docker compose up` │
|
||||
└──────────────────────────────────────────────────────────────────────┘
|
||||
│ webhooks │ git
|
||||
▼ ▼
|
||||
Plane (ag_proj) Gitea (localhost:3000)
|
||||
/repos/<project> ← общий каталог репозиториев (host: /home/slin/repos)
|
||||
```
|
||||
|
||||
## Контейнеры
|
||||
|
||||
| Контейнер | Роль | Порт | env_file | БД (хост) | Старт |
|
||||
|-----------|------|------|----------|-----------|-------|
|
||||
| `orchestrator` | прод | 8500 | `.env` | `./data/orchestrator.db` | `docker compose up -d` |
|
||||
| `orchestrator-staging` | staging / песочница | 8501 | `.env.staging` | `./data/staging/orchestrator.db` | `docker compose --profile staging up -d orchestrator-staging` |
|
||||
|
||||
Оба: `network_mode: host`, `init: true` (tini как PID 1 — reaping зомби, B-2), `restart: unless-stopped`.
|
||||
|
||||
### Тома (volumes)
|
||||
- `./data` → `/app/data` (БД; у staging — `./data/staging`)
|
||||
- `/home/slin/repos` → `/repos` (рабочие репозитории проектов)
|
||||
- `/var/run/docker.sock` (для docker-операций деплоя)
|
||||
- claude-code, node, `~/.claude*` (CLI агентов, ro)
|
||||
- `~/.orchestrator-ssh` → `/root/.ssh` (ro, деплой по ssh)
|
||||
|
||||
## Переменные окружения (карта; значения — в `.env`)
|
||||
|
||||
| Переменная | Назначение |
|
||||
|-----------|-----------|
|
||||
| `ORCH_PLANE_API_URL` / `_TOKEN` / `_WORKSPACE_SLUG` | доступ к Plane API |
|
||||
| `ORCH_PLANE_WEBHOOK_SECRET` | HMAC-проверка вебхуков Plane |
|
||||
| `ORCH_GITEA_URL` / `_TOKEN` / `_WEBHOOK_SECRET` | доступ к Gitea + HMAC |
|
||||
| `ORCH_CLAUDE_BIN` | путь к claude CLI |
|
||||
| `ORCH_REPOS_DIR` / `ORCH_HOST_REPOS_DIR` | каталог репозиториев (в контейнере / на хосте) |
|
||||
| `ORCH_DB_PATH` | путь к SQLite БД |
|
||||
| `ORCH_PROJECTS_JSON` | реестр проектов (Plane id → repo + prefix); пусто → дефолт из `src/projects.py` |
|
||||
| `DEPLOY_SSH_USER` / `_HOST` / `DEPLOY_HOOK_SCRIPT` | параметры деплой-хука |
|
||||
|
||||
**Секреты — только в `.env` / `.env.staging` на хосте, в гит НЕ коммитятся.** Канон — `.env.example`, `.env.staging.example`.
|
||||
|
||||
## Реестр проектов (`src/projects.py`, ORCH-6)
|
||||
Связывает Plane project id → gitea repo + work-item prefix. Источник: `ORCH_PROJECTS_JSON`, fallback — встроенный дефолт. Прод видит: `enduro-trails` (ET), `orchestrator` (ORCH). Staging видит ТОЛЬКО `orchestrator-sandbox` (SANDBOX) — изоляция.
|
||||
|
||||
## ⚠️ Self-hosting — оркестратор дорабатывает САМ СЕБЯ
|
||||
|
||||
**Факт:** прод-инстанс `orchestrator` (8500) — ОДИН на ВСЕ прод-проекты (enduro-trails + orchestrator), с ОБЩЕЙ БД `./data/orchestrator.db` и общей очередью задач (ORCH-1).
|
||||
|
||||
**Следствие — групповой риск:** когда орк выполняет задачу из проекта ORCH (дорабатывает себя), он бежит в том же инстансе, что обслуживает enduro-trails.
|
||||
- Рестарт / падение прод-контейнера орк-задачей → конвейер ВСЕХ проектов встаёт.
|
||||
- Кривой self-деплой (ORCH-36, Вариант B) → лежат все проекты сразу.
|
||||
- Общая очередь → орк-задача занимает concurrency-слоты других проектов.
|
||||
|
||||
**Что изолировано (безопасно):**
|
||||
- Staging (8501) — отдельная БД (`./data/staging`), отдельный реестр (`ORCH_PROJECTS_JSON` = только sandbox). Прод-проекты не видит.
|
||||
- Репозитории разделены, изоляция веток через git worktree (ORCH-2).
|
||||
|
||||
**Страховки:**
|
||||
- Стадия `deploy-staging` (порт 8501) — обязательный гейт перед прод-деплоем орка. Прод-деплой недостижим, пока staging-гейт не зелёный (см. `STAGING.md`, ORCH-35). Гейт условный: реален только для self-hosting (repo=orchestrator), для остальных проектов — no-op.
|
||||
|
||||
**Правила для агентов при задачах ORCH:**
|
||||
1. НЕ перезапускать / не ронять прод-контейнер `orchestrator` в рамках задачи.
|
||||
2. Все проверки деплоя — на staging (8501), боевой 8500 не трогать.
|
||||
3. Деплой self — только через хук с health-check + авто-rollback (`DEPLOY_HOOK.md`).
|
||||
|
||||
## Эксплуатация (быстрые команды)
|
||||
```bash
|
||||
# статус
|
||||
docker ps --filter name=orchestrator
|
||||
curl -s http://localhost:8500/health
|
||||
curl -s http://localhost:8500/status # активные задачи
|
||||
curl -s http://localhost:8500/queue # очередь
|
||||
|
||||
# поднять staging-песочницу
|
||||
docker compose --profile staging up -d orchestrator-staging
|
||||
curl -s http://localhost:8501/health
|
||||
|
||||
# логи
|
||||
docker logs --tail 100 orchestrator
|
||||
```
|
||||
|
||||
---
|
||||
*RUNBOOK 2026-06-05. Обновлять при изменении топологии/портов/переменных. См. CONTRIBUTING.md §8.*
|
||||
163
docs/operations/SETUP_WEBHOOKS.md
Normal file
163
docs/operations/SETUP_WEBHOOKS.md
Normal file
@@ -0,0 +1,163 @@
|
||||
# Webhook Setup: Plane + Gitea → Orchestrator
|
||||
|
||||
## Архитектура
|
||||
|
||||
```
|
||||
Gitea (push/PR/CI) ──→ Nginx proxy ──→ Orchestrator /webhook/gitea
|
||||
Plane (work_item/comment) ──→ Nginx proxy ──→ Orchestrator /webhook/plane
|
||||
```
|
||||
|
||||
External URL: `https://openclaw.mva154.duckdns.org/orchestrator/`
|
||||
Internal URL: `http://127.0.0.1:8500/`
|
||||
|
||||
---
|
||||
|
||||
## Gitea Webhook
|
||||
|
||||
**Создан автоматически через API.**
|
||||
|
||||
- URL: `https://openclaw.mva154.duckdns.org/orchestrator/webhook/gitea`
|
||||
- Events: `push`, `pull_request`, `status`
|
||||
- Secret: значение `ORCH_GITEA_WEBHOOK_SECRET` в `.env`
|
||||
- Signature header: `X-Gitea-Signature` (HMAC-SHA256 hex digest)
|
||||
|
||||
### Проверка
|
||||
|
||||
```bash
|
||||
GITEA_TOKEN=$(grep ORCH_GITEA_TOKEN /home/slin/repos/orchestrator/.env | cut -d= -f2)
|
||||
curl -s "http://localhost:3000/api/v1/repos/admin/enduro-trails/hooks" \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" | python3 -m json.tool
|
||||
```
|
||||
|
||||
### Пересоздание (если нужно)
|
||||
|
||||
```bash
|
||||
GITEA_WEBHOOK_SECRET=$(openssl rand -hex 20)
|
||||
# Обновить в .env: ORCH_GITEA_WEBHOOK_SECRET=<new_secret>
|
||||
|
||||
curl -X POST "http://localhost:3000/api/v1/repos/admin/enduro-trails/hooks" \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"type": "gitea",
|
||||
"active": true,
|
||||
"config": {
|
||||
"url": "https://openclaw.mva154.duckdns.org/orchestrator/webhook/gitea",
|
||||
"content_type": "json",
|
||||
"secret": "'${GITEA_WEBHOOK_SECRET}'"
|
||||
},
|
||||
"events": ["push", "pull_request", "status"],
|
||||
"branch_filter": "*"
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Plane Webhook
|
||||
|
||||
**Создан напрямую в PostgreSQL** (Plane CE не экспортирует webhook API через внешний /api/v1/).
|
||||
|
||||
- URL: `https://openclaw.mva154.duckdns.org/orchestrator/webhook/plane`
|
||||
- Events: `issue` (work_item.created), `issue_comment` (comment.created)
|
||||
- Secret: значение `ORCH_PLANE_WEBHOOK_SECRET` в `.env`
|
||||
- Signature header: `X-Plane-Signature` (HMAC-SHA256 hex digest)
|
||||
|
||||
### Проверка
|
||||
|
||||
```bash
|
||||
docker exec -e PGPASSWORD=plane plane-app-plane-db-1 psql -U plane -d plane -c \
|
||||
"SELECT id, url, is_active FROM webhooks;"
|
||||
```
|
||||
|
||||
### Ручная настройка через UI (альтернатива)
|
||||
|
||||
1. Открыть `https://plane.mva154.duckdns.org`
|
||||
2. Workspace Settings → Webhooks → Add Webhook
|
||||
3. URL: `https://openclaw.mva154.duckdns.org/orchestrator/webhook/plane`
|
||||
4. Secret: значение из `ORCH_PLANE_WEBHOOK_SECRET` в `.env`
|
||||
5. Events: Issue, Issue Comment
|
||||
6. Save
|
||||
|
||||
### Пересоздание через SQL
|
||||
|
||||
```bash
|
||||
PLANE_WEBHOOK_SECRET=$(openssl rand -hex 20)
|
||||
# Обновить в .env: ORCH_PLANE_WEBHOOK_SECRET=<new_secret>
|
||||
|
||||
WORKSPACE_ID=$(docker exec -e PGPASSWORD=plane plane-app-plane-db-1 psql -U plane -d plane -t -A -c \
|
||||
"SELECT id FROM workspaces WHERE slug='ag_proj'")
|
||||
|
||||
WEBHOOK_ID=$(cat /proc/sys/kernel/random/uuid)
|
||||
|
||||
docker exec -e PGPASSWORD=plane plane-app-plane-db-1 psql -U plane -d plane -c "
|
||||
INSERT INTO webhooks (id, created_at, updated_at, deleted_at, workspace_id, url, is_active, secret_key, project, issue, module, cycle, issue_comment, is_internal, version)
|
||||
VALUES ('${WEBHOOK_ID}', NOW(), NOW(), NULL, '${WORKSPACE_ID}',
|
||||
'https://openclaw.mva154.duckdns.org/orchestrator/webhook/plane',
|
||||
true, '${PLANE_WEBHOOK_SECRET}', true, true, false, false, true, false, 'v1');
|
||||
"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## HMAC Signature Verification
|
||||
|
||||
Оба handler'а проверяют подпись:
|
||||
- Если secret пустой в `.env` — верификация пропускается (для dev/debug)
|
||||
- Если secret задан — запрос без валидной подписи получает `401 Unauthorized`
|
||||
|
||||
### Формат подписи
|
||||
|
||||
| Source | Header | Algorithm | Format |
|
||||
|--------|--------|-----------|--------|
|
||||
| Gitea | `X-Gitea-Signature` | HMAC-SHA256 | hex digest (без префикса) |
|
||||
| Plane | `X-Plane-Signature` | HMAC-SHA256 | hex digest |
|
||||
|
||||
### Тест подписи вручную
|
||||
|
||||
```bash
|
||||
SECRET=$(grep ORCH_GITEA_WEBHOOK_SECRET /home/slin/repos/orchestrator/.env | cut -d= -f2)
|
||||
BODY='{"ref":"refs/heads/test","repository":{"name":"enduro-trails"},"commits":[]}'
|
||||
SIG=$(echo -n "${BODY}" | openssl dgst -sha256 -hmac "${SECRET}" | awk '{print $NF}')
|
||||
|
||||
curl -X POST http://localhost:8500/webhook/gitea \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-Gitea-Event: push" \
|
||||
-H "X-Gitea-Signature: ${SIG}" \
|
||||
-d "${BODY}"
|
||||
# Expected: {"status":"accepted"}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Переменные окружения (.env)
|
||||
|
||||
| Переменная | Описание |
|
||||
|-----------|----------|
|
||||
| `ORCH_GITEA_WEBHOOK_SECRET` | HMAC secret для Gitea webhook |
|
||||
| `ORCH_PLANE_WEBHOOK_SECRET` | HMAC secret для Plane webhook |
|
||||
| `ORCH_GITEA_TOKEN` | API token для Gitea |
|
||||
| `ORCH_PLANE_API_TOKEN` | API token для Plane |
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
```bash
|
||||
# Логи Orchestrator
|
||||
docker logs orchestrator --tail 50 2>&1 | grep -i "webhook\|signature\|401"
|
||||
|
||||
# События в БД
|
||||
docker exec orchestrator python3 -c "
|
||||
import sqlite3
|
||||
conn = sqlite3.connect('/app/data/orchestrator.db')
|
||||
for r in conn.execute('SELECT id, source, event_type, timestamp FROM events ORDER BY id DESC LIMIT 10').fetchall():
|
||||
print(r)
|
||||
"
|
||||
|
||||
# Gitea webhook delivery history
|
||||
# Gitea UI → Settings → Webhooks → click webhook → Recent Deliveries
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
*Создано: 2026-05-21 | Автор: Dev-агент*
|
||||
85
docs/operations/STAGING.md
Normal file
85
docs/operations/STAGING.md
Normal file
@@ -0,0 +1,85 @@
|
||||
# Staging Environment (ORCH-31)
|
||||
|
||||
Orchestrator supports a permanent **staging instance** running on port **8501** with a
|
||||
fully-isolated SQLite database. The staging instance shares the same codebase and
|
||||
Dockerfile as production but is started under the `staging` Docker Compose profile so it
|
||||
**never starts accidentally** during a normal `docker compose up -d`.
|
||||
|
||||
## Architecture
|
||||
|
||||
| | Production | Staging |
|
||||
|---|---|---|
|
||||
| Port | 8500 | 8501 |
|
||||
| Container name | `orchestrator` | `orchestrator-staging` |
|
||||
| DB (host path) | `./data/orchestrator.db` | `./data/staging/orchestrator.db` |
|
||||
| DB (container path) | `/app/data/orchestrator.db` | `/app/data/orchestrator.db` |
|
||||
| env file | `.env` | `.env.staging` |
|
||||
| Compose profile | *(default)* | `staging` |
|
||||
|
||||
DB isolation is achieved via a separate volume mount (`./data/staging:/app/data`), not by
|
||||
changing `ORCH_DB_PATH` — the container path stays identical while the host path is a
|
||||
different directory.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. **`.env.staging`** — create from the template (see below). This file is **not committed**
|
||||
to the repo (it contains secrets). Copy and fill in values before first start.
|
||||
2. **`./data/staging/`** directory — created automatically on first container start.
|
||||
|
||||
### Create `.env.staging`
|
||||
|
||||
```bash
|
||||
cd /home/slin/repos/orchestrator
|
||||
cp .env.staging.example .env.staging
|
||||
# Edit .env.staging — fill in real tokens / secrets.
|
||||
# At Stage 1 (ORCH-31) you can reuse prod values; sandbox Plane project
|
||||
# and isolated Gitea webhook will be wired in ORCH-32.
|
||||
nano .env.staging
|
||||
```
|
||||
|
||||
## Starting Staging
|
||||
|
||||
```bash
|
||||
cd /home/slin/repos/orchestrator
|
||||
docker compose --profile staging up -d orchestrator-staging
|
||||
```
|
||||
|
||||
Check it is running:
|
||||
|
||||
```bash
|
||||
docker ps | grep orchestrator-staging
|
||||
curl -s http://localhost:8501/health | python3 -m json.tool
|
||||
```
|
||||
|
||||
## Stopping Staging
|
||||
|
||||
```bash
|
||||
docker compose --profile staging stop orchestrator-staging
|
||||
# or remove the container entirely:
|
||||
docker compose --profile staging down orchestrator-staging
|
||||
```
|
||||
|
||||
## Normal `up -d` does NOT start staging
|
||||
|
||||
```bash
|
||||
# This starts ONLY the prod orchestrator (port 8500). Staging is NOT affected.
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
The `profiles: [staging]` directive in `docker-compose.yml` ensures staging is
|
||||
completely invisible to commands that do not pass `--profile staging`.
|
||||
|
||||
## Logs
|
||||
|
||||
```bash
|
||||
docker logs -f orchestrator-staging
|
||||
```
|
||||
|
||||
## Roadmap
|
||||
|
||||
| Task | Description |
|
||||
|---|---|
|
||||
| **ORCH-31** *(this PR)* | Infra: compose service, .env template, gitignore, docs |
|
||||
| **ORCH-32** | Sandbox: isolated Plane project + Gitea repo for staging |
|
||||
| **ORCH-33** | Test suite running against staging endpoint |
|
||||
| **ORCH-34** | Deploy hook: promote `orchestrator:candidate` image to staging |
|
||||
136
docs/operations/STAGING_CHECK.md
Normal file
136
docs/operations/STAGING_CHECK.md
Normal file
@@ -0,0 +1,136 @@
|
||||
# STAGING_CHECK.md — Инструкция по запуску staging check suite (ORCH-33)
|
||||
|
||||
## Что это
|
||||
|
||||
`scripts/staging_check.py` — самостоятельный скрипт проверки **живого** staging-стенда orchestrator (порт 8501). Не unit-тесты — реальные HTTP-вызовы против работающих сервисов.
|
||||
|
||||
Три блока проверок:
|
||||
|
||||
| Блок | Название | Что проверяет |
|
||||
|------|----------|---------------|
|
||||
| A | SMOKE | `/health`, `/queue`, `ORCH_STAGING=true` |
|
||||
| B | ACCESS | Plane sandbox (R), Gitea sandbox (R+push), реестр проектов |
|
||||
| C | E2E | Создать задачу → триггер конвейера → ветка + коммент → cleanup |
|
||||
|
||||
Exit code: **0** = все PASS, **non-zero** = есть FAIL.
|
||||
|
||||
---
|
||||
|
||||
## Требования к окружению
|
||||
|
||||
Скрипт читает токены/URL из env (те же переменные, что использует orchestrator):
|
||||
|
||||
| Переменная | Описание |
|
||||
|-----------|----------|
|
||||
| `ORCH_STAGING` | Должна быть `true` — защита от случайного запуска на проде |
|
||||
| `ORCH_PLANE_API_TOKEN` | Plane API token (`X-API-Key`) |
|
||||
| `ORCH_PLANE_API_URL` | Plane base URL **без** `/api/v1` (скрипт добавляет сам) |
|
||||
| `ORCH_PLANE_WORKSPACE_SLUG` | Workspace slug (`ag_proj`) |
|
||||
| `ORCH_GITEA_TOKEN` | Gitea token (`Authorization: token …`) |
|
||||
| `ORCH_GITEA_URL` | Gitea base URL (`http://localhost:3000`) |
|
||||
| `ORCH_PLANE_WEBHOOK_SECRET` | HMAC-секрет для подписи `/webhook/plane` (если пустой — без подписи) |
|
||||
|
||||
Все эти переменные **уже есть** внутри контейнера `orchestrator-staging`.
|
||||
|
||||
---
|
||||
|
||||
## Способы запуска
|
||||
|
||||
### 1. Внутри контейнера (рекомендуемый)
|
||||
|
||||
```bash
|
||||
docker exec orchestrator-staging \
|
||||
python3 /repos/orchestrator/scripts/staging_check.py --mode stub
|
||||
```
|
||||
|
||||
### 2. С хоста (если есть токены в env)
|
||||
|
||||
```bash
|
||||
export ORCH_STAGING=true
|
||||
export ORCH_PLANE_API_TOKEN=...
|
||||
# ... остальные переменные ...
|
||||
|
||||
python3 scripts/staging_check.py \
|
||||
--base-url http://localhost:8501 \
|
||||
--mode stub
|
||||
```
|
||||
|
||||
### 3. Из docker exec с передачей URL
|
||||
|
||||
```bash
|
||||
docker exec orchestrator-staging \
|
||||
python3 /repos/orchestrator/scripts/staging_check.py \
|
||||
--base-url http://localhost:8501 \
|
||||
--mode stub
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Режимы (`--mode`)
|
||||
|
||||
| Режим | Описание | Скорость |
|
||||
|-------|----------|----------|
|
||||
| `stub` (дефолт) | Проверяет **ранние артефакты** конвейера: ветка + QG-0-коммент. Создаются ДО запуска Claude CLI → быстро, детерминированно, без расхода LLM-кредитов. | ~30-90 сек |
|
||||
| `full-real` | Дополнительно ждёт реального завершения аналитика. Долго, расходует LLM-кредиты. | 5-15+ мин |
|
||||
|
||||
**Текущий дефолт: `stub`** — достаточен для проверки работоспособности стенда.
|
||||
|
||||
---
|
||||
|
||||
## Что проверяет блок C (E2E) и почему это безопасно
|
||||
|
||||
Порядок `start_pipeline` в коде orchestrator:
|
||||
1. Resolve проекта из реестра
|
||||
2. Получить name/description из Plane API (если в webhook пустые)
|
||||
3. **QG-0 гейт** (name ≥ 5 симв, description ≥ 20 симв)
|
||||
4. **Создать work_item_id + ветку в Gitea + начальные доки**
|
||||
5. **Записать строку задачи в БД**
|
||||
6. Поставить аналитика в очередь (вот тут Claude CLI)
|
||||
|
||||
Блок C проверяет **шаги 4-5**, аналитика (шаг 6) **не ждёт**.
|
||||
Тест-задача создаётся ТОЛЬКО в **SANDBOX** (`project_id 8c5a3025-...`),
|
||||
ветка создаётся ТОЛЬКО в **orchestrator-sandbox**.
|
||||
|
||||
### CLEANUP (обязателен)
|
||||
|
||||
`try/finally` гарантирует удаление тестовых артефактов:
|
||||
- Удаляет ветку из `orchestrator-sandbox`
|
||||
- Удаляет задачу из Plane SANDBOX
|
||||
|
||||
Cleanup отрабатывает даже при падении e2e.
|
||||
|
||||
---
|
||||
|
||||
## Принцип HMAC-подписи
|
||||
|
||||
Скрипт читает `ORCH_PLANE_WEBHOOK_SECRET` из env и формирует подпись:
|
||||
```python
|
||||
hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
|
||||
```
|
||||
Передаёт как заголовок `X-Plane-Signature`. Алгоритм совпадает с `verify_plane_signature` в `src/webhooks/plane.py`.
|
||||
|
||||
---
|
||||
|
||||
## Изолированность от прода
|
||||
|
||||
| Проверка | Гарантия |
|
||||
|---------|---------|
|
||||
| A3 `ORCH_STAGING=true` | При false — abort до деструктивных блоков |
|
||||
| B6 Реестр без боевых | ET/ORCH project_id absent в `known_plane_project_ids()` |
|
||||
| C: only SANDBOX project_id | Webhook payload указывает только `8c5a3025-...` |
|
||||
| C: only orchestrator-sandbox repo | Gitea operations на `admin/orchestrator-sandbox` |
|
||||
| C: cleanup в finally | Артефакты удаляются даже при ошибке |
|
||||
|
||||
---
|
||||
|
||||
## Добавление в деплой-хук
|
||||
|
||||
```bash
|
||||
# В deploy.sh, после docker-compose up -d orchestrator-staging
|
||||
docker exec orchestrator-staging \
|
||||
python3 /repos/orchestrator/scripts/staging_check.py --mode stub
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "Staging check FAILED — rolling back"
|
||||
exit 1
|
||||
fi
|
||||
```
|
||||
Reference in New Issue
Block a user