Compare commits
172
Commits
73d0003281
...
v1.12.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9639a03bfe | ||
|
|
48c10b7436 | ||
|
|
4db6438245 | ||
|
|
fb108ec5ab | ||
|
|
a1ada06a76 | ||
|
|
b5ed47902c | ||
|
|
8a19c2a3f4 | ||
|
|
1c0d78b552 | ||
|
|
e0a912a693 | ||
|
|
9740a34fdc | ||
|
|
6fa265a246 | ||
|
|
b8170c4204 | ||
|
|
c6e13bb86b | ||
|
|
2aecbf96fd | ||
|
|
ec65249bf1 | ||
|
|
6329a4df27 | ||
|
|
880d77810a | ||
|
|
8ebce28e34 | ||
|
|
dd7d43c2c2 | ||
|
|
a8c5e9701f | ||
|
|
be3d73f374 | ||
|
|
5fca165c69 | ||
|
|
293115e0e1 | ||
|
|
6d2051f813 | ||
|
|
b51a9ae3b3 | ||
|
|
4d4cd2301f | ||
|
|
d687881eaa | ||
|
|
87e756f34f | ||
|
|
27864fad58 | ||
|
|
dc5e777d07 | ||
|
|
23910c3393 | ||
|
|
0e90bbee4e | ||
|
|
55bc87cbc4 | ||
|
|
e68f034966 | ||
|
|
e06ee880b2 | ||
|
|
33fe8fdd18 | ||
|
|
6fa693156d | ||
|
|
5858d0889e | ||
|
|
bfe20c1fe0 | ||
|
|
c66cc9317d | ||
|
|
9ea4a68ccf | ||
|
|
8204105fd6 | ||
|
|
0c11ecfa48 | ||
|
|
ab8660ac42 | ||
|
|
ce747673fd | ||
|
|
e558570967 | ||
|
|
b6b081b04f | ||
|
|
13b4c20148 | ||
|
|
700d415422 | ||
|
|
6ca34b9008 | ||
|
|
bb334b10f5 | ||
|
|
4c23232c4e | ||
|
|
c263fd5c7e | ||
|
|
6bee5adc34 | ||
|
|
64516c316d | ||
|
|
ea65451160 | ||
|
|
250cdea35d | ||
|
|
1dd713514c | ||
|
|
aff27e8f7b | ||
|
|
07b97bddc1 | ||
|
|
34ecc5c235 | ||
|
|
a536a2d5eb | ||
|
|
765a8052da | ||
|
|
5e59a1c334 | ||
|
|
92f6de8695 | ||
|
|
87309cfcec | ||
|
|
1f9930d467 | ||
|
|
9808aca44f | ||
|
|
3a3056ba76 | ||
|
|
57dcf306f3 | ||
|
|
b992301c99 | ||
|
|
77a2cfd426 | ||
|
|
ac635e91eb | ||
|
|
2d78c8156f | ||
|
|
00a2a44630 | ||
|
|
35ed79bdd6 | ||
|
|
0cb5a7d4cb | ||
|
|
fefadac1bf | ||
|
|
7d52a4af63 | ||
|
|
9ab7de65ce | ||
|
|
6025f383f1 | ||
|
|
27e01d010f | ||
|
|
b5061a58d9 | ||
|
|
80229b33fc | ||
|
|
7a2b015b12 | ||
|
|
ee364c8b6d | ||
|
|
1a61ae2d71 | ||
|
|
458a885868 | ||
|
|
1e13ef9e70 | ||
|
|
47764345f6 | ||
|
|
8a50ba44b3 | ||
|
|
6107c3eb87 | ||
|
|
3b17228ef2 | ||
|
|
e700f90c47 | ||
|
|
1765ab89e7 | ||
|
|
b99fc179ab | ||
|
|
1f85654653 | ||
|
|
05ec176c7a | ||
|
|
25374a6919 | ||
|
|
dc1f4a59b0 | ||
|
|
ae9fbe30b4 | ||
|
|
9f021289c0 | ||
|
|
40c8a8d38a | ||
|
|
d91667f698 | ||
|
|
1386b63db2 | ||
|
|
4f50350990 | ||
|
|
10e2415cfa | ||
|
|
2260ecf74a | ||
|
|
6d0e214655 | ||
|
|
f6b94a44d0 | ||
|
|
39ba976454 | ||
|
|
9163aeca1e | ||
|
|
6c8e7c55ad | ||
|
|
c811c43bbc | ||
|
|
b7a8aab2e8 | ||
|
|
00bd03735a | ||
|
|
4acd6857c9 | ||
|
|
1e77e1a2b8 | ||
|
|
f877ec89a7 | ||
|
|
2da6d49368 | ||
|
|
53fd527a6d | ||
|
|
e1c4cbce93 | ||
|
|
4aaaa30b1b | ||
|
|
d83efe24ef | ||
|
|
149fb0a18c | ||
|
|
b140dcbcf2 | ||
|
|
b541794d84 | ||
|
|
0ca5542f6b | ||
|
|
6a7284245f | ||
|
|
67ce135b46 | ||
|
|
88226f6dd9 | ||
|
|
57c09acb3d | ||
|
|
97908b50c8 | ||
|
|
9f0b1281f2 | ||
|
|
1c5a9c91bb | ||
|
|
0428b83eb5 | ||
|
|
e816d175ea | ||
|
|
bae2d68803 | ||
|
|
233f29b437 | ||
|
|
4ba5b03f0b | ||
|
|
655d7507e5 | ||
|
|
05bc5c435e | ||
|
|
c48cc4e2d4 | ||
|
|
678bd27085 | ||
|
|
42d956d109 | ||
|
|
e20c9f3113 | ||
|
|
a2cbfacd45 | ||
|
|
482eeb122d | ||
|
|
dc5e20e9b2 | ||
|
|
20e674c1f2 | ||
|
|
07f2ce562e | ||
|
|
0b3ceaa7b8 | ||
|
|
e2002ba33d | ||
|
|
133ea93e83 | ||
|
|
6266a39aed | ||
|
|
62bf987a19 | ||
|
|
431c6a90f1 | ||
|
|
be8e7b5742 | ||
|
|
c958d5af0d | ||
|
|
80965adc0c | ||
|
|
3e8543177e | ||
|
|
80f3a8d105 | ||
|
|
d92a06c9c8 | ||
|
|
399622cc70 | ||
|
|
94a4c6acd4 | ||
|
|
e1aaa18377 | ||
|
|
1969a00151 | ||
|
|
693227163a | ||
|
|
4a860a088e | ||
|
|
d4282c270b | ||
|
|
b70a643016 | ||
|
|
1db6b5b7b2 |
No files matched your search
@@ -0,0 +1,37 @@
|
||||
# Сгенерировать commit message (EvoBGP)
|
||||
|
||||
Сгенерируй сообщение коммита для **текущих staged-изменений**. Не выполняй `git commit`, если пользователь явно не просил закоммитить.
|
||||
|
||||
## Обязательный workflow (MUST)
|
||||
|
||||
1. Прочитай скилл [`.cursor/skills/commit-message/SKILL.md`](../skills/commit-message/SKILL.md).
|
||||
2. Следуй правилу [`.cursor/rules/conventional-commits.mdc`](../rules/conventional-commits.mdc).
|
||||
3. **Первым вызовом Shell** из корня репозитория:
|
||||
|
||||
```powershell
|
||||
powershell -NoProfile -File scripts/commit/staged-context.ps1
|
||||
```
|
||||
|
||||
4. Строй текст **только** по JSON stdout (`groups`, `stat`, `diff_excerpt`). Exit `1` → index пуст, сообщи пользователю.
|
||||
5. **Запрещено** обходить скрипт через один `git diff --cached`.
|
||||
|
||||
## Формат вывода
|
||||
|
||||
Для каждого коммита (при auto-split — по одному блоку):
|
||||
|
||||
```
|
||||
<type>(<scope>): <summary in English>
|
||||
|
||||
<тело на русском>
|
||||
```
|
||||
|
||||
Плюс пояснение (RU): semver impact (`minor`|`patch`|`none`|`major`), почему выбран type, был ли split.
|
||||
|
||||
## Semver (кратко)
|
||||
|
||||
- Новая пользовательская возможность → `feat` (minor)
|
||||
- Починка ожидаемого поведения / баг → `fix` (patch)
|
||||
- Follow-up баги после недавнего `feat` в том же scope → **`fix`**, не `feat`
|
||||
- Только перестройка без нового поведения → `refactor` (patch, без новых функций)
|
||||
|
||||
Заголовок — EN, императив, ≤72 символов. Тело — RU.
|
||||
@@ -0,0 +1,180 @@
|
||||
---
|
||||
description: >-
|
||||
Conventional Commits EvoBGP. Триггеры commit/коммит/закоммить/staged/commit message —
|
||||
ОБЯЗАТЕЛЬНО сначала Shell scripts/commit/staged-context.ps1, скилл commit-message.
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Conventional Commits (EvoBGP)
|
||||
|
||||
Полное описание релизного пайплайна: [docs/releasing.md](../../docs/releasing.md).
|
||||
|
||||
## Триггеры (применить правило + скилл)
|
||||
|
||||
Любой запрос на коммит или сообщение коммита: `commit`, `коммит`, `закоммить`, `git commit`, `commit message`, `conventional commit`, `staged`, «сгенерируй коммит», **`/commit-message`** — в т.ч. если это указано в плане или [AGENTS.md](../../AGENTS.md).
|
||||
|
||||
### Не путать с кнопкой ✨ в Source Control
|
||||
|
||||
Команда **`cursor.generateGitCommitMessage`** (sparkle в поле commit message) **не** читает Rules, Skills и `staged-context.ps1` — только staged diff и история коммитов ([ограничение Cursor](https://forum.cursor.com/t/how-to-set-prompt-for-generate-commit-message/148606)).
|
||||
|
||||
**Замена для EvoBGP:** Agent → `/commit-message` или команда [`.cursor/commands/commit-message.md`](../commands/commit-message.md).
|
||||
|
||||
## Обязательный запуск скрипта (MUST)
|
||||
|
||||
1. Прочитать скилл [`.cursor/skills/commit-message/SKILL.md`](../skills/commit-message/SKILL.md).
|
||||
2. **Первым действием** выполнить Shell (из корня репо):
|
||||
|
||||
```powershell
|
||||
powershell -NoProfile -File scripts/commit/staged-context.ps1
|
||||
```
|
||||
|
||||
3. Сообщение коммита строить **только** по JSON из stdout скрипта (`groups`, `diff_excerpt`, `stat`).
|
||||
4. **Запрещено** генерировать commit message без успешного (exit 0) запуска скрипта; не заменять скрипт одним `git diff --cached`.
|
||||
|
||||
## Формат (строго)
|
||||
|
||||
```
|
||||
<type>(<scope>): <short summary in English>
|
||||
|
||||
<тело на русском: что изменено и зачем>
|
||||
```
|
||||
|
||||
- **Заголовок** — только английский; императив, без точки в конце; ≤72 символов.
|
||||
- **Тело** — только русский; полные предложения; пустая строка после заголовка.
|
||||
- Запрещены vague-сообщения: `fix bug`, `update code`, `wip`, `misc`.
|
||||
|
||||
## Типы (semantic-release)
|
||||
|
||||
| type | Когда | Версия |
|
||||
|------|--------|--------|
|
||||
| `feat` | **новая** пользовательская возможность (раньше нельзя было) | minor |
|
||||
| `fix` | восстановление **ожидаемого** поведения; баг, регрессия, падение UI | patch |
|
||||
| `perf` | ускорение без смены API | patch |
|
||||
| `refactor` | реструктуризация **без** новой возможности и **без** исправления бага | patch |
|
||||
| `docs` | только документация | — |
|
||||
| `test` | тесты | — |
|
||||
| `ci` | CI/CD (`.gitea/`, workflows); правки, из‑за которых нужны новые образы | patch |
|
||||
| `chore` | обслуживание, deps, `.cursor/` | — |
|
||||
|
||||
### Выбор type: semver, а не «красивые слова»
|
||||
|
||||
**Главный вопрос:** что изменится для пользователя после релиза?
|
||||
|
||||
1. Появилось **новое** действие / экран / API / настройка, которых не было → `feat`
|
||||
2. То, что **должно было работать**, не работало (кнопки, диалоги, сохранение, 500) → `fix`
|
||||
3. Только перестройка кода или UI на другой паттерн, поведение для пользователя то же → `refactor` (patch, без новых функций)
|
||||
4. Ускорение без изменения контракта → `perf`
|
||||
|
||||
**Не путать с формулировкой diff:**
|
||||
|
||||
| В diff / задаче часто пишут | Неверный type | Верный type, если… |
|
||||
|-----------------------------|---------------|---------------------|
|
||||
| enhance, improve, polish UI | `feat` | …только чиним сломанное после прошлого PR → `fix` |
|
||||
| refactor pages, unify tables | `feat` | …новой возможности нет, лишь перенос на AppDataTable → `refactor` |
|
||||
| follow-up после feat(web) | `feat` | …исправляем баги того же экрана → `fix` |
|
||||
|
||||
**Follow-up rule:** коммит сразу после `feat` в той же области, который **не добавляет** новую возможность, а устраняет дефект (effect loop, не открывается dialog, confirm не срабатывает) — **`fix`**, не `feat`.
|
||||
|
||||
**Split при смешанном diff:** новая страница/flow → `feat`; отдельным коммитом правки багов → `fix`. Не объединять в один `feat`.
|
||||
|
||||
**Breaking changes** — только `feat!` / `fix!` / `BREAKING CHANGE:` когда пользователь **обязан** менять конфиг, API или привычный workflow.
|
||||
|
||||
### Обязательно в пояснении агенту
|
||||
|
||||
При каждом предложении коммита указать:
|
||||
|
||||
- **Semver impact:** `minor` | `patch` | `none` | `major`
|
||||
- **Почему не другой type** (одно предложение), если diff большой или формулировка двусмысленная
|
||||
|
||||
Пример неправильно / правильно:
|
||||
|
||||
```
|
||||
# Плохо — patch-фикс, minor-bump
|
||||
feat(web): enhance module entry dialogs and selection handling
|
||||
|
||||
# Хорошо
|
||||
fix(web): stop effect loop breaking module action buttons
|
||||
|
||||
Исправлен effect_update_depth_exceeded и bind:open у Dialog; кнопки редактирования/удаления снова работают.
|
||||
```
|
||||
|
||||
```
|
||||
# Плохо — рефакторинг без новой фичи
|
||||
feat(web): migrate modules list to AppDataTable
|
||||
|
||||
# Хорошо — если не было нового user-facing
|
||||
refactor(web): migrate modules list to AppDataTable
|
||||
|
||||
Единый паттерн таблиц; поведение списка модулей без изменений. Semver: patch.
|
||||
```
|
||||
|
||||
```
|
||||
# Хорошо feat — действительно новое
|
||||
feat(web): add module create dialog on /modules
|
||||
|
||||
Диалог создания модуля с POST /v1/modules; раньше создание было только через API.
|
||||
```
|
||||
|
||||
## Breaking changes
|
||||
|
||||
- Заголовок: `feat!` / `fix!` **или** в теле строка `BREAKING CHANGE:` (на английском ключевое слово) + описание impact **на русском**.
|
||||
|
||||
## Scope (EvoBGP)
|
||||
|
||||
Выбирать по доминирующему пути из staged diff:
|
||||
|
||||
| Префикс | scope |
|
||||
|---------|-------|
|
||||
| `internal/httpapi/` | `httpapi` |
|
||||
| `internal/store/`, `internal/repository/`, `internal/db/` | `store` |
|
||||
| `internal/jobs/` | `jobs` |
|
||||
| `internal/pipeline/` | `pipeline` |
|
||||
| `internal/birdfmt/` | `birdfmt` |
|
||||
| `internal/birddeploy/` | `birddeploy` |
|
||||
| `internal/bundle/`, `internal/signing/` | `bundle` |
|
||||
| `cmd/` | `cmd` |
|
||||
| `web/` | `web` |
|
||||
| `docs/openapi.yaml`, `redocly.yaml` | `openapi` |
|
||||
| `docs/` (остальное) | `docs` |
|
||||
| `migrations/` | `db` |
|
||||
| `.gitea/` | `ci` |
|
||||
| `deploy/` | `deploy` |
|
||||
| `.cursor/` | `chore` |
|
||||
| прочее в корне | `chore` |
|
||||
|
||||
**Запрещено:** несколько scope через запятую (`refactor(web, httpapi): …`) — semantic-release не распознает `type`, релиз не будет (см. [docs/releasing.md](../../docs/releasing.md)).
|
||||
|
||||
`type` определять по **содержимому diff**, не только по пути.
|
||||
|
||||
## Multi-change
|
||||
|
||||
- Несвязанные области → **отдельные коммиты** (auto-split по скиллу).
|
||||
- Одна логическая фича через несколько scope (OpenAPI + httpapi + web) → **один** коммит, scope по главной области.
|
||||
|
||||
## Обязательный вывод агенту
|
||||
|
||||
Для каждого коммита:
|
||||
|
||||
**1. Готовое сообщение** (копировать в `git commit -m` / HEREDOC):
|
||||
|
||||
```
|
||||
<type>(<scope>): <summary>
|
||||
|
||||
<тело RU>
|
||||
```
|
||||
|
||||
**2. Пояснение (RU):** semver impact (`minor`|`patch`|`none`|`major`); почему выбран type; риск/impact; был ли split.
|
||||
|
||||
## Примеры
|
||||
|
||||
```
|
||||
feat(httpapi): add version endpoint and wire web footer
|
||||
|
||||
Добавлен GET /v1/version. В Web UI версия в footer берётся из API вместо захардкоженного значения.
|
||||
```
|
||||
|
||||
```
|
||||
fix(auth): correct token validation edge case
|
||||
|
||||
Исправлена ложная 401 при истёкшем refresh-токене с валидной сессией.
|
||||
```
|
||||
@@ -0,0 +1,244 @@
|
||||
---
|
||||
description: Инженерные правила EvoBGP — Go, API, migrations, общие стандарты
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Engineering Guidelines — EvoBGP
|
||||
|
||||
Специализированные правила: **Web UI** → `.cursor/rules/web-shadcn.mdc`; **BIRD2 / BGP / IP** → `.cursor/rules/networking-bird.mdc`.
|
||||
|
||||
Карта репозитория: `AGENTS.md`, `docs/architecture.md`. HTTP-контракт: `docs/openapi.yaml`.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
**ARCH-01** | MUST | Новая persistence-логика — метод `store.Backend` + реализации в `repository` и `store.Memory`; SQL не в `httpapi`.
|
||||
*Rationale:* единая абстракция данных.
|
||||
*Проверка:* CI `scripts/lint-httpapi.sh`; grep SQL в `internal/httpapi` — отсутствие.
|
||||
|
||||
**ARCH-02** | MUST | HTTP-маршруты только в `internal/httpapi`; регистрация через `http.ServeMux` с паттернами `METHOD /v1/...`.
|
||||
*Rationale:* один слой REST.
|
||||
*Проверка:* маршруты только в `routes.go`, `routes_crud.go`.
|
||||
|
||||
**ARCH-03** | MUST | Долгие операции (refresh, apply, rollback) — `jobs.Registry`; ответ `202` + `job_id` где задано OpenAPI.
|
||||
*Rationale:* не блокировать HTTP worker.
|
||||
*Проверка:* OpenAPI + handlers.
|
||||
|
||||
**ARCH-04** | MUST | Кросс-процессные воркеры — HTTP к API или общая БД; не shared memory (кроме `evobgp-all`).
|
||||
*Rationale:* `jobs.Registry` in-process only.
|
||||
*Проверка:* `docs/architecture.md`; review.
|
||||
|
||||
**ARCH-05** | MUST | `birdfmt` не импортирует `httpapi` / `store`.
|
||||
*Rationale:* направление зависимостей вниз.
|
||||
*Проверка:* `go list -deps` / review imports.
|
||||
|
||||
**ARCH-06** | MUST | Точки входа `cmd/*` — тонкий `main`: config, wiring, signal/shutdown; без бизнес-логики.
|
||||
*Rationale:* тестируемость `internal/`.
|
||||
*Проверка:* review `main.go`.
|
||||
|
||||
**ARCH-07** | MUST | Инициализация store + jobs для API и воркеров — `httpapi.BootstrapWorkers`.
|
||||
*Rationale:* единый wiring.
|
||||
*Проверка:* `bootstrap.go`.
|
||||
|
||||
**ARCH-08** | MUST | Ingest+render префиксов — `internal/pipeline`; генерация BIRD-текста — `internal/birdfmt`.
|
||||
*Rationale:* разделение data plane / control plane.
|
||||
*Проверка:* review пакетов.
|
||||
|
||||
**ARCH-09** | NEVER | Прямой доступ handler'ов к `pgxpool` для CRUD; только `store.Backend`.
|
||||
*Rationale:* абстракция бэкенда.
|
||||
*Проверка:* review `httpapi`.
|
||||
|
||||
**ARCH-10** | MUST | Подпись бандлов — `internal/bundle` + `internal/signing`; не дублировать crypto в handlers.
|
||||
*Rationale:* единая криптография артефактов.
|
||||
*Проверка:* review.
|
||||
|
||||
---
|
||||
|
||||
## Code Style
|
||||
|
||||
**STYLE-01** | MUST | Go-код после `gofmt`; перед PR — `go vet ./...`. Агент после правок Go: `gofmt -w` на изменённых файлах + `golangci-lint run` (или `scripts/lint-go.*`) до exit 0.
|
||||
*Rationale:* CI job `go` включает golangci-lint (gofmt).
|
||||
*Проверка:* CI job `go`; `.cursor/rules/engineering.mdc` STYLE-01.
|
||||
|
||||
**STYLE-02** | MUST | Экспортируемые типы/функции публичных пакетов — godoc-комментарий.
|
||||
*Rationale:* навигация по API пакетов.
|
||||
*Проверка:* review.
|
||||
|
||||
**STYLE-03** | NEVER | `panic` в `internal/*` вне `init` и тестов.
|
||||
*Rationale:* предсказуемые ошибки.
|
||||
*Проверка:* grep `panic(`.
|
||||
|
||||
**STYLE-04** | MUST | Ошибки пакетов с префиксом (`birdfmt:`, `db:`, `httpapi:`) и `%w` при оборачивании.
|
||||
*Rationale:* трассировка.
|
||||
*Проверка:* review.
|
||||
|
||||
**STYLE-05** | MUST | HTTP-ошибки — `writeProblem` / `writeJSON` (`application/problem+json` для 4xx/5xx).
|
||||
*Rationale:* RFC 9457, OpenAPI.
|
||||
*Проверка:* `problem.go`; CI `scripts/lint-httpapi.sh` (5xx и 4xx store/cdn/csv).
|
||||
|
||||
**STYLE-06** | MUST | JSON полей HTTP DTO согласованы с `docs/openapi.yaml`.
|
||||
*Rationale:* контракт API.
|
||||
*Проверка:* OpenAPI diff + review.
|
||||
|
||||
---
|
||||
|
||||
## Dependency Management
|
||||
|
||||
**DEP-01** | MUST | Go-зависимости — через `go get` / `go.mod`; версия Go как в `go.mod` и CI (1.24).
|
||||
*Проверка:* `go.mod`, `.gitea/workflows/ci.yaml`.
|
||||
|
||||
**DEP-02** | NEVER | Vendor-копирование без явного решения в репозитории.
|
||||
*Проверка:* review.
|
||||
|
||||
**DEP-03** | MUST | Миграции схемы — пары `.up.sql`/`.down.sql` для **postgres** и **sqlite**, синхронная нумерация.
|
||||
*Проверка:* `migrations/postgres/`, `migrations/sqlite/`.
|
||||
|
||||
**DEP-04** | MUST | Web UI-библиотеки — только экосистема shadcn-svelte/bits-ui (см. `web-shadcn.mdc`).
|
||||
*Проверка:* `web/package.json` review.
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
**ERR-01** | MUST | HTTP 5xx — без сырого `err.Error()` клиенту; detail через `writeProblem`.
|
||||
*Проверка:* review handlers.
|
||||
|
||||
**ERR-02** | MUST | Публичные функции I/O — `(T, error)`; `errors.Is`/`errors.As` для sentinel.
|
||||
*Проверка:* review.
|
||||
|
||||
**ERR-03** | MUST | `context.Context` — первый аргумент для I/O; таймауты на внешние HTTP (CDN, DoH, RIPEstat).
|
||||
*Проверка:* `pipeline`, `bootstrap.go`.
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
**TEST-01** | MUST | Перед PR: `go test ./... -race -count=1`.
|
||||
*Проверка:* CI job `go`.
|
||||
|
||||
**TEST-02** | MUST | Табличные тесты — эталон для `birdfmt`, `pipeline`, `bundle`.
|
||||
*Проверка:* `*_test.go`.
|
||||
|
||||
**TEST-03** | MUST | Новые BIRD-сценарии в `internal/birdfmt/testdata/scenarios/*/bird.conf` + `bird -p`.
|
||||
*Проверка:* CI job `bird2`.
|
||||
|
||||
**TEST-04** | MUST | Изменения `web/` — локально **`npm run check` и `npm run lint`** (обе команды, exit 0); CI job `web` в `.gitea/workflows/ci.yaml`. Агент: при fail lint — `npx prettier --write` затем повтор. Только `check` не заменяет `lint`.
|
||||
*Проверка:* CI job `web`; `.cursor/rules/web-shadcn.mdc` WEB-19.
|
||||
|
||||
**TEST-05** | MUST | Изменения OpenAPI — `npx @redocly/cli lint docs/openapi.yaml`.
|
||||
*Проверка:* CI job `openapi`.
|
||||
|
||||
---
|
||||
|
||||
## Documentation
|
||||
|
||||
**DOC-01** | MUST | Пользовательская документация в `docs/` — на русском.
|
||||
*Проверка:* review.
|
||||
|
||||
**DOC-02** | MUST | Изменение HTTP API: сначала `docs/openapi.yaml`, затем handlers/store, затем `docs/api.md` при необходимости.
|
||||
*Проверка:* PR diff order.
|
||||
|
||||
**DOC-03** | MUST | Расхождение spec/код — явно в `docs/access.md` или description операции OpenAPI.
|
||||
*Проверка:* review (напр. `X-Tenant-Id`).
|
||||
|
||||
**DOC-04** | NEVER | Дублировать длинные фрагменты OpenAPI в комментариях; ссылка на путь/operationId.
|
||||
*Проверка:* review.
|
||||
|
||||
---
|
||||
|
||||
## Naming Conventions
|
||||
|
||||
**NAME-01** | MUST | Бинарники: `cmd/evobgp-<role>/main.go`.
|
||||
*Проверка:* `cmd/`.
|
||||
|
||||
**NAME-02** | MUST | Env-переменные: префикс `EVOBGP_`.
|
||||
*Проверка:* `internal/config`, `docs/access.md`.
|
||||
|
||||
**NAME-03** | MUST | Job kinds — константы в `internal/jobs/worker.go` (`module_refresh`, …).
|
||||
*Проверка:* grep `Kind`.
|
||||
|
||||
**NAME-04** | MUST | ID сущностей — UUID-строки; tenant только из API-ключа (auth context), не из недокументированных заголовков.
|
||||
*Проверка:* `auth.go`, `docs/access.md`.
|
||||
|
||||
---
|
||||
|
||||
## Performance
|
||||
|
||||
**PERF-01** | MUST | Списки API — пагинация `cursor` + `limit`; не unbounded выборки в handlers.
|
||||
*Проверка:* OpenAPI + store methods.
|
||||
|
||||
**PERF-02** | MUST | CDN HTTP — переиспользуемый `http.Client` с таймаутом (45s в bootstrap).
|
||||
*Проверка:* `bootstrap.go`.
|
||||
|
||||
**PERF-03** | MUST | Новые метрики — `internal/observability`, экспорт `/metrics`.
|
||||
*Проверка:* review.
|
||||
|
||||
---
|
||||
|
||||
## Security
|
||||
|
||||
**SEC-01** | NEVER | Секреты, API-ключи, токены в Git.
|
||||
*Проверка:* review; `docs/access.md`.
|
||||
|
||||
**SEC-02** | NEVER | `EVOBGP_DEV_INSECURE=1` в production.
|
||||
*Проверка:* ops review.
|
||||
|
||||
**SEC-03** | MUST | Роль `node` — только node API; CRUD — `403` для `node`.
|
||||
*Проверка:* `auth.go`, handlers.
|
||||
|
||||
**SEC-04** | MUST | apply/rollback/settings — operator (или выше по `roleLevel`).
|
||||
*Проверка:* review handlers.
|
||||
|
||||
**SEC-05** | MUST | Бандл на ноде — `verify-bundle` перед `apply-bundle`.
|
||||
*Проверка:* `docs/access.md`.
|
||||
|
||||
**SEC-06** | MUST | CORS — явный whitelist `EVOBGP_CORS_ORIGINS`.
|
||||
*Проверка:* `cors.go`.
|
||||
|
||||
---
|
||||
|
||||
## Documentation Sync Rules
|
||||
|
||||
| Область | Источник |
|
||||
|---------|----------|
|
||||
| Go / net/http | https://go.dev/doc/ |
|
||||
| pgx v5 | https://pkg.go.dev/github.com/jackc/pgx/v5 |
|
||||
| OpenAPI / problem+json | `docs/openapi.yaml`, RFC 9457 |
|
||||
| Svelte / Kit | https://svelte.dev/docs , https://kit.svelte.dev/docs |
|
||||
| shadcn-svelte | https://shadcn-svelte.com/docs |
|
||||
| BIRD 2 | https://bird.network.cz/?get_doc |
|
||||
| Prometheus Go | https://pkg.go.dev/github.com/prometheus/client_golang |
|
||||
|
||||
**DOC-SYNC-01** | MUST | Новый API библиотеки — сверка версии в `go.mod`/`package.json` с официальной документацией.
|
||||
**DOC-SYNC-02** | NEVER | Устаревшие примеры (Svelte 4 `export let`, deprecated pgx).
|
||||
**DOC-SYNC-03** | MUST | Конфликт docs: **OpenAPI (HTTP)** → **код** → обзорные `docs/`; `.cursor/plans/` не контракт.
|
||||
**DOC-SYNC-04** | MUST | Сомнения по Svelte — Svelte MCP / `npm run check`.
|
||||
**DOC-SYNC-05** | MUST | BIRD — официальная документация BIRD2 + `networking-bird.mdc` + `go test ./internal/birdfmt/...`.
|
||||
|
||||
Приоритет при сомнениях — **официальные источники**, не блоги и не «память модели».
|
||||
|
||||
---
|
||||
|
||||
## Enforcement Strategy
|
||||
|
||||
**CI (Gitea):** OpenAPI lint; `go vet`, `go test -race`, build `cmd/*`; `bird -p` на scenarios; Docker bake на push.
|
||||
|
||||
**Локально перед PR:**
|
||||
|
||||
```powershell
|
||||
go vet ./...
|
||||
go test ./... -race -count=1
|
||||
npx @redocly/cli lint docs/openapi.yaml
|
||||
# web: cd web; npm run check; npm run lint (или scripts/lint-web.ps1)
|
||||
# go fmt/lint: gofmt -w <files>; scripts/lint-go.ps1 (gofmt + vet + golangci-lint)
|
||||
# birdfmt: go test ./internal/birdfmt/... -count=1
|
||||
```
|
||||
|
||||
**CI (Gitea):** job `web` (check + lint); job `go`: `go vet`, `scripts/lint-httpapi.sh` (ARCH-01, ERR-01), `scripts/check-migrations-pair.sh` (DEP-03), `golangci-lint`, `go test -race`, build `cmd/*`.
|
||||
|
||||
**Рекомендуется локально:** `.golangci.yml`; `.pre-commit-config.yaml` (gofmt + prettier web).
|
||||
|
||||
**Только code review:** слои SQL; роли; idempotency; OpenAPI bodies; secrets в compose.
|
||||
|
||||
**Известные ограничения:** `X-Tenant-Id` в OpenAPI не реализован в handlers; `jobs.Registry` не shared между процессами API и отдельными воркерами без HTTP.
|
||||
@@ -0,0 +1,219 @@
|
||||
---
|
||||
description: EvoBGP — BIRD2, BGP policy, IP/CIDR, маршрутизация, валидация конфигов
|
||||
globs:
|
||||
- internal/birdfmt/**
|
||||
- internal/birddeploy/**
|
||||
- internal/pipeline/**
|
||||
- deploy/bird/**
|
||||
- "**/testdata/scenarios/**"
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Networking & Routing Rules
|
||||
|
||||
Общие правила: `.cursor/rules/engineering.mdc`. Пакет BIRD: `internal/birdfmt/doc.go`.
|
||||
|
||||
## Single source of truth
|
||||
|
||||
| Домен | SSOT |
|
||||
|-------|------|
|
||||
| Префиксы для анонса | Модули tenant → materialized snapshot → ревизия (`store`, `pipeline`, `CreateRenderRevision`) |
|
||||
| Текст BIRD-фрагментов | `internal/birdfmt` — только генератор `evobgp_*.conf` |
|
||||
| Каркас `bird.conf` | Operator skeleton + `include` (`StandardIncludeFragments`) |
|
||||
| Параметры BIRD tenant | Global settings: `bird_router_id`, `bird_local_asn`, … (`docs/manual.md`) |
|
||||
| BGP peers | `BGPPeer` + `ParsePeerNeighbor` |
|
||||
|
||||
**BIRD2 docs:** https://bird.network.cz/?get_doc
|
||||
|
||||
---
|
||||
|
||||
## A. BIRD2 Configuration Rules
|
||||
|
||||
**BIRD-01** | MUST | Имена фрагментов — константы `Fragment*` (`evobgp_prefixes_v4.conf`, …); include `bird.d/<name>`.
|
||||
*Rationale:* совместимость deploy.
|
||||
*Проверка:* `layout.go`; `go test ./internal/birdfmt/...`
|
||||
|
||||
**BIRD-02** | MUST | Порядок include: filters v4/v6 → BGP template → prefixes v4/v6 → peers (`StandardIncludeFragments`).
|
||||
*Rationale:* фильтры до ссылок.
|
||||
*Проверка:* scenario `standard_layout`; `bird -p`
|
||||
|
||||
**BIRD-03** | MUST | `bird.conf` (router id, device, direct, includes) отдельно от `bird.d/evobgp_*` (политика, префиксы).
|
||||
*Rationale:* атомарная подмена фрагментов.
|
||||
*Проверка:* review layout.
|
||||
|
||||
**BIRD-04** | MUST | Новая логика фильтрации — функция в `birdfmt` + unit-тест; NEVER дублировать filter-блок в два `.conf` вручную.
|
||||
*Rationale:* DRY v4/v6.
|
||||
*Проверка:* `filter_test.go`; review.
|
||||
|
||||
**BIRD-05** | MUST | Filter: префикс `evobgp_`, суффикс `_v4`/`_v6`; templates `bgp_template` / `bgp_template_v6`.
|
||||
*Проверка:* `bgp.go`, `layout.go`.
|
||||
|
||||
**BIRD-06** | MUST | `router id` — валидный IPv4 dotted-quad (`RenderMainBirdConf`).
|
||||
*Проверка:* `birdfmt` error; `bird -p`
|
||||
|
||||
**BIRD-07** | MUST | Communities — `RouteCommunityAttrs`; синтаксис `((a,b))` в `add()`, не `add(65000,1)`.
|
||||
*Проверка:* `community_bird_test.go`
|
||||
|
||||
**BIRD-08** | SHOULD | Комментарии `#` в preamble; в фрагментах — revision/module id где уместно.
|
||||
*Проверка:* review.
|
||||
|
||||
**BIRD-09** | NEVER | Ручное редактирование `evobgp_*.conf` на ноде без ревизии/бандла в control plane.
|
||||
*Rationale:* drift.
|
||||
*Проверка:* `evobgp-deploy` logs.
|
||||
|
||||
**BIRD-10** | MUST | Новый scenario: `testdata/scenarios/<name>/bird.conf` (+ `bird.d/`) проходит `bird -p`.
|
||||
*Проверка:* CI `bird2`
|
||||
|
||||
**BIRD-11** | MUST | Только BIRD **2.x**, не 1.6.
|
||||
*Проверка:* `bird --version`
|
||||
|
||||
**BIRD-12** | MUST | Apply: staging → `bird -p` → atomic swap → `birdc configure`; NEVER configure без parse check.
|
||||
*Проверка:* `birdctl.go`; `birddeploy` review.
|
||||
|
||||
---
|
||||
|
||||
## B. Routing Policy Rules
|
||||
|
||||
**RTE-01** | MUST | BGP template: `import none` на каждый AFI, если задача явно не добавляет import policy.
|
||||
*Rationale:* deny-by-default.
|
||||
*Проверка:* `bgp.go`
|
||||
|
||||
**RTE-02** | MUST | Export filter завершается `reject;`.
|
||||
*Проверка:* `filter.go`; `filter_export` scenario.
|
||||
|
||||
**RTE-03** | MUST | Анонс только префиксов materialized revision; NEVER static `route` вне pipeline/birdfmt без operator approval.
|
||||
*Проверка:* store snapshot; review.
|
||||
|
||||
**RTE-04** | NEVER | Анонс `0.0.0.0/0`, `::/0`, RFC1918/ULA, loopback, link-local, multicast, reserved без documented exception.
|
||||
*Проверка:* ingest validation; review.
|
||||
|
||||
**RTE-05** | NEVER | Префиксы чужих ASN без авторизации (IRR/RPKI — ops review).
|
||||
*Проверка:* ops review.
|
||||
|
||||
**RTE-06** | MUST | Отдельные export filters IPv4 и IPv6.
|
||||
*Проверка:* `RenderExportFilterIPv4/IPv6`
|
||||
|
||||
**RTE-07** | SHOULD | AS_PATH match — ASN из tenant modules; дедуп `filterUniqueASNs`.
|
||||
*Проверка:* unit tests.
|
||||
|
||||
**RTE-08** | MUST | Peer import/export overrides — расширение `birdfmt`, не ad-hoc в operator `bird.conf`.
|
||||
*Проверка:* review.
|
||||
|
||||
**RTE-09** | SHOULD | hold 90s / keepalive 30s — менять только с обоснованием в settings/docs.
|
||||
*Проверка:* review.
|
||||
|
||||
**RTE-10** | MUST | После apply — post-check `birdc`/метрики (`mergeBirdPostApplyMeta`, `EVOBGP_BIRDC_SOCKET`).
|
||||
*Проверка:* jobs meta; observability poller.
|
||||
|
||||
---
|
||||
|
||||
## C. IP Addressing Rules
|
||||
|
||||
**IP-01** | MUST | CIDR в Go — `netip.Prefix`; строка — `Masked().String()`.
|
||||
*Проверка:* `pipeline/parse.go`
|
||||
|
||||
**IP-02** | MUST | IPv4/IPv6 — отдельные fragments/filters.
|
||||
*Проверка:* `layout.go`
|
||||
|
||||
**IP-03** | MUST | BGP neighbor — `ParsePeerNeighbor`; `/32`/`/128` нормализуются в host addr.
|
||||
*Проверка:* `peer_neighbor_test.go`
|
||||
|
||||
**IP-04** | NEVER | Hardcoded production CIDR вне testdata/fixtures.
|
||||
*Проверка:* grep; review.
|
||||
|
||||
**IP-05** | MUST | Fixtures/docs — TEST-NET (RFC 5737, 3849): `203.0.113.0/24`, `198.51.100.0/24`, `2001:db8::/32`.
|
||||
*Проверка:* scenarios.
|
||||
|
||||
**IP-06** | MUST | Domain→IP: host routes `/32`, `/128` via `ipToHostPrefix`; invalid отбрасывается.
|
||||
*Проверка:* `collect_parallel.go`
|
||||
|
||||
**IP-07** | MUST | IP range entries — валидный CIDR на границе API/store.
|
||||
*Проверка:* httpapi; review.
|
||||
|
||||
**IP-08** | SHOULD | Множество префиксов — без дубликатов; агрегация — policy decision.
|
||||
*Проверка:* snapshot dedup.
|
||||
|
||||
**IP-09** | MUST | `router id`, `local as` — из tenant settings, не hardcode в callers `birdfmt`.
|
||||
*Проверка:* `docs/manual.md`
|
||||
|
||||
**IP-10** | NEVER | Reserved blocks (`0.0.0.0/8`, `127.0.0.0/8`, `169.254.0.0/16`, `224.0.0.0/4`, IPv6 analogs) в materialized prefixes.
|
||||
*Проверка:* review; future validator.
|
||||
|
||||
---
|
||||
|
||||
## D. Internet Compliance
|
||||
|
||||
**COMP-01** | SHOULD | Policy changes — сверка RFC 4271, 4760, 7454 (обзор).
|
||||
*Проверка:* review.
|
||||
|
||||
**COMP-02** | MUST | No excessive deaggregation без need.
|
||||
*Проверка:* review prefix list.
|
||||
|
||||
**COMP-03** | MUST | Standard community 0..65535; large — schema store.
|
||||
*Проверка:* `community_bird_test.go`
|
||||
|
||||
**COMP-04** | NEVER | AS_PATH/MED manipulation без product spec.
|
||||
*Проверка:* review output.
|
||||
|
||||
**COMP-05** | SHOULD | Revision/job meta: source, counts, samples (`revisionLogEntry`).
|
||||
*Проверка:* jobs.
|
||||
|
||||
**COMP-06** | MUST | Node: `evobgp-node verify-bundle` перед apply.
|
||||
*Проверка:* `docs/access.md`
|
||||
|
||||
**COMP-07** | SHOULD | `bird_local_asn` = `local as` в templates/peers.
|
||||
*Проверка:* settings + birdfmt.
|
||||
|
||||
**COMP-08** | NEVER | Default route leak без named `default-originate` policy.
|
||||
*Проверка:* export filter review.
|
||||
|
||||
---
|
||||
|
||||
## Validation & Observability
|
||||
|
||||
**VAL-01** | MUST | Перед деплоем: `bird -c <bird.conf> -p` (main + includes).
|
||||
*Проверка:* CI `bird2`; `ParseCheck`
|
||||
|
||||
**VAL-02** | MUST | Preview ревизии read-only; apply — jobs/apply/bundle only.
|
||||
*Проверка:* OpenAPI + httpapi.
|
||||
|
||||
**VAL-03** | MUST | Изменения birdfmt — `go test ./internal/birdfmt/...`.
|
||||
*Проверка:* CI `go`
|
||||
|
||||
**VAL-04** | SHOULD | Dry-run apply где API поддерживает `dry_run`.
|
||||
*Проверка:* routes.go.
|
||||
|
||||
**VAL-05** | MUST | `/metrics` Prometheus; `EVOBGP_BIRDC_SOCKET` — BGP session poller.
|
||||
*Проверка:* `observability`
|
||||
|
||||
**VAL-06** | MUST | Логировать job_id, revision_id, speaker_id на apply/refresh/rollback.
|
||||
*Проверка:* jobs API.
|
||||
|
||||
**VAL-07** | SHOULD | После apply — `birdc show protocols` / parsers в `birdfmt`.
|
||||
*Проверка:* `protocols.go`
|
||||
|
||||
**VAL-08** | MUST | Мониторить drift: `last_applied_revision_id` vs published (`evobgp-deploy`).
|
||||
*Проверка:* deploy worker.
|
||||
|
||||
---
|
||||
|
||||
## Documentation Sync
|
||||
|
||||
**DOC-SYNC-05** | MUST | BIRD — https://bird.network.cz/?get_doc
|
||||
**DOC-SYNC-08** | MUST | BGP policy — RFC 4271, 4760, 7454 + BIRD docs + `birdfmt`
|
||||
**DOC-SYNC-09** | MUST | CIDR — https://pkg.go.dev/net/netip ; примеры — RFC 5737, 3849
|
||||
|
||||
---
|
||||
|
||||
## Enforcement
|
||||
|
||||
```powershell
|
||||
go test ./internal/birdfmt/... ./internal/pipeline/... -count=1
|
||||
bird -c internal/birdfmt/testdata/scenarios/<name>/bird.conf -p
|
||||
```
|
||||
|
||||
**PR checklist `birdfmt/**`, `pipeline/**`, `deploy/bird/**`:**
|
||||
- [ ] filter + unit-test + `bird -p`
|
||||
- [ ] нет дубли filter logic v4/v6 без общей Go-функции
|
||||
- [ ] префиксы только store/revision path
|
||||
- [ ] `import none` на templates сохранён
|
||||
@@ -0,0 +1,126 @@
|
||||
---
|
||||
description: EvoBGP WebUI — shadcn-svelte, Svelte 5, слои ui/core|patterns|app
|
||||
globs:
|
||||
- web/**
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# Web UI — shadcn-svelte
|
||||
|
||||
**Источник правды:** https://shadcn-svelte.com/docs (не React shadcn/ui, не Legacy Docs).
|
||||
|
||||
Общие правила Go/API: `.cursor/rules/engineering.mdc`. Локальная карта: `web/README.md`.
|
||||
|
||||
## Слои UI
|
||||
|
||||
| Слой | Путь | Назначение |
|
||||
|------|------|------------|
|
||||
| Примитивы | `src/lib/ui/core/` | shadcn-svelte (только CLI `add`) |
|
||||
| Паттерны | `src/lib/ui/patterns/` | FormField, AppDataTable, ConfirmDialog, EmptyState |
|
||||
| App chrome | `src/lib/ui/app/` | Layout, PageHeader, `notify` |
|
||||
| Legacy | `src/lib/components/ui/` | Re-export; **не добавлять новые файлы** |
|
||||
|
||||
Тема: `src/routes/layout.css`, `src/lib/ui/app/tokens.md`. CLI из `web/`: `npx shadcn-svelte@latest add <component> -y -o`.
|
||||
|
||||
---
|
||||
|
||||
## Правила
|
||||
|
||||
**WEB-01** | MUST | Перед новым UI — проверить https://shadcn-svelte.com/docs/components; использовать компонент, не HTML+CSS с нуля.
|
||||
*Rationale:* Open Code + единый дизайн.
|
||||
*Проверка:* review; нет голых `<button class=…>`.
|
||||
|
||||
**WEB-02** | MUST | Отсутствующий примитив — `npx shadcn-svelte@latest add <component> -y -o` → `src/lib/ui/core/`.
|
||||
*Rationale:* Distribution через CLI и `components.json`.
|
||||
*Проверка:* файлы только в `ui/core`.
|
||||
|
||||
**WEB-03** | NEVER | Альтернативные UI-kit'ы (Material, Vuetify, DaisyUI-only без shadcn-примитива).
|
||||
*Проверка:* `package.json` review.
|
||||
|
||||
**WEB-04** | MUST | Комозиция по docs: все sub-компоненты (`DialogHeader`, `TableRow`, `Field`, …).
|
||||
*Проверка:* сверка со страницей компонента в docs.
|
||||
|
||||
**WEB-05** | MUST | Формы — Formsnap + `sveltekit-superforms`; UI в `ui/patterns/form`, не ad-hoc валидация на странице.
|
||||
*Проверка:* https://shadcn-svelte.com/docs/components/form
|
||||
|
||||
**WEB-06** | MUST | Таблицы — Data Table + `@tanstack/table-core`; на страницах — `AppDataTable` из patterns.
|
||||
*Проверка:* https://shadcn-svelte.com/docs/components/data-table
|
||||
|
||||
**WEB-07** | MUST | Toast — Sonner через `notify` из `ui/app/toast.js`.
|
||||
*Проверка:* https://shadcn-svelte.com/docs/components/sonner
|
||||
|
||||
**WEB-08** | MUST | Иконки — `@lucide/svelte` (`components.json` → `iconLibrary: lucide`).
|
||||
*Проверка:* imports.
|
||||
|
||||
**WEB-09** | MUST | Цвета — CSS-переменные `layout.css` и токены `tokens.md`; не hex/rgb на страницах.
|
||||
*Проверка:* grep `#[0-9a-f]{3,6}` в `routes/`.
|
||||
|
||||
**WEB-10** | SHOULD | Кастомизация — правка `ui/core` (Open Code), не `!important` поверх API.
|
||||
*Проверка:* review.
|
||||
|
||||
**WEB-11** | MUST | `routes/**` — композиция `ui/core` + `ui/patterns` + `ui/app`; не копировать целые примитивы shadcn в route.
|
||||
*Проверка:* review.
|
||||
|
||||
**WEB-12** | NEVER | Примеры React shadcn/ui или Svelte 4 Legacy без адаптации под https://shadcn-svelte.com/docs/migration/svelte-5
|
||||
*Проверка:* `npm run check`.
|
||||
|
||||
**WEB-13** | MUST | Реактивность — Svelte 5 runes (`$state`, `$derived`, `$effect`); не `export let` для локального state страниц.
|
||||
*Проверка:* `npm run check`; Svelte MCP.
|
||||
|
||||
**WEB-14** | SHOULD | Нетривиальный UI — прочитать страницу компонента (props, a11y).
|
||||
*Проверка:* PR description.
|
||||
|
||||
**WEB-15** | MUST | Сомнения — https://shadcn-svelte.com/llms.txt , Svelte MCP, `npm run check`.
|
||||
*Проверка:* локально.
|
||||
|
||||
**WEB-19** | MUST | **После любого изменения `web/**`** — перед завершением задачи агент **обязан** выполнить в `web/`:
|
||||
```powershell
|
||||
npm run check
|
||||
npm run lint
|
||||
```
|
||||
Если `npm run lint` падает (Prettier) — **сначала** `npx prettier --write <изменённые файлы>` или `npx prettier --write .`, затем снова `npm run check` и `npm run lint`. Не сдавать PR/ответ, пока обе команды не exit 0.
|
||||
*Rationale:* CI job `web` = `check` + `prettier --check`; `svelte-check` не ловит форматирование.
|
||||
*Проверка:* CI job `web`; pre-commit hook `prettier-web`.
|
||||
|
||||
**WEB-16** | MUST | Подтверждение удаления — `ConfirmDialog` из patterns, не `window.confirm`.
|
||||
*Проверка:* review.
|
||||
|
||||
**WEB-17** | MUST | Пустые списки — `EmptyState` из patterns.
|
||||
*Проверка:* review.
|
||||
|
||||
**WEB-18** | SHOULD | Повторяемая комбинация core (≥2 раза) — вынести в `ui/patterns/`.
|
||||
*Проверка:* review.
|
||||
|
||||
---
|
||||
|
||||
## Documentation Sync (Web)
|
||||
|
||||
**DOC-SYNC-06** | MUST | UI — первично https://shadcn-svelte.com/docs; при конфликте с блогами/Stack Overflow побеждает официальная страница компонента.
|
||||
**DOC-SYNC-07** | MUST | Перед `add` — сверить Installation/Theming с `web/components.json` и `src/routes/layout.css`.
|
||||
|
||||
Tailwind v4: https://shadcn-svelte.com/docs/migration/tailwind-v4
|
||||
|
||||
---
|
||||
|
||||
## Enforcement
|
||||
|
||||
**Обязательный финальный шаг агента при правках `web/**`:** `npm run check` **и** `npm run lint` (см. **WEB-19**). Только `check` недостаточно.
|
||||
|
||||
```powershell
|
||||
cd web
|
||||
npm run check
|
||||
npm run lint
|
||||
# при warn/fail lint:
|
||||
npx prettier --write .
|
||||
npm run check
|
||||
npm run lint
|
||||
```
|
||||
|
||||
**PR checklist `web/**`:**
|
||||
- [ ] `npm run check` — exit 0
|
||||
- [ ] `npm run lint` (prettier --check) — exit 0
|
||||
- [ ] `ui/core` / `ui/patterns`, не дубли примитивов
|
||||
- [ ] Новые примитивы через shadcn CLI
|
||||
- [ ] Ссылка на docs компонента (если новый паттерн)
|
||||
|
||||
**CI:** job `web` — `npm run check` + `npm run lint`.
|
||||
@@ -0,0 +1,143 @@
|
||||
---
|
||||
name: commit-message
|
||||
description: >-
|
||||
ОБЯЗАТЕЛЬНО при commit, коммит, закоммить, commit message, conventional commit,
|
||||
staged, semantic-release, «сгенерируй коммит», git commit, /commit-message: ПЕРВЫМ
|
||||
делом Shell — scripts/commit/staged-context.ps1; затем Conventional Commit (заголовок EN, тело RU).
|
||||
---
|
||||
|
||||
> **Кнопка ✨ Generate commit message в Source Control** не использует этот скилл и Rules.
|
||||
> Эквивалент: Agent Chat → **`/commit-message`** или «сгенерируй коммит по staged».
|
||||
> См. [docs/README.md](../../docs/README.md#сообщения-коммитов-cursor).
|
||||
|
||||
# Commit message (EvoBGP)
|
||||
|
||||
## Когда применять (сразу читать этот скилл)
|
||||
|
||||
Триггеры в промпте пользователя или в плане/AGENTS.md:
|
||||
|
||||
- `commit`, `коммит`, `закоммить`, `commit message`, `conventional commit`
|
||||
- `git commit`, `staged`, `сообщение коммита`, `сгенерируй коммит`
|
||||
- агент собирается выполнить `git commit` или предложить текст коммита
|
||||
|
||||
## Шаг 0 — ОБЯЗАТЕЛЬНО (до любого текста коммита)
|
||||
|
||||
**Первый вызов инструментов** в этой задаче — Shell из корня репозитория:
|
||||
|
||||
```powershell
|
||||
powershell -NoProfile -File scripts/commit/staged-context.ps1
|
||||
```
|
||||
|
||||
| Правило | Деталь |
|
||||
|---------|--------|
|
||||
| **MUST** | Запустить скрипт до генерации заголовка/тела коммита |
|
||||
| **MUST NOT** | Строить сообщение только по `git diff --cached` / `git status` без скрипта |
|
||||
| **MUST NOT** | Пропускать скрипт, даже если diff «и так понятен» |
|
||||
| Exit `1` | Index пуст — сообщить пользователю, **не коммитить** |
|
||||
| Exit `0` | Разобрать JSON stdout: `staged_count`, `groups[]` (`scope`, `files`, `stat`, `diff_excerpt`) |
|
||||
|
||||
Дополнительно: [.cursor/rules/conventional-commits.mdc](../../rules/conventional-commits.mdc).
|
||||
|
||||
## Слияние групп (одна фича)
|
||||
|
||||
Скрипт группирует **только по путям**. Перед split проверьте логическую связность:
|
||||
|
||||
**Объединить в один коммит**, если это одна задача:
|
||||
|
||||
- `docs/openapi.yaml` + `internal/httpapi/` (+ опционально `web/`) — один endpoint/контракт;
|
||||
- `migrations/` + `internal/store/` / `repository/` — одна схема;
|
||||
- правки теста рядом с кодом той же фичи.
|
||||
|
||||
При объединении: один scope (доминирующий пакет, часто `httpapi` или `openapi`), один type, одно тело RU.
|
||||
|
||||
**Auto-split** — если группы **не связаны** (например `web/` + `internal/birdfmt/` без общего смысла): **отдельный коммит на группу**, без вопроса пользователю.
|
||||
|
||||
## Порядок коммитов при split
|
||||
|
||||
1. `openapi`
|
||||
2. `httpapi`, `store`, `jobs`
|
||||
3. `pipeline`, `birdfmt`, `birddeploy`, `bundle`
|
||||
4. `web`
|
||||
5. `ci`, `deploy`, `db`
|
||||
6. `docs`
|
||||
7. `chore`, `cmd`
|
||||
|
||||
## Алгоритм auto-split (уровень файлов)
|
||||
|
||||
1. `git status` и `git diff --cached --stat` — зафиксировать полный список staged-файлов.
|
||||
2. `git reset HEAD` — снять всё из index (working tree не трогать).
|
||||
3. Для каждой (объединённой) группы по порядку выше:
|
||||
- `git add -- <paths…>`
|
||||
- Сгенерировать сообщение по правилу conventional-commits.
|
||||
- Закоммитить (см. ниже).
|
||||
4. После всех коммитов — `git status` для проверки.
|
||||
|
||||
**Ограничение:** частичный stage одного файла с разной семантикой — предупредить; split по hunk'ам не делать; предложить разнести правки по файлам.
|
||||
|
||||
## Создание коммита
|
||||
|
||||
Только если пользователь **явно** просил закоммитить. Иначе — только вывести готовые сообщения.
|
||||
|
||||
```powershell
|
||||
git commit -m "$( @'
|
||||
<type>(<scope>): <summary in English>
|
||||
|
||||
<Тело на русском.>
|
||||
'@ )"
|
||||
```
|
||||
|
||||
В PowerShell для многострочного тела используйте here-string как выше или `-m` для заголовка и `-m` для тела.
|
||||
|
||||
Перед коммитом: `git status`, `git diff --cached` для группы — убедиться, что stage соответствует сообщению.
|
||||
|
||||
## Генерация текста
|
||||
|
||||
По `groups[].diff_excerpt`, `stat`, `files`:
|
||||
|
||||
### Шаг A — semver (до выбора type)
|
||||
|
||||
| Вопрос | Если «да» → |
|
||||
|--------|-------------|
|
||||
| Пользователь получает **новую** возможность? | `feat` (minor) |
|
||||
| Восстанавливается **ожидаемое** поведение / устранён баг? | `fix` (patch) |
|
||||
| Только скорость, контракт тот же? | `perf` (patch) |
|
||||
| Только структура кода/UI, поведение то же? | `refactor` (patch) |
|
||||
|
||||
**Follow-up:** правки сразу после `feat` в том же scope без новой возможности → **`fix`**, не `feat` (слова *enhance/improve/refactor* в задаче не делают commit `feat`).
|
||||
|
||||
**Запрещено** по умолчанию ставить `feat` для «большого diff» в `web/` — type по **semver impact**, не по объёму.
|
||||
|
||||
### Шаг B — type, scope, текст
|
||||
|
||||
- **type** — результат шага A, не «chore по умолчанию» и не `feat` из-за слова enhance.
|
||||
- **scope** — из JSON группы или доминирующий при merge.
|
||||
- **summary** — конкретный, английский, императив; для `fix` — что **починено** (`fix broken …`, `prevent … loop`).
|
||||
- **body** — русский: что, зачем, edge cases, breaking impact.
|
||||
|
||||
## Вывод пользователю
|
||||
|
||||
Для **каждого** коммита:
|
||||
|
||||
### 1. Готовое сообщение
|
||||
|
||||
```
|
||||
<type>(<scope>): <summary>
|
||||
|
||||
<тело>
|
||||
```
|
||||
|
||||
### 2. Пояснение (RU)
|
||||
|
||||
- **Semver impact:** `minor` | `patch` | `none` | `major` — и почему не другой type.
|
||||
- Риски и impact.
|
||||
- Split: сколько коммитов и почему.
|
||||
|
||||
## Не смешивать
|
||||
|
||||
Один commit message — одна primary intent. Не объединять несвязанный `fix` и `feat` в один заголовок.
|
||||
|
||||
## Ссылки
|
||||
|
||||
- Правило: `.cursor/rules/conventional-commits.mdc`
|
||||
- Скрипт: `scripts/commit/staged-context.ps1`
|
||||
- Просмотр групп: `powershell -File scripts/commit/staged-context.ps1 | ConvertFrom-Json`
|
||||
+30
-50
@@ -1,75 +1,55 @@
|
||||
# Gitea Actions
|
||||
|
||||
В репозитории включён workflow [workflows/ci.yaml](workflows/ci.yaml).
|
||||
Workflow: [workflows/ci.yaml](workflows/ci.yaml).
|
||||
|
||||
Job **changes** вычисляет два флага:
|
||||
| Job | PR | push в main |
|
||||
|-----|-----|-------------|
|
||||
| changes, openapi, web, go, bird2 | quality gates | quality gates |
|
||||
| commitlint | да | — |
|
||||
| **release** | — | semantic-release + docker push (один run) |
|
||||
|
||||
- **`openapi`** — в диффе есть `docs/openapi.yaml` или `redocly.yaml` → запускается **openapi** (Redocly lint).
|
||||
- **`code`** — в диффе есть **хотя бы один файл вне «только документация»** → запускаются **go**, **bird2** и при push в main/master **docker-images**.
|
||||
Подробнее: [docs/releasing.md](../docs/releasing.md).
|
||||
|
||||
Если изменены **только** файлы из списка ниже, **`code=false`**: Go-тесты, bird2 и сборка образов **не** запускаются; при необходимости всё ещё выполняется **openapi**, если трогали OpenAPI или `redocly.yaml`.
|
||||
## CI (quality gates)
|
||||
|
||||
**Список путей «только документация» (без полной сборки):** всё под `docs/`, корневой `README.md`, `web/README.md`, `.gitea/README.md`, `redocly.yaml`.
|
||||
Job **changes** вычисляет флаги по путям в diff. Полный прогон (все узлы openapi / web / go / bird2 в графе): `.gitea/workflows/*`, `scripts/*`, `.golangci.yml`, `.pre-commit-config.yaml`, корневой `package.json` / `.releaserc.json`. Отдельно: `migrations/*`, `docs/openapi.yaml` → `go` / `openapi` и т.д. (см. `ci.yaml`).
|
||||
|
||||
Любой другой путь (в т.ч. `.gitea/workflows/ci.yaml`, `go.mod`, `web/package.json`, `deploy/**`, `**/*.go`) включает полный пайплайн.
|
||||
На **pull request** — **commitlint** (Conventional Commits).
|
||||
|
||||
Требования к runner:
|
||||
Runner: `ubuntu-latest`, **bird2** из apt, Docker для job **release**.
|
||||
|
||||
- Метка `ubuntu-latest` (или измените `runs-on` под свои labels).
|
||||
- Job `bird2` ставит пакет **bird2** через `apt-get` на самом runner и вызывает `bird -c … -p` по файлам в checkout (без вложенного Docker: иначе bind-mount `/workspace/...` часто не виден демону Docker на хосте).
|
||||
- Job **docker-images** требует **Docker** и (для push) доступ к Container Registry Gitea с runner’а.
|
||||
## Release (job в ci.yaml)
|
||||
|
||||
## Сборка и публикация образов (`docker-images`)
|
||||
После успешных quality gates на **push в main** job **release**:
|
||||
|
||||
Запускается только при **push** в ветки `main` или `master` (после успешного job `go`). Собираются образы из `deploy/docker/*` (все бинарники через `gobinary`, плюс `evobgp-web`, `evobgp-agent`, `evobgp-bird2`).
|
||||
1. `npx semantic-release` — тег `vX.Y.Z` на **текущий commit** (без дополнительного commit в main).
|
||||
2. Gitea Release + `CHANGELOG.md` как attachment (не в git).
|
||||
3. `docker buildx bake default --push` с `VERSION=X.Y.Z` — в том же job.
|
||||
|
||||
### Секреты репозитория (для push в реестр)
|
||||
Если releasable-коммитов нет — semantic-release no-op, образы не публикуются.
|
||||
|
||||
Хост Container Registry в workflow **зашит**: **`git.shts.su`** (`docker/login-action` и теги образов).
|
||||
### Секреты
|
||||
|
||||
В настройках репозитория Gitea: **Settings → Actions → Secrets** (или аналог):
|
||||
**`ACTIONS_PAT`**: push tags, releases, Container Registry. Fallback: **`gitea.token`**.
|
||||
|
||||
| Секрет | Назначение |
|
||||
|--------|------------|
|
||||
| `ACTIONS_PAT` | (Опционально) PAT с правом **записи пакетов**. Если не задан, для `docker login` используется **`gitea.token`** (нужны права у workflow на пакеты). |
|
||||
|
||||
Вход в реестр в workflow:
|
||||
|
||||
- **registry:** `git.shts.su`;
|
||||
- **username:** `${{ gitea.actor }}`;
|
||||
- **password:** `${{ secrets.ACTIONS_PAT || gitea.token }}`.
|
||||
|
||||
### Почему шаг «Log in to Gitea Registry» мог быть skipped
|
||||
|
||||
Раньше в `if:` стояло **`secrets.ACTIONS_PAT != ''`**. В **Gitea act_runner** такая проверка секрета в условии шага часто **всегда ложна**, из‑за этого логин **всегда skipped**. Сейчас условие только `docker_push == 'true'` (всегда при нормальном шаге **Prepare**), пароль: **`secrets.ACTIONS_PAT || gitea.token`**.
|
||||
|
||||
Если после правки `docker login` падает с 401/403 — выдайте job-токену или PAT право **записи в Container Registry** (в настройках Gitea / организации / репозитория, в зависимости от версии).
|
||||
|
||||
Если **`gitea.token`** в выражениях недоступен, в [ci.yaml](workflows/ci.yaml) замените пароль на `${{ secrets.ACTIONS_PAT || github.token }}`.
|
||||
|
||||
### Имена образов и теги
|
||||
|
||||
Формат:
|
||||
### Теги образов
|
||||
|
||||
```text
|
||||
git.shts.su/<owner_lowercase>/<имя>:<тег>
|
||||
git.shts.su/<owner>/<имя>:latest
|
||||
git.shts.su/<owner>/<имя>:v1.2.3
|
||||
git.shts.su/<owner>/<имя>:1.2.3
|
||||
git.shts.su/<owner>/<имя>:<short-sha>
|
||||
git.shts.su/<owner>/<имя>:sha-<full-sha>
|
||||
```
|
||||
|
||||
где `<имя>` — одно из: `evobgp-api`, `evobgp-all`, `evobgp-scheduler`, `evobgp-ingest`, `evobgp-render`, `evobgp-deploy`, `evobgp-node`, `evobgp-web`, `evobgp-web-all` (UI с прокси на `evobgp-all` для профиля Compose `microvps-full`), `evobgp-agent`, `evobgp-bird2`.
|
||||
Имена образов: `evobgp-api`, `evobgp-all`, `evobgp-scheduler`, `evobgp-ingest`, `evobgp-render`, `evobgp-deploy`, `evobgp-node`, `evobgp-web`, `evobgp-web-all`, `evobgp-agent`, `evobgp-bird2`.
|
||||
|
||||
Теги: `latest`, короткий SHA (7 символов), `sha-<полный_commit_sha>`.
|
||||
**Удалённый спикер** (compose `deploy/compose/docker-compose.remote-speaker.yaml`): `evobgp-bird2`, `evobgp-agent`, `evobgp-node` (fallback profile); Traefik — внешний `traefik:latest`. CI: `scripts/validate-remote-speaker-compose.sh`.
|
||||
|
||||
Пример pull:
|
||||
Пример:
|
||||
|
||||
```bash
|
||||
docker pull git.shts.su/myuser/evobgp-api:latest
|
||||
docker pull git.shts.su/myuser/evobgp-api:1.2.3
|
||||
```
|
||||
|
||||
Полная таблица образов, тегов, ссылок на страницы пакетов в Gitea и минимальный `docker run` для сервера без сборки — в [docs/quickstart.md](../docs/quickstart.md) (раздел «Готовые образы без сборки»).
|
||||
|
||||
Убедитесь, что в **Gitea** включены пакеты (Container Registry) и у токена есть права на создание/обновление образов. Другой хост реестра — правьте **`registry:`** и префикс **`IMG=`** в [ci.yaml](workflows/ci.yaml).
|
||||
|
||||
### Примечания
|
||||
|
||||
- Сборка с платформой `linux/amd64`. При необходимости добавьте `linux/arm64` и multi-arch в `docker buildx build`.
|
||||
- Для PR job **docker-images** не выполняется (только push в main/master), чтобы не публиковать образы из чужих форков без явной политики.
|
||||
См. [deploy/docker/README.md](../deploy/docker/README.md), [docs/quickstart.md](../docs/quickstart.md).
|
||||
+197
-231
@@ -8,10 +8,9 @@ on:
|
||||
|
||||
jobs:
|
||||
# ---------------------------------------------------------------------------
|
||||
# Гранулярная детекция изменений по модулям.
|
||||
# Каждый флаг соответствует группе файлов; downstream-джобы запускаются
|
||||
# только когда их группа затронута. Изменение CI-конфигурации (.gitea/workflows/*)
|
||||
# поднимает все флаги, чтобы гарантировать полный прогон.
|
||||
# Детекция изменений по модулям (флаги → downstream-джобы в графе CI).
|
||||
# Полный прогон (все флаги true): .gitea/workflows/*, scripts/*, .golangci.yml,
|
||||
# .pre-commit-config.yaml — чтобы при правках CI/CD пересобирались все узлы.
|
||||
# ---------------------------------------------------------------------------
|
||||
changes:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -40,6 +39,23 @@ jobs:
|
||||
docker_web=false
|
||||
docker_bird=false
|
||||
|
||||
# Все флаги true → openapi, web, go, bird2 (и release на main) в графе CI.
|
||||
set_all_flags_true() {
|
||||
openapi=true
|
||||
go=true
|
||||
web=true
|
||||
bird_conf=true
|
||||
docker_go=true
|
||||
docker_web=true
|
||||
docker_bird=true
|
||||
}
|
||||
|
||||
write_outputs() {
|
||||
for v in openapi go web bird_conf docker_go docker_web docker_bird; do
|
||||
eval "echo \"\$v=\$$v\"" >> "$GITHUB_OUTPUT"
|
||||
done
|
||||
}
|
||||
|
||||
if [ "${{ github.event_name }}" = "pull_request" ]; then
|
||||
base="${{ github.event.pull_request.base.sha }}"
|
||||
head="${{ github.event.pull_request.head.sha }}"
|
||||
@@ -52,59 +68,84 @@ jobs:
|
||||
elif git rev-parse --verify HEAD~1 >/dev/null 2>&1; then
|
||||
FILES="$(git diff --name-only HEAD~1 HEAD)"
|
||||
else
|
||||
openapi=true; go=true; web=true; bird_conf=true
|
||||
docker_go=true; docker_web=true; docker_bird=true
|
||||
for v in openapi go web bird_conf docker_go docker_web docker_bird; do
|
||||
echo "$v=true" >> "$GITHUB_OUTPUT"
|
||||
done
|
||||
echo "No parent commit — full pipeline"
|
||||
set_all_flags_true
|
||||
write_outputs
|
||||
echo "No parent commit — full pipeline (all modules)"
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$(printf '%s' "$FILES" | tr -d '[:space:]')" ]; then
|
||||
go=true; web=true
|
||||
for v in openapi go web bird_conf docker_go docker_web docker_bird; do
|
||||
eval "echo \"\$v=\$$v\"" >> "$GITHUB_OUTPUT"
|
||||
done
|
||||
echo "Empty diff — safe fallback: go=true web=true"
|
||||
set_all_flags_true
|
||||
write_outputs
|
||||
echo "Empty diff — full pipeline fallback"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
ci_changed=false
|
||||
full_pipeline=false
|
||||
|
||||
while IFS= read -r f || [ -n "${f:-}" ]; do
|
||||
[ -z "${f:-}" ] && continue
|
||||
case "$f" in
|
||||
.gitea/workflows/*) ci_changed=true ;;
|
||||
docs/openapi.yaml|redocly.yaml) openapi=true ;;
|
||||
web/README.md) ;; # doc-only
|
||||
web/*) web=true ;;
|
||||
deploy/bird/*) bird_conf=true ;;
|
||||
deploy/docker/gobinary/*) docker_go=true ;;
|
||||
deploy/docker/evobgp-agent/*) docker_go=true ;;
|
||||
deploy/docker/evobgp-web/*) docker_web=true ;;
|
||||
deploy/docker/bird2/*) docker_bird=true ;;
|
||||
go.mod|go.sum|go.work) go=true ;;
|
||||
*.go) go=true ;;
|
||||
cmd/*|internal/*) go=true ;;
|
||||
# CI/CD инфраструктура — все узлы quality gates
|
||||
.gitea/workflows/*|.golangci.yml|.pre-commit-config.yaml|scripts/*)
|
||||
full_pipeline=true
|
||||
;;
|
||||
docs/openapi.yaml|redocly.yaml)
|
||||
openapi=true
|
||||
;;
|
||||
docs/api.md|docs/access.md)
|
||||
openapi=true
|
||||
go=true
|
||||
;;
|
||||
web/README.md|web/components.json)
|
||||
;;
|
||||
web/*)
|
||||
web=true
|
||||
;;
|
||||
deploy/bird/*)
|
||||
bird_conf=true
|
||||
go=true
|
||||
;;
|
||||
deploy/compose/*|deploy/docker/*)
|
||||
docker_go=true
|
||||
docker_web=true
|
||||
docker_bird=true
|
||||
go=true
|
||||
;;
|
||||
go.mod|go.sum|go.work)
|
||||
go=true
|
||||
;;
|
||||
migrations/*)
|
||||
go=true
|
||||
;;
|
||||
cmd/*|internal/*|*.go)
|
||||
go=true
|
||||
bird_conf=true
|
||||
;;
|
||||
docs/*)
|
||||
go=true
|
||||
;;
|
||||
package.json|package-lock.json|.releaserc.json)
|
||||
full_pipeline=true
|
||||
;;
|
||||
*)
|
||||
go=true
|
||||
;;
|
||||
esac
|
||||
done <<< "$FILES"
|
||||
|
||||
if $ci_changed; then
|
||||
go=true; web=true; bird_conf=true
|
||||
docker_go=true; docker_web=true; docker_bird=true
|
||||
if $full_pipeline; then
|
||||
set_all_flags_true
|
||||
fi
|
||||
|
||||
for v in openapi go web bird_conf docker_go docker_web docker_bird; do
|
||||
eval "echo \"\$v=\$$v\"" >> "$GITHUB_OUTPUT"
|
||||
done
|
||||
write_outputs
|
||||
|
||||
echo "Changed files (first 30):"
|
||||
printf '%s\n' "$FILES" | head -n 30
|
||||
echo "--- flags ---"
|
||||
echo "openapi=$openapi go=$go web=$web bird_conf=$bird_conf"
|
||||
echo "docker_go=$docker_go docker_web=$docker_web docker_bird=$docker_bird ci=$ci_changed"
|
||||
echo "docker_go=$docker_go docker_web=$docker_web docker_bird=$docker_bird full_pipeline=$full_pipeline"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
openapi:
|
||||
@@ -119,6 +160,26 @@ jobs:
|
||||
- name: Lint OpenAPI (Redocly)
|
||||
run: npx --yes @redocly/cli@1 lint docs/openapi.yaml
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
web:
|
||||
needs: [changes]
|
||||
if: needs.changes.outputs.web == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "20"
|
||||
cache: npm
|
||||
cache-dependency-path: web/package-lock.json
|
||||
- name: npm ci, check, lint
|
||||
run: |
|
||||
set -euxo pipefail
|
||||
cd web
|
||||
npm ci
|
||||
npm run check
|
||||
npm run lint
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
go:
|
||||
needs: [changes]
|
||||
@@ -128,9 +189,23 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.22"
|
||||
go-version: "1.24"
|
||||
cache: true
|
||||
cache-dependency-path: go.sum
|
||||
- name: Vet
|
||||
run: go vet ./...
|
||||
- name: Lint httpapi (ERR-01 / ARCH-01)
|
||||
run: sh scripts/lint-httpapi.sh
|
||||
- name: Check migration pairs (DEP-03)
|
||||
run: sh scripts/check-migrations-pair.sh
|
||||
- name: Validate remote speaker compose
|
||||
run: sh scripts/validate-remote-speaker-compose.sh
|
||||
# go.mod: go 1.24 — бинарник golangci-lint < v1.64.2 (сборка на Go 1.23) не запускается.
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v6
|
||||
with:
|
||||
version: v1.64.8
|
||||
install-mode: goinstall
|
||||
- name: Test
|
||||
run: go test ./... -race -count=1
|
||||
- name: Build all commands
|
||||
@@ -146,10 +221,18 @@ jobs:
|
||||
# ---------------------------------------------------------------------------
|
||||
bird2:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [go]
|
||||
needs: [changes, go]
|
||||
if: >-
|
||||
always() &&
|
||||
needs.changes.result == 'success' &&
|
||||
needs.go.result != 'failure' &&
|
||||
(needs.changes.outputs.go == 'true' ||
|
||||
needs.changes.outputs.bird_conf == 'true' ||
|
||||
needs.changes.outputs.docker_bird == 'true' ||
|
||||
needs.changes.outputs.docker_go == 'true')
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install bird2
|
||||
- name: Install bird2 (репозиторий Ubuntu runner, как в образе evobgp-bird2)
|
||||
run: |
|
||||
set -euxo pipefail
|
||||
if command -v sudo >/dev/null 2>&1; then SUDO=sudo; else SUDO=""; fi
|
||||
@@ -174,224 +257,107 @@ jobs:
|
||||
done
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Docker: Go-бинарники (api, all, scheduler, ingest, render, deploy, node, agent).
|
||||
# Запускается если изменился Go-код или Go-Dockerfile.
|
||||
# Если Go-код менялся — требуем успех go-тестов; если только Dockerfile — go skipped, ОК.
|
||||
commitlint:
|
||||
if: github.event_name == 'pull_request'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
- name: Lint commit messages
|
||||
run: |
|
||||
set -euxo pipefail
|
||||
npm ci
|
||||
npx commitlint --from "${{ github.event.pull_request.base.sha }}" --to "${{ github.event.pull_request.head.sha }}"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
docker-go:
|
||||
needs: [changes, go]
|
||||
# Один push в main: semantic-release (тег на текущий commit, без доп. commit) + docker push.
|
||||
# ---------------------------------------------------------------------------
|
||||
release:
|
||||
needs: [changes, openapi, web, go, bird2]
|
||||
if: >-
|
||||
always() &&
|
||||
github.event_name == 'push' &&
|
||||
(github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master') &&
|
||||
needs.changes.result == 'success' &&
|
||||
needs.go.result != 'failure' &&
|
||||
github.event_name == 'push' &&
|
||||
(github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master') &&
|
||||
(needs.changes.outputs.go == 'true' || needs.changes.outputs.docker_go == 'true')
|
||||
(needs.openapi.result == 'success' || needs.openapi.result == 'skipped') &&
|
||||
(needs.web.result == 'success' || needs.web.result == 'skipped') &&
|
||||
(needs.go.result == 'success' || needs.go.result == 'skipped') &&
|
||||
(needs.bird2.result == 'success' || needs.bird2.result == 'skipped')
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- image: evobgp-api
|
||||
dockerfile: deploy/docker/gobinary/Dockerfile
|
||||
bin: evobgp-api
|
||||
birdc: "1"
|
||||
evobgp_upstream: ""
|
||||
- image: evobgp-all
|
||||
dockerfile: deploy/docker/gobinary/Dockerfile
|
||||
bin: evobgp-all
|
||||
birdc: "1"
|
||||
evobgp_upstream: ""
|
||||
- image: evobgp-scheduler
|
||||
dockerfile: deploy/docker/gobinary/Dockerfile
|
||||
bin: evobgp-scheduler
|
||||
birdc: "0"
|
||||
evobgp_upstream: ""
|
||||
- image: evobgp-ingest
|
||||
dockerfile: deploy/docker/gobinary/Dockerfile
|
||||
bin: evobgp-ingest
|
||||
birdc: "0"
|
||||
evobgp_upstream: ""
|
||||
- image: evobgp-render
|
||||
dockerfile: deploy/docker/gobinary/Dockerfile
|
||||
bin: evobgp-render
|
||||
birdc: "0"
|
||||
evobgp_upstream: ""
|
||||
- image: evobgp-deploy
|
||||
dockerfile: deploy/docker/gobinary/Dockerfile
|
||||
bin: evobgp-deploy
|
||||
birdc: "0"
|
||||
evobgp_upstream: ""
|
||||
- image: evobgp-node
|
||||
dockerfile: deploy/docker/gobinary/Dockerfile
|
||||
bin: evobgp-node
|
||||
birdc: "0"
|
||||
evobgp_upstream: ""
|
||||
- image: evobgp-agent
|
||||
dockerfile: deploy/docker/evobgp-agent/Dockerfile
|
||||
evobgp_upstream: ""
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.ACTIONS_PAT || gitea.token }}
|
||||
persist-credentials: true
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: npm
|
||||
cache-dependency-path: package-lock.json
|
||||
- name: Install release tooling
|
||||
run: npm ci
|
||||
- name: Verify releasable commit messages
|
||||
run: node scripts/commit/verify-release-commits.mjs
|
||||
- name: Semantic release
|
||||
run: npx semantic-release
|
||||
env:
|
||||
GITEA_URL: https://git.shts.su
|
||||
GITEA_TOKEN: ${{ secrets.ACTIONS_PAT || gitea.token }}
|
||||
- name: Detect new release
|
||||
id: rel
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ -f .release-version ]; then
|
||||
echo "version=$(tr -d '[:space:]' < .release-version)" >> "$GITHUB_OUTPUT"
|
||||
echo "released=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "released=false" >> "$GITHUB_OUTPUT"
|
||||
echo "No releasable commits — skipping image publish"
|
||||
fi
|
||||
- name: Set up Docker Buildx
|
||||
if: steps.rel.outputs.released == 'true'
|
||||
uses: docker/setup-buildx-action@v3
|
||||
- name: Prepare image metadata
|
||||
if: steps.rel.outputs.released == 'true'
|
||||
id: meta
|
||||
run: |
|
||||
set -euo pipefail
|
||||
echo "version=${{ steps.rel.outputs.version }}" >> "$GITHUB_OUTPUT"
|
||||
owner_lc="$(echo '${{ github.repository_owner }}' | tr '[:upper:]' '[:lower:]')"
|
||||
echo "owner_lc=$owner_lc" >> "$GITHUB_OUTPUT"
|
||||
short_sha="$(echo '${{ github.sha }}' | cut -c1-7)"
|
||||
echo "short_sha=$short_sha" >> "$GITHUB_OUTPUT"
|
||||
echo "build_time=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$GITHUB_OUTPUT"
|
||||
- name: Log in to Gitea Registry
|
||||
if: steps.rel.outputs.released == 'true'
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: git.shts.su
|
||||
username: ${{ gitea.actor }}
|
||||
password: ${{ secrets.ACTIONS_PAT || gitea.token }}
|
||||
- name: Build and push ${{ matrix.image }}
|
||||
- name: Build and push images (bake)
|
||||
if: steps.rel.outputs.released == 'true'
|
||||
env:
|
||||
OWNER_LC: ${{ steps.meta.outputs.owner_lc }}
|
||||
REGISTRY: git.shts.su/${{ steps.meta.outputs.owner_lc }}
|
||||
IMAGE_TAG: latest
|
||||
VERSION: ${{ steps.meta.outputs.version }}
|
||||
SHORT_SHA: ${{ steps.meta.outputs.short_sha }}
|
||||
DF: ${{ matrix.dockerfile }}
|
||||
IMAGE: ${{ matrix.image }}
|
||||
BIN: ${{ matrix.bin }}
|
||||
BIRDC: ${{ matrix.birdc }}
|
||||
EVOBGP_UPSTREAM: ${{ matrix.evobgp_upstream }}
|
||||
SHA_FULL: ${{ github.sha }}
|
||||
BUILD_TIME: ${{ steps.meta.outputs.build_time }}
|
||||
CACHE_REF_GO: git.shts.su/${{ steps.meta.outputs.owner_lc }}/evobgp-buildcache:go-buildcache
|
||||
CACHE_REF_WEB: git.shts.su/${{ steps.meta.outputs.owner_lc }}/evobgp-buildcache:web-buildcache
|
||||
BUILDX_BAKE_ENTITLEMENTS_FS: "0"
|
||||
run: |
|
||||
set -euxo pipefail
|
||||
WS="${{ github.workspace }}"
|
||||
cd "$WS"
|
||||
cd "${{ github.workspace }}/deploy/docker"
|
||||
sh write-bake-override.sh
|
||||
docker buildx bake --allow=fs.read="${{ github.workspace }}" \
|
||||
-f docker-bake.hcl -f docker-bake.override.hcl default --push
|
||||
|
||||
IMG="git.shts.su/${OWNER_LC}/${IMAGE}"
|
||||
BUILD_ARGS=()
|
||||
if [ -n "${BIN:-}" ]; then
|
||||
BUILD_ARGS+=(--build-arg "BIN=${BIN}")
|
||||
BUILD_ARGS+=(--build-arg "INSTALL_BIRDC=${BIRDC:-0}")
|
||||
fi
|
||||
if [ -n "${EVOBGP_UPSTREAM:-}" ]; then
|
||||
BUILD_ARGS+=(--build-arg "EVOBGP_UPSTREAM=${EVOBGP_UPSTREAM}")
|
||||
fi
|
||||
|
||||
docker buildx build \
|
||||
--platform linux/amd64 \
|
||||
--file "$DF" \
|
||||
"${BUILD_ARGS[@]}" \
|
||||
--tag "${IMG}:latest" \
|
||||
--tag "${IMG}:${SHORT_SHA}" \
|
||||
--tag "${IMG}:sha-${{ github.sha }}" \
|
||||
--push \
|
||||
"$WS"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Docker: Web-фронтенд (evobgp-web, evobgp-web-all).
|
||||
# Не зависит от Go-тестов — SvelteKit собирается отдельно.
|
||||
# ---------------------------------------------------------------------------
|
||||
docker-web:
|
||||
needs: [changes]
|
||||
if: >-
|
||||
github.event_name == 'push' &&
|
||||
(github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master') &&
|
||||
(needs.changes.outputs.web == 'true' || needs.changes.outputs.docker_web == 'true')
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- image: evobgp-web
|
||||
dockerfile: deploy/docker/evobgp-web/Dockerfile
|
||||
evobgp_upstream: ""
|
||||
- image: evobgp-web-all
|
||||
dockerfile: deploy/docker/evobgp-web/Dockerfile
|
||||
evobgp_upstream: evobgp-all
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
- name: Prepare image metadata
|
||||
id: meta
|
||||
run: |
|
||||
set -euo pipefail
|
||||
owner_lc="$(echo '${{ github.repository_owner }}' | tr '[:upper:]' '[:lower:]')"
|
||||
echo "owner_lc=$owner_lc" >> "$GITHUB_OUTPUT"
|
||||
short_sha="$(echo '${{ github.sha }}' | cut -c1-7)"
|
||||
echo "short_sha=$short_sha" >> "$GITHUB_OUTPUT"
|
||||
- name: Log in to Gitea Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: git.shts.su
|
||||
username: ${{ gitea.actor }}
|
||||
password: ${{ secrets.ACTIONS_PAT || gitea.token }}
|
||||
- name: Build and push ${{ matrix.image }}
|
||||
env:
|
||||
OWNER_LC: ${{ steps.meta.outputs.owner_lc }}
|
||||
SHORT_SHA: ${{ steps.meta.outputs.short_sha }}
|
||||
DF: ${{ matrix.dockerfile }}
|
||||
IMAGE: ${{ matrix.image }}
|
||||
EVOBGP_UPSTREAM: ${{ matrix.evobgp_upstream }}
|
||||
run: |
|
||||
set -euxo pipefail
|
||||
WS="${{ github.workspace }}"
|
||||
cd "$WS"
|
||||
|
||||
IMG="git.shts.su/${OWNER_LC}/${IMAGE}"
|
||||
BUILD_ARGS=()
|
||||
if [ -n "${EVOBGP_UPSTREAM:-}" ]; then
|
||||
BUILD_ARGS+=(--build-arg "EVOBGP_UPSTREAM=${EVOBGP_UPSTREAM}")
|
||||
fi
|
||||
|
||||
docker buildx build \
|
||||
--platform linux/amd64 \
|
||||
--file "$DF" \
|
||||
"${BUILD_ARGS[@]}" \
|
||||
--tag "${IMG}:latest" \
|
||||
--tag "${IMG}:${SHORT_SHA}" \
|
||||
--tag "${IMG}:sha-${{ github.sha }}" \
|
||||
--push \
|
||||
"$WS"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Docker: BIRD2 (evobgp-bird2).
|
||||
# Собирается только при изменении deploy/bird/ или Dockerfile bird2.
|
||||
# ---------------------------------------------------------------------------
|
||||
docker-bird:
|
||||
needs: [changes]
|
||||
if: >-
|
||||
github.event_name == 'push' &&
|
||||
(github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master') &&
|
||||
(needs.changes.outputs.bird_conf == 'true' || needs.changes.outputs.docker_bird == 'true')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
- name: Prepare image metadata
|
||||
id: meta
|
||||
run: |
|
||||
set -euo pipefail
|
||||
owner_lc="$(echo '${{ github.repository_owner }}' | tr '[:upper:]' '[:lower:]')"
|
||||
echo "owner_lc=$owner_lc" >> "$GITHUB_OUTPUT"
|
||||
short_sha="$(echo '${{ github.sha }}' | cut -c1-7)"
|
||||
echo "short_sha=$short_sha" >> "$GITHUB_OUTPUT"
|
||||
- name: Log in to Gitea Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: git.shts.su
|
||||
username: ${{ gitea.actor }}
|
||||
password: ${{ secrets.ACTIONS_PAT || gitea.token }}
|
||||
- name: Build and push evobgp-bird2
|
||||
env:
|
||||
OWNER_LC: ${{ steps.meta.outputs.owner_lc }}
|
||||
SHORT_SHA: ${{ steps.meta.outputs.short_sha }}
|
||||
run: |
|
||||
set -euxo pipefail
|
||||
WS="${{ github.workspace }}"
|
||||
IMG="git.shts.su/${OWNER_LC}/evobgp-bird2"
|
||||
|
||||
docker buildx build \
|
||||
--platform linux/amd64 \
|
||||
--file deploy/docker/bird2/Dockerfile \
|
||||
--tag "${IMG}:latest" \
|
||||
--tag "${IMG}:${SHORT_SHA}" \
|
||||
--tag "${IMG}:sha-${{ github.sha }}" \
|
||||
--push \
|
||||
"$WS"
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
# Root npm (semantic-release, commitlint) — npm ci in CI, never commit deps
|
||||
node_modules/
|
||||
|
||||
# Generated by deploy/docker/write-bake-override.sh (CI/local bake)
|
||||
deploy/docker/docker-bake.override.hcl
|
||||
|
||||
# CI-only markers (not committed)
|
||||
.release-version
|
||||
CHANGELOG.md
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Env / secrets (local only)
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
!.env.*.example
|
||||
@@ -0,0 +1,18 @@
|
||||
run:
|
||||
timeout: 5m
|
||||
|
||||
linters:
|
||||
disable-all: true
|
||||
enable:
|
||||
- gofmt
|
||||
- govet
|
||||
- errcheck
|
||||
|
||||
issues:
|
||||
exclude-use-default: false
|
||||
max-issues-per-linter: 50
|
||||
max-same-issues: 20
|
||||
|
||||
linters-settings:
|
||||
gofmt:
|
||||
simplify: true
|
||||
@@ -0,0 +1,19 @@
|
||||
# Local hooks (optional): install with `pre-commit install`
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v5.0.0
|
||||
hooks:
|
||||
- id: trailing-whitespace
|
||||
- id: end-of-file-fixer
|
||||
- repo: https://github.com/dnephin/pre-commit-golang
|
||||
rev: v0.5.1
|
||||
hooks:
|
||||
- id: go-fmt
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: prettier-web
|
||||
name: prettier (web)
|
||||
entry: bash -c 'cd web && npx prettier --check .'
|
||||
language: system
|
||||
files: ^web/
|
||||
pass_filenames: false
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"branches": ["main", "master"],
|
||||
"tagFormat": "v${version}",
|
||||
"plugins": [
|
||||
[
|
||||
"@semantic-release/commit-analyzer",
|
||||
{
|
||||
"preset": "conventionalcommits",
|
||||
"releaseRules": [
|
||||
{ "type": "feat", "release": "minor" },
|
||||
{ "type": "fix", "release": "patch" },
|
||||
{ "type": "perf", "release": "patch" },
|
||||
{ "type": "ci", "release": "patch" },
|
||||
{ "type": "refactor", "release": "patch" },
|
||||
{ "breaking": true, "release": "major" }
|
||||
]
|
||||
}
|
||||
],
|
||||
[
|
||||
"@semantic-release/release-notes-generator",
|
||||
{
|
||||
"preset": "conventionalcommits"
|
||||
}
|
||||
],
|
||||
[
|
||||
"@semantic-release/changelog",
|
||||
{
|
||||
"changelogFile": "CHANGELOG.md"
|
||||
}
|
||||
],
|
||||
[
|
||||
"@semantic-release/exec",
|
||||
{
|
||||
"successCmd": "echo ${nextRelease.version} > .release-version"
|
||||
}
|
||||
],
|
||||
[
|
||||
"@markwylde/semantic-release-gitea",
|
||||
{
|
||||
"giteaUrl": "https://git.shts.su",
|
||||
"assets": [
|
||||
{
|
||||
"path": "CHANGELOG.md",
|
||||
"label": "Changelog"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
# Руководство для ИИ-агентов (экономия контекста)
|
||||
|
||||
Краткие ориентиры по репозиторию **EvoBGP**, чтобы не тратить токены на полное сканирование дерева и повторное чтение одних и тех же файлов.
|
||||
|
||||
## С чего начать (минимум чтения)
|
||||
|
||||
0. **Инженерные правила** — при изменении кода следовать [.cursor/rules/engineering.mdc](.cursor/rules/engineering.mdc); для `web/` — [.cursor/rules/web-shadcn.mdc](.cursor/rules/web-shadcn.mdc); для `birdfmt` / `pipeline` / BIRD — [.cursor/rules/networking-bird.mdc](.cursor/rules/networking-bird.mdc).
|
||||
1. **[docs/README.md](docs/README.md)** — оглавление и роли читателя.
|
||||
2. **[docs/architecture.md](docs/architecture.md)** — компоненты `cmd/`, карта `internal/`, потоки данных (одного этого файла обычно достаточно для ориентации).
|
||||
3. Задача-специфично: [docs/api.md](docs/api.md), [docs/access.md](docs/access.md), [web/README.md](web/README.md) — только если меняете API, доступ или фронт.
|
||||
|
||||
Источник правды по HTTP-контракту: **[docs/openapi.yaml](docs/openapi.yaml)**. Не дублируйте длинные фрагменты спецификации в ответах — ссылайтесь на путь и тег/операцию.
|
||||
|
||||
## Карта кода (куда смотреть)
|
||||
|
||||
| Область | Где искать |
|
||||
|---------|------------|
|
||||
| REST, auth, CORS | `internal/httpapi/` |
|
||||
| Бизнес-слой и абстракция хранилища | `internal/store/` |
|
||||
| PostgreSQL | `internal/repository/`, `internal/db/`, `migrations/` |
|
||||
| Фоновые задачи | `internal/jobs/` |
|
||||
| Цепочка refresh модуля (ingest+render, BIRD preview) | `internal/pipeline/` |
|
||||
| Конфиг BIRD, `birdc` | `internal/birdfmt/`, `internal/birddeploy/` |
|
||||
| Бандлы и подписи | `internal/bundle/`, `internal/signing/` |
|
||||
| Точки входа процессов | `cmd/*/` |
|
||||
| Веб (SvelteKit) | `web/` |
|
||||
| Compose, деплой | `deploy/compose/` |
|
||||
|
||||
Точки входа бинарников и их роли — в таблице в начале [docs/architecture.md](docs/architecture.md).
|
||||
|
||||
## Как не раздувать контекст
|
||||
|
||||
- **Сначала узкий поиск:** `grep`/поиск по символу или короткий семантический запрос по одной папке (`internal/httpapi/`, `internal/pipeline/`, …), а не чтение всех `.go` подряд.
|
||||
- **Читайте файлы целиком только при необходимости:** большие файлы — с `offset`/`limit` или по найденным строкам.
|
||||
- **Не подтягивайте в контекст:** `web/node_modules/`, сгенерированные артефакты сборки, бинарники, полный `openapi.html`, если достаточно `openapi.yaml`.
|
||||
- **Повторное использование:** если [docs/architecture.md](docs/architecture.md) уже описывает поток — не пересказывайте его длинно; укажите документ и конкретный подпункт задачи.
|
||||
- **Длинные планы:** `.cursor/plans/*.plan.md` — для истории решений; для навигации пользователю достаточно `docs/`; не читайте план целиком без причины.
|
||||
|
||||
## Коммиты (Conventional Commits)
|
||||
|
||||
Если пользователь просит **коммит**, **commit message**, **закоммить**, **git commit**, **`/commit-message`** или это следует из плана — **сразу**:
|
||||
|
||||
1. Shell: `powershell -NoProfile -File scripts/commit/staged-context.ps1` (первый вызов, до текста коммита).
|
||||
2. Скилл [.cursor/skills/commit-message/SKILL.md](.cursor/skills/commit-message/SKILL.md) и правило [.cursor/rules/conventional-commits.mdc](.cursor/rules/conventional-commits.mdc).
|
||||
|
||||
Без вывода скрипта (exit 0) **не** придумывать сообщение коммита. Заголовок — EN, тело — RU; несвязанные области — auto-split (скилл).
|
||||
|
||||
**Кнопка ✨ Generate commit message в Source Control** skill/rule **не** использует. Для сообщений по правилам EvoBGP — Agent Chat → **`/commit-message`** (см. [.cursor/commands/commit-message.md](.cursor/commands/commit-message.md)).
|
||||
|
||||
## Команды и среда
|
||||
|
||||
- Консоль пользователя: **PowerShell**; пути в стиле `deploy\compose`.
|
||||
- Быстрый старт и переменные: [docs/quickstart.md](docs/quickstart.md), [README.md](README.md).
|
||||
- **Go:** после правок — `gofmt -w`, `go vet ./...`, `scripts/lint-go.ps1` (как CI golangci-lint).
|
||||
|
||||
## Язык документации проекта
|
||||
|
||||
Пользовательская документация в `docs/` — преимущественно на русском. Комментарии и имена в коде — в существующем стиле репозитория.
|
||||
|
||||
## Svelte / фронтенд
|
||||
|
||||
При правках `web/**/*.svelte` или Svelte-модулей следуйте [.cursor/rules/web-shadcn.mdc](.cursor/rules/web-shadcn.mdc) (**WEB-19**): перед завершением задачи **обязательно**:
|
||||
|
||||
```powershell
|
||||
cd web
|
||||
npm run check
|
||||
npm run lint
|
||||
```
|
||||
|
||||
Если `lint` падает — `npx prettier --write .` и повторить обе команды. CI job `web` не пропускает без этого.
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
## 1.0.0 (2026-05-19)
|
||||
|
||||
* feat: add @tanstack/table-core dependency and integrate module name mapping in operations page. Upda ([b140dcb](http://192.168.100.56:3000/denozord/EvoBGP/commit/b140dcb))
|
||||
* feat: add @types/node and undici-types to devDependencies in package.json and package-lock.json for ([d92a06c](http://192.168.100.56:3000/denozord/EvoBGP/commit/d92a06c))
|
||||
* feat: add aggregated router-lists catalog endpoint and update module listing filters ([c811c43](http://192.168.100.56:3000/denozord/EvoBGP/commit/c811c43))
|
||||
* feat: add auto-updater service for Docker stack with configurable settings ([ae9fbe3](http://192.168.100.56:3000/denozord/EvoBGP/commit/ae9fbe3))
|
||||
* feat: add bird configuration preview functionality with tabbed interface for fragments and prefixes. ([1969a00](http://192.168.100.56:3000/denozord/EvoBGP/commit/1969a00))
|
||||
* feat: add BIRD status endpoint and integrate birdc checks into job processing. Enhance UI to display ([94a4c6a](http://192.168.100.56:3000/denozord/EvoBGP/commit/94a4c6a))
|
||||
* feat: add CSV import and export functionality for module entries. Implement endpoints for exporting ([bae2d68](http://192.168.100.56:3000/denozord/EvoBGP/commit/bae2d68))
|
||||
* feat: add debug logging and optimize database queries in Postgres repository ([6d0e214](http://192.168.100.56:3000/denozord/EvoBGP/commit/6d0e214))
|
||||
* feat: add diagnostic log endpoint for revisions and implement download functionality ([2260ecf](http://192.168.100.56:3000/denozord/EvoBGP/commit/2260ecf))
|
||||
* feat: add enabled state to BGP peer types and UI. Implement peer enabling toggle in the network page ([80965ad](http://192.168.100.56:3000/denozord/EvoBGP/commit/80965ad))
|
||||
* feat: add last refreshed timestamp to modules and CDN sources ([1e13ef9](http://192.168.100.56:3000/denozord/EvoBGP/commit/1e13ef9))
|
||||
* feat: add live BGP protocol state tracking to peer listing ([8a50ba4](http://192.168.100.56:3000/denozord/EvoBGP/commit/8a50ba4))
|
||||
* feat: add optional name field to BGP peer creation and update UI ([1a61ae2](http://192.168.100.56:3000/denozord/EvoBGP/commit/1a61ae2))
|
||||
* feat: add optional name field to DoH profile schema and types ([6bee5ad](http://192.168.100.56:3000/denozord/EvoBGP/commit/6bee5ad))
|
||||
* feat: add smart aggregation for IPv4 CIDR prefixes in refresh pipeline. Implement functionality to a ([0428b83](http://192.168.100.56:3000/denozord/EvoBGP/commit/0428b83))
|
||||
* feat: add strict bind configuration to BGP templates. Enhance BGP template rendering by including 's ([07f2ce5](http://192.168.100.56:3000/denozord/EvoBGP/commit/07f2ce5))
|
||||
* feat: add tenant refresh functionality to HTTP API and job processing ([7a2b015](http://192.168.100.56:3000/denozord/EvoBGP/commit/7a2b015))
|
||||
* feat: auto-refresh non-IP module updates and add full project manual ([1e77e1a](http://192.168.100.56:3000/denozord/EvoBGP/commit/1e77e1a))
|
||||
* feat: enhance API client with pagination and new data fetching functions. Implement `apiPageAll` for ([9f0b128](http://192.168.100.56:3000/denozord/EvoBGP/commit/9f0b128))
|
||||
* feat: enhance BGP template and peer configuration handling. Introduce policies_json parameter for lo ([be8e7b5](http://192.168.100.56:3000/denozord/EvoBGP/commit/be8e7b5))
|
||||
* feat: enhance CDN source management with last refreshed timestamp ([4776434](http://192.168.100.56:3000/denozord/EvoBGP/commit/4776434))
|
||||
* feat: enhance community attribute handling in BIRD format. Add validation for community route bodies ([b541794](http://192.168.100.56:3000/denozord/EvoBGP/commit/b541794))
|
||||
* feat: enhance community label handling and improve UI localization across operations pages. Introduc ([53fd527](http://192.168.100.56:3000/denozord/EvoBGP/commit/53fd527))
|
||||
* feat: enhance deployment configuration for secure Web UI with Traefik integration ([4acd685](http://192.168.100.56:3000/denozord/EvoBGP/commit/4acd685))
|
||||
* feat: enhance DoH profile management and resolver policy in modules ([34ecc5c](http://192.168.100.56:3000/denozord/EvoBGP/commit/34ecc5c))
|
||||
* feat: enhance EvoBGP with new command-line options for the evobgp-agent, including a watch command f ([6a55f72](http://192.168.100.56:3000/denozord/EvoBGP/commit/6a55f72))
|
||||
* feat: enhance evobgp with new command-line tools for bundle management, including pull, verify, and ([bf52b21](http://192.168.100.56:3000/denozord/EvoBGP/commit/bf52b21))
|
||||
* feat: enhance job detail handling in UI with caching and loading states. Introduce SvelteMap for job ([05bc5c4](http://192.168.100.56:3000/denozord/EvoBGP/commit/05bc5c4))
|
||||
* feat: enhance job detail UI with improved overflow handling and layout adjustments. Update card comp ([67ce135](http://192.168.100.56:3000/denozord/EvoBGP/commit/67ce135))
|
||||
* feat: enhance job filtering and display functionality in operations page. Introduce job search and f ([e1c4cbc](http://192.168.100.56:3000/denozord/EvoBGP/commit/e1c4cbc))
|
||||
* feat: enhance job processing with detailed logging and UI improvements. Introduce revision log entri ([c48cc4e](http://192.168.100.56:3000/denozord/EvoBGP/commit/c48cc4e))
|
||||
* feat: enhance monitoring page with detailed status tracking and error handling ([458a885](http://192.168.100.56:3000/denozord/EvoBGP/commit/458a885))
|
||||
* feat: enhance observability with prefix aggregation metrics ([07b97bd](http://192.168.100.56:3000/denozord/EvoBGP/commit/07b97bd))
|
||||
* feat: enhance peer neighbor handling by introducing NormalizePeerNeighborString function. Update Cre ([80f3a8d](http://192.168.100.56:3000/denozord/EvoBGP/commit/80f3a8d))
|
||||
* feat: enhance RefreshModule to aggregate prefixes from all enabled tenant modules. Update documentat ([431c6a9](http://192.168.100.56:3000/denozord/EvoBGP/commit/431c6a9))
|
||||
* feat: enhance RefreshModule to support legacy ASN resolution and improve prefix handling. Introduce ([e1aaa18](http://192.168.100.56:3000/denozord/EvoBGP/commit/e1aaa18))
|
||||
* feat: enhance settings page layout and section management ([d91667f](http://192.168.100.56:3000/denozord/EvoBGP/commit/d91667f))
|
||||
* feat: enhance UI components with improved styling and layout adjustments. Update button sizes, text ([6a72842](http://192.168.100.56:3000/denozord/EvoBGP/commit/6a72842))
|
||||
* feat: enhance worker functionality by adding job queuing for deploy_apply. Introduce a Registry fiel ([42d956d](http://192.168.100.56:3000/denozord/EvoBGP/commit/42d956d))
|
||||
* feat: implement AS holder name resolution and enhance ASEntry structure. Add ASHolderName function t ([c958d5a](http://192.168.100.56:3000/denozord/EvoBGP/commit/c958d5a))
|
||||
* feat: implement bulk selection and deletion for modules and entries. Add functionality for selecting ([e816d17](http://192.168.100.56:3000/denozord/EvoBGP/commit/e816d17))
|
||||
* feat: implement CDN source preview functionality and enhance data handling. Add a new endpoint for p ([e20c9f3](http://192.168.100.56:3000/denozord/EvoBGP/commit/e20c9f3))
|
||||
* feat: implement countAll function for API data retrieval ([40c8a8d](http://192.168.100.56:3000/denozord/EvoBGP/commit/40c8a8d))
|
||||
* feat: implement domain resolution via DoH in refresh pipeline. Enhance the collectModulePrefixRows f ([678bd27](http://192.168.100.56:3000/denozord/EvoBGP/commit/678bd27))
|
||||
* feat: implement effective peer enabling logic during peer creation. Update CreatePeer methods in Pos ([3e85431](http://192.168.100.56:3000/denozord/EvoBGP/commit/3e85431))
|
||||
* feat: implement module refresh job management with concurrency control. Add CountOtherActiveModuleRe ([149fb0a](http://192.168.100.56:3000/denozord/EvoBGP/commit/149fb0a))
|
||||
* feat: implement peer reconciliation job for BGP peers ([3b17228](http://192.168.100.56:3000/denozord/EvoBGP/commit/3b17228))
|
||||
* feat: implement revision retention settings and pruning logic ([4f50350](http://192.168.100.56:3000/denozord/EvoBGP/commit/4f50350))
|
||||
* feat: implement theme selection and automatic theme application based on user preference. Update App ([b70a643](http://192.168.100.56:3000/denozord/EvoBGP/commit/b70a643))
|
||||
* feat: implement versioning and release management in the project ([bb334b1](http://192.168.100.56:3000/denozord/EvoBGP/commit/bb334b1))
|
||||
* feat: improve BGP protocol summary handling by introducing isBGPProtocolSummaryRow function. Update ([399622c](http://192.168.100.56:3000/denozord/EvoBGP/commit/399622c))
|
||||
* feat: improve job detail UI with enhanced spacing and layout adjustments. Update table cell classes ([97908b5](http://192.168.100.56:3000/denozord/EvoBGP/commit/97908b5))
|
||||
* feat: improve peer speaker assignment UX in network settings ([f877ec8](http://192.168.100.56:3000/denozord/EvoBGP/commit/f877ec8))
|
||||
* feat: improve UI components with enhanced overflow handling and layout adjustments. Update card and ([0ca5542](http://192.168.100.56:3000/denozord/EvoBGP/commit/0ca5542))
|
||||
* feat: improve UI layout and responsiveness in module and operations pages. Refactor component struct ([233f29b](http://192.168.100.56:3000/denozord/EvoBGP/commit/233f29b))
|
||||
* feat: redesign settings page with structured controls ([2da6d49](http://192.168.100.56:3000/denozord/EvoBGP/commit/2da6d49))
|
||||
* feat: refactor materialization logic to group static routes by community in the refresh pipeline. In ([1c5a9c9](http://192.168.100.56:3000/denozord/EvoBGP/commit/1c5a9c9))
|
||||
* feat: refactor operations page to enhance UI and component structure. Remove unused card components ([88226f6](http://192.168.100.56:3000/denozord/EvoBGP/commit/88226f6))
|
||||
* feat: refine BGP template handling and documentation updates. Remove local IP requirements in BGP te ([6266a39](http://192.168.100.56:3000/denozord/EvoBGP/commit/6266a39))
|
||||
* feat: refine job detail UI with improved layout and scrolling capabilities. Enhance spacing and over ([57c09ac](http://192.168.100.56:3000/denozord/EvoBGP/commit/57c09ac))
|
||||
* feat: update BGP community structure and related documentation. Refactor BGP community handling by r ([a2cbfac](http://192.168.100.56:3000/denozord/EvoBGP/commit/a2cbfac))
|
||||
* feat: update BGP template configuration and OpenAPI documentation. Change import settings from 'all' ([133ea93](http://192.168.100.56:3000/denozord/EvoBGP/commit/133ea93))
|
||||
* feat: update BIRD installation process to build from source. Modify CI workflow to ensure BIRD 2.14 ([e2002ba](http://192.168.100.56:3000/denozord/EvoBGP/commit/e2002ba))
|
||||
* feat: update CI configuration and Dockerfiles for improved build efficiency ([80229b3](http://192.168.100.56:3000/denozord/EvoBGP/commit/80229b3))
|
||||
* feat: update collectModulePrefixRows to support prior snapshots and enhance CDN/domain prefix collec ([ee364c8](http://192.168.100.56:3000/denozord/EvoBGP/commit/ee364c8))
|
||||
* feat: update Go module dependencies and enhance DNS resolution in refresh pipeline. Upgrade Go versi ([655d750](http://192.168.100.56:3000/denozord/EvoBGP/commit/655d750))
|
||||
* feat: update OpenAPI documentation and internal logic for BIRD settings. Enhance the description of ([62bf987](http://192.168.100.56:3000/denozord/EvoBGP/commit/62bf987))
|
||||
* feat: update RevisionDiff type and enhance OperationsDiffTab component for better diff handling. Int ([4aaaa30](http://192.168.100.56:3000/denozord/EvoBGP/commit/4aaaa30))
|
||||
* feat: update Traefik deployment configuration for Let's Encrypt and logging ([39ba976](http://192.168.100.56:3000/denozord/EvoBGP/commit/39ba976))
|
||||
* docs: add router-lists-ui integration documentation to README ([b7a8aab](http://192.168.100.56:3000/denozord/EvoBGP/commit/b7a8aab))
|
||||
* docs: add Web UI section to EvoBGP architecture plan, detailing Svelte and shadcn-svelte integration ([272542b](http://192.168.100.56:3000/denozord/EvoBGP/commit/272542b))
|
||||
* docs: enhance EvoBGP architecture plan with new risk mitigation strategies, testing matrix for BIRD2 ([3992d01](http://192.168.100.56:3000/denozord/EvoBGP/commit/3992d01))
|
||||
* docs: enhance README and CI workflow documentation for Docker image building and publishing process, ([9eb3e33](http://192.168.100.56:3000/denozord/EvoBGP/commit/9eb3e33))
|
||||
* docs: enhance README and CI workflow to clarify Docker image build conditions and Gitea Container Re ([c6687b2](http://192.168.100.56:3000/denozord/EvoBGP/commit/c6687b2))
|
||||
* docs: openapi.html со встроенным Redoc; инструкция для Gitea и скрипт сборки ([a754e1d](http://192.168.100.56:3000/denozord/EvoBGP/commit/a754e1d))
|
||||
* docs: update AGENTS and README to include guidelines for Conventional Commits ([4c23232](http://192.168.100.56:3000/denozord/EvoBGP/commit/4c23232))
|
||||
* docs: update AGENTS and README with engineering rules and guidelines ([aff27e8](http://192.168.100.56:3000/denozord/EvoBGP/commit/aff27e8))
|
||||
* docs: update architecture and API documentation to clarify job processing, in-memory registry usage, ([acc0608](http://192.168.100.56:3000/denozord/EvoBGP/commit/acc0608))
|
||||
* docs: update EvoBGP architecture plan with detailed REST API section, including general agreements, ([1a86d6c](http://192.168.100.56:3000/denozord/EvoBGP/commit/1a86d6c))
|
||||
* docs: update EvoBGP architecture plan with new repository structure, refined sections, and detailed ([4480d64](http://192.168.100.56:3000/denozord/EvoBGP/commit/4480d64))
|
||||
* docs: update README and CI workflow to clarify Docker workspace mounting for bird2 job ([6be46db](http://192.168.100.56:3000/denozord/EvoBGP/commit/6be46db))
|
||||
* docs: update README and CI workflow to clarify Gitea Registry login process and improve Docker image ([f1b33b9](http://192.168.100.56:3000/denozord/EvoBGP/commit/f1b33b9))
|
||||
* docs: update README and Docker Compose configurations to clarify usage of pre-built images from the ([7fac79c](http://192.168.100.56:3000/denozord/EvoBGP/commit/7fac79c))
|
||||
* docs: update README to include information about the EvoBGP web interface, linking to quickstart and ([5d21f01](http://192.168.100.56:3000/denozord/EvoBGP/commit/5d21f01))
|
||||
* docs: статическая Redoc-страница OpenAPI (для просмотра в Gitea без встроенного рендера) ([5c9d2e2](http://192.168.100.56:3000/denozord/EvoBGP/commit/5c9d2e2))
|
||||
* docs: убрать типографское тире и невидимый Unicode из текстов API ([fbe9cd3](http://192.168.100.56:3000/denozord/EvoBGP/commit/fbe9cd3))
|
||||
* refactor: adjust BootstrapWorkers function call in server.go to change the order of returned values, ([032fa99](http://192.168.100.56:3000/denozord/EvoBGP/commit/032fa99))
|
||||
* refactor: consolidate module interval display logic and improve edit form handling ([1f85654](http://192.168.100.56:3000/denozord/EvoBGP/commit/1f85654))
|
||||
* refactor: enhance bird metrics polling with context support ([f6b94a4](http://192.168.100.56:3000/denozord/EvoBGP/commit/f6b94a4))
|
||||
* refactor: enhance CI workflow for granular change detection by module and improve idempotency key ge ([54eaad3](http://192.168.100.56:3000/denozord/EvoBGP/commit/54eaad3))
|
||||
* refactor: enhance job status checks in worker tests ([6107c3e](http://192.168.100.56:3000/denozord/EvoBGP/commit/6107c3e))
|
||||
* refactor: enhance JSON struct tags for various data models in backend and memory store. Update field ([4a860a0](http://192.168.100.56:3000/denozord/EvoBGP/commit/4a860a0))
|
||||
* refactor: enhance module display and input handling in module pages ([25374a6](http://192.168.100.56:3000/denozord/EvoBGP/commit/25374a6))
|
||||
* refactor: enhance module interval label logic and add reset buttons in edit forms ([b99fc17](http://192.168.100.56:3000/denozord/EvoBGP/commit/b99fc17))
|
||||
* refactor: improve code consistency and formatting across components ([c263fd5](http://192.168.100.56:3000/denozord/EvoBGP/commit/c263fd5))
|
||||
* refactor: improve handling of deployable fragments in ApplyRevision and buildPreviewFragments functi ([6932271](http://192.168.100.56:3000/denozord/EvoBGP/commit/6932271))
|
||||
* refactor: improve module save functionality and nullable value handling ([05ec176](http://192.168.100.56:3000/denozord/EvoBGP/commit/05ec176))
|
||||
* refactor: improve PATCH handling for module updates with nullable field support ([e700f90](http://192.168.100.56:3000/denozord/EvoBGP/commit/e700f90))
|
||||
* refactor: optimize job listing and counting logic for concurrency safety. Separate tenant filtering ([d83efe2](http://192.168.100.56:3000/denozord/EvoBGP/commit/d83efe2))
|
||||
* refactor: phase 2 structural alignment — reports, importer, nodecli, pagination ([250cdea](http://192.168.100.56:3000/denozord/EvoBGP/commit/250cdea))
|
||||
* refactor: remove strict bind configuration from BGP templates and update related logic. Eliminate 's ([482eeb1](http://192.168.100.56:3000/denozord/EvoBGP/commit/482eeb1))
|
||||
* refactor: streamline Docker build process in CI configuration and documentation ([6025f38](http://192.168.100.56:3000/denozord/EvoBGP/commit/6025f38))
|
||||
* refactor: streamline edit form handling for community and DoH profile selections ([1765ab8](http://192.168.100.56:3000/denozord/EvoBGP/commit/1765ab8))
|
||||
* refactor: streamline module refresh process and enhance revision handling ([10e2415](http://192.168.100.56:3000/denozord/EvoBGP/commit/10e2415))
|
||||
* refactor: switch BIRD installation from source to Ubuntu package. Update CI workflow and Dockerfiles ([0b3ceaa](http://192.168.100.56:3000/denozord/EvoBGP/commit/0b3ceaa))
|
||||
* refactor: update AS entry handling in API and database to support ASN-only entries. Remove prefix fi ([1db6b5b](http://192.168.100.56:3000/denozord/EvoBGP/commit/1db6b5b))
|
||||
* refactor: update Docker build context and paths in CI configuration and documentation ([7d52a4a](http://192.168.100.56:3000/denozord/EvoBGP/commit/7d52a4a))
|
||||
* refactor: update Docker build variable syntax in CI configuration and documentation ([27e01d0](http://192.168.100.56:3000/denozord/EvoBGP/commit/27e01d0))
|
||||
* refactor: update job kind display logic in schedule page ([dc1f4a5](http://192.168.100.56:3000/denozord/EvoBGP/commit/dc1f4a5))
|
||||
* refactor: update ListModules and GetModule methods in Postgres repository to include cron expression ([73d0003](http://192.168.100.56:3000/denozord/EvoBGP/commit/73d0003))
|
||||
* refactor: update Switch component styles and structure for improved accessibility and responsiveness ([d4282c2](http://192.168.100.56:3000/denozord/EvoBGP/commit/d4282c2))
|
||||
* refactor: update worker processes in EvoBGP to accept dependencies for shared store and job registry ([b7968db](http://192.168.100.56:3000/denozord/EvoBGP/commit/b7968db))
|
||||
* ci: add conditional job for OpenAPI linting based on file changes; update README with workflow detai ([3adfc49](http://192.168.100.56:3000/denozord/EvoBGP/commit/3adfc49))
|
||||
* ci: phase 4 automation — web job, lint-httpapi, golangci ([64516c3](http://192.168.100.56:3000/denozord/EvoBGP/commit/64516c3))
|
||||
* ci: update README and CI workflow to improve bird2 job installation process and clarify Docker usage ([eddc6b8](http://192.168.100.56:3000/denozord/EvoBGP/commit/eddc6b8))
|
||||
* chore: phase 3 code quality — pipeline prefixes, godoc baseline ([ea65451](http://192.168.100.56:3000/denozord/EvoBGP/commit/ea65451))
|
||||
* chore: update CI configuration to disable filesystem entitlement for Docker builds ([9ab7de6](http://192.168.100.56:3000/denozord/EvoBGP/commit/9ab7de6))
|
||||
* chore: update package dependencies and enhance AppShell component with new navigation items and tool ([7d85fef](http://192.168.100.56:3000/denozord/EvoBGP/commit/7d85fef))
|
||||
* chore: upgrade Go version to 1.24 in Dockerfiles for evobgp-agent and gobinary. This change ensures ([4ba5b03](http://192.168.100.56:3000/denozord/EvoBGP/commit/4ba5b03))
|
||||
* fix: adjust Postgres resource limits and healthcheck parameters. Increase memory limit to 256M and m ([20e674c](http://192.168.100.56:3000/denozord/EvoBGP/commit/20e674c))
|
||||
* fix: improve input handling and validation for settings fields ([1386b63](http://192.168.100.56:3000/denozord/EvoBGP/commit/1386b63))
|
||||
* fix: improve sidebar and navigation layout in AppShell component ([9f02128](http://192.168.100.56:3000/denozord/EvoBGP/commit/9f02128))
|
||||
* fix: update BGP configuration in test scenarios to use new IPv6 addresses ([9fd9745](http://192.168.100.56:3000/denozord/EvoBGP/commit/9fd9745))
|
||||
* fix: update bird build script and Dockerfile to include libncurses dependency ([0cb5a7d](http://192.168.100.56:3000/denozord/EvoBGP/commit/0cb5a7d))
|
||||
* fix: update bird build script and Dockerfile to include readline dependency ([35ed79b](http://192.168.100.56:3000/denozord/EvoBGP/commit/35ed79b))
|
||||
* fix: update bird build script and Dockerfile to remove readline dependency ([fefadac](http://192.168.100.56:3000/denozord/EvoBGP/commit/fefadac))
|
||||
* fix: update deployment configuration for Traefik and secure Web UI ([00bd037](http://192.168.100.56:3000/denozord/EvoBGP/commit/00bd037))
|
||||
* fix: update Docker build commands in CI configuration and documentation ([b5061a5](http://192.168.100.56:3000/denozord/EvoBGP/commit/b5061a5))
|
||||
* fix(httpapi): phase 1 compliance — ERR-01, SEC-04, CDN client, scheduler docs ([1dd7135](http://192.168.100.56:3000/denozord/EvoBGP/commit/1dd7135))
|
||||
* test: add CDN prefetch tests for 304 responses and snapshot handling ([a536a2d](http://192.168.100.56:3000/denozord/EvoBGP/commit/a536a2d))
|
||||
* test: add validation for 'strict bind on' in BGP rendering tests. Enhance BGP test cases to ensure ' ([dc5e20e](http://192.168.100.56:3000/denozord/EvoBGP/commit/dc5e20e))
|
||||
* docker: refactor cache handling in Docker bake configuration ([5e59a1c](http://192.168.100.56:3000/denozord/EvoBGP/commit/5e59a1c))
|
||||
* docker: simplify web image targets in Docker bake configuration ([765a805](http://192.168.100.56:3000/denozord/EvoBGP/commit/765a805))
|
||||
* docker: update web image build process and README ([92f6de8](http://192.168.100.56:3000/denozord/EvoBGP/commit/92f6de8))
|
||||
* web(ui): app layout — sidebar, mobile sheet, topbar, PageHeader ([2d78c81](http://192.168.100.56:3000/denozord/EvoBGP/commit/2d78c81))
|
||||
* web(ui): AppDataTable pattern and modules pilot ([b992301](http://192.168.100.56:3000/denozord/EvoBGP/commit/b992301))
|
||||
* web(ui): design tokens — spacing and component scale ([ac635e9](http://192.168.100.56:3000/denozord/EvoBGP/commit/ac635e9))
|
||||
* web(ui): feedback — confirm dialog, skeletons, README ([87309cf](http://192.168.100.56:3000/denozord/EvoBGP/commit/87309cf))
|
||||
* web(ui): form patterns — FormField, formsnap, directories pilot ([77a2cfd](http://192.168.100.56:3000/denozord/EvoBGP/commit/77a2cfd))
|
||||
* web(ui): foundation — ui/core layout, shadcn primitives, notify ([00a2a44](http://192.168.100.56:3000/denozord/EvoBGP/commit/00a2a44))
|
||||
* web(ui): migrate dashboard, schedule, monitoring to ui patterns ([57dcf30](http://192.168.100.56:3000/denozord/EvoBGP/commit/57dcf30))
|
||||
* web(ui): migrate network to ui patterns ([3a3056b](http://192.168.100.56:3000/denozord/EvoBGP/commit/3a3056b))
|
||||
* web(ui): migrate operations and module detail to ui patterns ([1f9930d](http://192.168.100.56:3000/denozord/EvoBGP/commit/1f9930d))
|
||||
* web(ui): migrate settings to ui patterns ([9808aca](http://192.168.100.56:3000/denozord/EvoBGP/commit/9808aca))
|
||||
* Enhance EvoBGP architecture plan by refining the overview, updating todos with detailed descriptions ([30efdbf](http://192.168.100.56:3000/denozord/EvoBGP/commit/30efdbf))
|
||||
* init ([cbf3aaa](http://192.168.100.56:3000/denozord/EvoBGP/commit/cbf3aaa))
|
||||
* Refine EvoBGP architecture plan with updated database schema details, improved descriptions for comp ([431ef3e](http://192.168.100.56:3000/denozord/EvoBGP/commit/431ef3e))
|
||||
* Update EvoBGP architecture plan with new overview and todos. Refined descriptions for control-plane ([31ff5bb](http://192.168.100.56:3000/denozord/EvoBGP/commit/31ff5bb))
|
||||
@@ -6,6 +6,7 @@ Control plane для управления префиксами, модулями
|
||||
|
||||
| Документ | Содержание |
|
||||
|----------|------------|
|
||||
| [AGENTS.md](AGENTS.md) | Краткая карта репозитория и советы для ИИ-агентов (экономия контекста) |
|
||||
| [docs/README.md](docs/README.md) | Оглавление и навигация по разделам |
|
||||
| [docs/overview.md](docs/overview.md) | Ключевые возможности продукта |
|
||||
| [docs/quickstart.md](docs/quickstart.md) | Быстрый запуск (Docker, локально, фронтенд) |
|
||||
@@ -43,4 +44,12 @@ docker compose --profile reference up -d
|
||||
- **Go:** модуль `evobgp`, точки входа в `cmd/`.
|
||||
- **Веб:** SvelteKit в каталоге `web/` (см. [web/README.md](web/README.md)).
|
||||
|
||||
## Версионирование и релизы
|
||||
|
||||
Версии определяются автоматически из Conventional Commits при merge в `main` (semantic-release на Gitea Actions). Первая версия — **1.0.0**; ручной bump не нужен.
|
||||
|
||||
- [docs/releasing.md](docs/releasing.md) — пайплайн, commit conventions, секреты CI
|
||||
- API: `GET /version` и `GET /v1/version` (поле `version`)
|
||||
- Docker-образы: теги `latest`, `vX.Y.Z`, `X.Y.Z` — в **том же CI run**, что и релиз (job `release`)
|
||||
|
||||
Лицензия и условия использования — по политике владельца репозитория.
|
||||
@@ -6,8 +6,10 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"evobgp/internal/agentserver"
|
||||
"evobgp/internal/birdfmt"
|
||||
)
|
||||
|
||||
@@ -17,12 +19,14 @@ func main() {
|
||||
socket := flag.String("socket", "", "optional birdc control socket (-s)")
|
||||
timeout := flag.Duration("timeout", 30*time.Second, "timeout for bird/birdc")
|
||||
watchEvery := flag.Duration("watch-interval", 30*time.Second, "for watch: interval between birdc configure")
|
||||
listen := flag.String("listen", "", "for serve: listen address (default :8443 or EVOBGP_AGENT_LISTEN)")
|
||||
flag.Usage = func() {
|
||||
fmt.Fprintf(os.Stderr, "Usage: %s [flags] <command>\n", os.Args[0])
|
||||
fmt.Fprintf(os.Stderr, "Commands:\n")
|
||||
fmt.Fprintf(os.Stderr, " parse-check <path/to/bird.conf> run bird -c <path> -p (syntax check)\n")
|
||||
fmt.Fprintf(os.Stderr, " configure run birdc configure (reload running BIRD)\n")
|
||||
fmt.Fprintf(os.Stderr, " watch periodically run birdc configure (compose sidecar)\n")
|
||||
fmt.Fprintf(os.Stderr, " serve Panel→Node HTTP API (POST /v1/agent/sync)\n")
|
||||
flag.PrintDefaults()
|
||||
}
|
||||
flag.Parse()
|
||||
@@ -40,9 +44,21 @@ func main() {
|
||||
ctl.Birdc = *birdc
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||
defer cancel()
|
||||
switch args[0] {
|
||||
case "serve":
|
||||
runServe(*listen, *timeout)
|
||||
case "parse-check", "configure", "watch":
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||
defer cancel()
|
||||
runBirdCommand(ctx, args, ctl, *watchEvery, *timeout)
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "unknown command: %s\n", args[0])
|
||||
flag.Usage()
|
||||
os.Exit(2)
|
||||
}
|
||||
}
|
||||
|
||||
func runBirdCommand(ctx context.Context, args []string, ctl *birdfmt.BirdCtl, watchEvery, timeout time.Duration) {
|
||||
switch args[0] {
|
||||
case "parse-check":
|
||||
if len(args) != 2 {
|
||||
@@ -63,23 +79,51 @@ func main() {
|
||||
os.Exit(1)
|
||||
}
|
||||
case "watch":
|
||||
if *watchEvery <= 0 {
|
||||
if watchEvery <= 0 {
|
||||
fmt.Fprintln(os.Stderr, "watch-interval must be > 0")
|
||||
os.Exit(2)
|
||||
}
|
||||
log.Printf("evobgp-agent watch: birdc configure every %s (socket=%q)", *watchEvery, *socket)
|
||||
log.Printf("evobgp-agent watch: birdc configure every %s (socket=%q)", watchEvery, ctl.Socket)
|
||||
for {
|
||||
cctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||
cctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
err := ctl.Configure(cctx)
|
||||
cancel()
|
||||
if err != nil {
|
||||
log.Printf("evobgp-agent watch: configure: %v", err)
|
||||
}
|
||||
time.Sleep(*watchEvery)
|
||||
time.Sleep(watchEvery)
|
||||
}
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "unknown command: %s\n", args[0])
|
||||
flag.Usage()
|
||||
}
|
||||
}
|
||||
|
||||
func runServe(listenFlag string, syncTimeout time.Duration) {
|
||||
cfg, err := agentserver.ConfigFromEnv()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(2)
|
||||
}
|
||||
if listenFlag != "" {
|
||||
cfg.Listen = listenFlag
|
||||
}
|
||||
if syncTimeout > 0 {
|
||||
cfg.SyncTimeout = syncTimeout
|
||||
}
|
||||
var mu sync.Mutex
|
||||
var lastRev string
|
||||
var lastAt time.Time
|
||||
cfg.LastSync = func() (string, time.Time) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return lastRev, lastAt
|
||||
}
|
||||
cfg.OnSyncSuccess = func(rev string) {
|
||||
mu.Lock()
|
||||
lastRev = rev
|
||||
lastAt = time.Now().UTC()
|
||||
mu.Unlock()
|
||||
}
|
||||
if err := agentserver.ListenAndServe(cfg); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
+12
-6
@@ -19,6 +19,7 @@ import (
|
||||
"evobgp/internal/platform"
|
||||
"evobgp/internal/render"
|
||||
"evobgp/internal/scheduler"
|
||||
"evobgp/internal/version"
|
||||
)
|
||||
|
||||
// microVPS entrypoint: один процесс — HTTP API и фоновые воркеры scheduler, ingest, render, deploy (общий store и jobs.Registry).
|
||||
@@ -37,7 +38,7 @@ func main() {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer srv.Close()
|
||||
observability.SetBuildInfo("0.1.0", strings.TrimSpace(os.Getenv("EVOBGP_GIT_SHA")))
|
||||
observability.SetBuildInfo(version.Version, version.GitSHA)
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
@@ -51,11 +52,15 @@ func main() {
|
||||
go render.Run(ctx, renderDeps)
|
||||
go deploy.Run(ctx, deployDeps)
|
||||
|
||||
startBirdMetricsPoller()
|
||||
startBirdMetricsPoller(ctx)
|
||||
|
||||
httpSrv := &http.Server{
|
||||
Addr: cfg.HTTPAddr,
|
||||
Handler: srv.Handler(),
|
||||
Addr: cfg.HTTPAddr,
|
||||
Handler: srv.Handler(),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 60 * time.Second,
|
||||
WriteTimeout: 120 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
go func() {
|
||||
svc := platform.ServiceName("evobgp-all")
|
||||
@@ -75,7 +80,7 @@ func main() {
|
||||
log.Printf("%s stopped", platform.ServiceName("evobgp-all"))
|
||||
}
|
||||
|
||||
func startBirdMetricsPoller() {
|
||||
func startBirdMetricsPoller(ctx context.Context) {
|
||||
sock := strings.TrimSpace(os.Getenv("EVOBGP_BIRDC_SOCKET"))
|
||||
if sock == "" {
|
||||
return
|
||||
@@ -85,11 +90,12 @@ func startBirdMetricsPoller() {
|
||||
interval = d
|
||||
}
|
||||
bin := strings.TrimSpace(os.Getenv("EVOBGP_BIRDC_BIN"))
|
||||
observability.StartBirdProtocolsPoller(sock, bin, interval,
|
||||
observability.StartBirdProtocolsPoller(ctx, sock, bin, interval,
|
||||
func(ctx context.Context, socket, birdcBin string) (string, error) {
|
||||
return birdfmt.ShowProtocols(ctx, socket, birdcBin)
|
||||
},
|
||||
birdfmt.CountEstablishedBGPSessions,
|
||||
birdfmt.ParseBGPProtocolStates,
|
||||
)
|
||||
log.Printf("birdc protocols poller enabled (socket=%s interval=%s)", sock, interval)
|
||||
}
|
||||
+14
-8
@@ -15,6 +15,7 @@ import (
|
||||
"evobgp/internal/httpapi"
|
||||
"evobgp/internal/observability"
|
||||
"evobgp/internal/platform"
|
||||
"evobgp/internal/version"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -34,15 +35,19 @@ func main() {
|
||||
}
|
||||
defer srv.Close()
|
||||
|
||||
observability.SetBuildInfo("0.1.0", strings.TrimSpace(os.Getenv("EVOBGP_GIT_SHA")))
|
||||
startBirdMetricsPoller()
|
||||
|
||||
observability.SetBuildInfo(version.Version, version.GitSHA)
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
startBirdMetricsPoller(ctx)
|
||||
|
||||
httpSrv := &http.Server{
|
||||
Addr: cfg.HTTPAddr,
|
||||
Handler: srv.Handler(),
|
||||
Addr: cfg.HTTPAddr,
|
||||
Handler: srv.Handler(),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 60 * time.Second,
|
||||
WriteTimeout: 120 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
go func() {
|
||||
svc := platform.ServiceName("evobgp-api")
|
||||
@@ -52,7 +57,7 @@ func main() {
|
||||
tid, mCDN, mIP, rev, sp := srv.Store().DemoIDs()
|
||||
log.Printf("demo tenant=%s module_cdn=%s module_ip_ranges=%s revision=%s speaker=%s", tid, mCDN, mIP, rev, sp)
|
||||
log.Printf("example: EVOBGP_API_KEYS=op|%s|operator,node|%s|node", tid, tid)
|
||||
log.Printf("with EVOBGP_DEV_INSECURE=1 use Authorization: Bearer dev (operator, demo tenant only)")
|
||||
log.Printf("demo auth: Authorization: Bearer dev (operator, demo tenant only)")
|
||||
}
|
||||
if err := httpSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatal(err)
|
||||
@@ -68,7 +73,7 @@ func main() {
|
||||
log.Printf("%s stopped", platform.ServiceName("evobgp-api"))
|
||||
}
|
||||
|
||||
func startBirdMetricsPoller() {
|
||||
func startBirdMetricsPoller(ctx context.Context) {
|
||||
sock := strings.TrimSpace(os.Getenv("EVOBGP_BIRDC_SOCKET"))
|
||||
if sock == "" {
|
||||
return
|
||||
@@ -78,11 +83,12 @@ func startBirdMetricsPoller() {
|
||||
interval = d
|
||||
}
|
||||
bin := strings.TrimSpace(os.Getenv("EVOBGP_BIRDC_BIN"))
|
||||
observability.StartBirdProtocolsPoller(sock, bin, interval,
|
||||
observability.StartBirdProtocolsPoller(ctx, sock, bin, interval,
|
||||
func(ctx context.Context, socket, birdcBin string) (string, error) {
|
||||
return birdfmt.ShowProtocols(ctx, socket, birdcBin)
|
||||
},
|
||||
birdfmt.CountEstablishedBGPSessions,
|
||||
birdfmt.ParseBGPProtocolStates,
|
||||
)
|
||||
log.Printf("birdc protocols poller enabled (socket=%s interval=%s)", sock, interval)
|
||||
}
|
||||
+3
-228
@@ -1,240 +1,15 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"evobgp/internal/birdfmt"
|
||||
"evobgp/internal/bundle"
|
||||
"evobgp/internal/signing"
|
||||
"evobgp/internal/nodecli"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
usage()
|
||||
os.Exit(2)
|
||||
}
|
||||
switch os.Args[1] {
|
||||
case "pull-bundle":
|
||||
os.Exit(cmdPullBundle(os.Args[2:]))
|
||||
case "verify-bundle":
|
||||
os.Exit(cmdVerifyBundle(os.Args[2:]))
|
||||
case "apply-bundle":
|
||||
os.Exit(cmdApplyBundle(os.Args[2:]))
|
||||
default:
|
||||
usage()
|
||||
nodecli.Usage(os.Stderr)
|
||||
os.Exit(2)
|
||||
}
|
||||
}
|
||||
|
||||
func usage() {
|
||||
fmt.Fprintf(os.Stderr, `Usage:
|
||||
%s pull-bundle -base-url URL -token TOKEN -speaker-id ID [-revision-id ID] [-o path]
|
||||
%s verify-bundle -f bundle.tar.gz (-pubkey-base64 B64 | -pubkey-hex HEX)
|
||||
%s apply-bundle -f bundle.tar.gz -extract-dir DIR (-pubkey-base64 B64 | -pubkey-hex HEX)
|
||||
[-bird PATH] [-birdc PATH] [-socket PATH] [-timeout DURATION]
|
||||
|
||||
apply-bundle verifies, extracts, runs bird -p on main bird.conf, then birdc configure.
|
||||
`, os.Args[0], os.Args[0], os.Args[0])
|
||||
}
|
||||
|
||||
func cmdPullBundle(args []string) int {
|
||||
fs := flag.NewFlagSet("pull-bundle", flag.ExitOnError)
|
||||
base := fs.String("base-url", "", "control plane base URL, e.g. http://localhost:8080")
|
||||
token := fs.String("token", "", "Bearer token (node role)")
|
||||
speaker := fs.String("speaker-id", "", "bgp_speaker id")
|
||||
revision := fs.String("revision-id", "", "revision to fetch (empty = latest pointer)")
|
||||
out := fs.String("o", "bundle.tar.gz", "output file")
|
||||
_ = fs.Parse(args)
|
||||
|
||||
if strings.TrimSpace(*base) == "" || *token == "" || *speaker == "" {
|
||||
fmt.Fprintln(os.Stderr, "pull-bundle: -base-url, -token, -speaker-id are required")
|
||||
return 2
|
||||
}
|
||||
rev := strings.TrimSpace(*revision)
|
||||
if rev == "" {
|
||||
var err error
|
||||
rev, err = fetchLatestRevision(*base, *token, *speaker)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return 1
|
||||
}
|
||||
}
|
||||
body, err := fetchBundle(*base, *token, *speaker, rev)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return 1
|
||||
}
|
||||
if err := os.WriteFile(*out, body, 0o644); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return 1
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "wrote %s (revision %s)\n", *out, rev)
|
||||
return 0
|
||||
}
|
||||
|
||||
func fetchLatestRevision(base, token, speaker string) (string, error) {
|
||||
u := strings.TrimRight(base, "/") + "/v1/speakers/" + speaker + "/revisions/latest"
|
||||
req, err := http.NewRequest(http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
return "", fmt.Errorf("latest revision: %s: %s", resp.Status, strings.TrimSpace(string(b)))
|
||||
}
|
||||
var out struct {
|
||||
RevisionID string `json:"revision_id"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if out.RevisionID == "" {
|
||||
return "", fmt.Errorf("empty revision_id in response")
|
||||
}
|
||||
return out.RevisionID, nil
|
||||
}
|
||||
|
||||
func fetchBundle(base, token, speaker, revision string) ([]byte, error) {
|
||||
u := strings.TrimRight(base, "/") + "/v1/speakers/" + speaker + "/bundle/" + revision
|
||||
req, err := http.NewRequest(http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
return nil, fmt.Errorf("bundle: %s: %s", resp.Status, strings.TrimSpace(string(b)))
|
||||
}
|
||||
return io.ReadAll(resp.Body)
|
||||
}
|
||||
|
||||
func loadPubKey(pubB64, pubHex string) (ed25519.PublicKey, error) {
|
||||
switch {
|
||||
case strings.TrimSpace(pubB64) != "":
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(pubB64))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(raw) != ed25519.PublicKeySize {
|
||||
return nil, fmt.Errorf("pubkey-base64 must decode to %d bytes", ed25519.PublicKeySize)
|
||||
}
|
||||
return ed25519.PublicKey(raw), nil
|
||||
case strings.TrimSpace(pubHex) != "":
|
||||
return bundle.ParsePublicKeyHex(pubHex)
|
||||
default:
|
||||
return nil, fmt.Errorf("public key required")
|
||||
}
|
||||
}
|
||||
|
||||
func cmdVerifyBundle(args []string) int {
|
||||
fs := flag.NewFlagSet("verify-bundle", flag.ExitOnError)
|
||||
path := fs.String("f", "", "path to bundle.tar.gz")
|
||||
pubB64 := fs.String("pubkey-base64", "", "Ed25519 public key (base64)")
|
||||
pubHex := fs.String("pubkey-hex", "", "Ed25519 public key (64 hex chars)")
|
||||
_ = fs.Parse(args)
|
||||
|
||||
if *path == "" {
|
||||
fmt.Fprintln(os.Stderr, "verify-bundle: -f required")
|
||||
return 2
|
||||
}
|
||||
pub, err := loadPubKey(*pubB64, *pubHex)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return 2
|
||||
}
|
||||
raw, err := os.ReadFile(*path)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return 1
|
||||
}
|
||||
v, err := signing.VerifyGzippedTar(raw, pub)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return 1
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "ok: revision %s, %d payload files\n", v.Manifest.RevisionID, len(v.Files))
|
||||
return 0
|
||||
}
|
||||
|
||||
func cmdApplyBundle(args []string) int {
|
||||
fs := flag.NewFlagSet("apply-bundle", flag.ExitOnError)
|
||||
path := fs.String("f", "", "path to bundle.tar.gz")
|
||||
dir := fs.String("extract-dir", "", "directory to extract into")
|
||||
pubB64 := fs.String("pubkey-base64", "", "Ed25519 public key (base64)")
|
||||
pubHex := fs.String("pubkey-hex", "", "Ed25519 public key (64 hex chars)")
|
||||
bird := fs.String("bird", "", "bird binary (default PATH)")
|
||||
birdc := fs.String("birdc", "", "birdc binary (default PATH)")
|
||||
socket := fs.String("socket", "", "birdc -s socket path")
|
||||
timeout := fs.Duration("timeout", 30*time.Second, "timeout for bird/birdc")
|
||||
_ = fs.Parse(args)
|
||||
|
||||
if *path == "" || *dir == "" {
|
||||
fmt.Fprintln(os.Stderr, "apply-bundle: -f and -extract-dir required")
|
||||
return 2
|
||||
}
|
||||
pub, err := loadPubKey(*pubB64, *pubHex)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return 2
|
||||
}
|
||||
raw, err := os.ReadFile(*path)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return 1
|
||||
}
|
||||
v, err := signing.VerifyGzippedTar(raw, pub)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return 1
|
||||
}
|
||||
root := filepath.Clean(*dir)
|
||||
if err := os.MkdirAll(root, 0o755); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return 1
|
||||
}
|
||||
if err := bundle.WriteExtractedFiles(root, v); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return 1
|
||||
}
|
||||
mainRel := v.FindMainBirdConf()
|
||||
if mainRel == "" {
|
||||
fmt.Fprintln(os.Stderr, "bundle has no bird.conf path in manifest")
|
||||
return 1
|
||||
}
|
||||
mainPath := filepath.Join(root, filepath.FromSlash(strings.TrimPrefix(mainRel, "/")))
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||
defer cancel()
|
||||
ctl := &birdfmt.BirdCtl{Bird: *bird, Birdc: *birdc, Socket: *socket}
|
||||
if err := ctl.ParseCheck(ctx, mainPath); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return 1
|
||||
}
|
||||
if err := ctl.Configure(ctx); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return 1
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "applied revision %s (main config %s)\n", v.Manifest.RevisionID, mainPath)
|
||||
return 0
|
||||
os.Exit(nodecli.Run(os.Args[1:]))
|
||||
}
|
||||
@@ -41,6 +41,9 @@ func main() {
|
||||
|
||||
apiBase := strings.TrimSpace(os.Getenv("EVOBGP_CONTROL_PLANE_URL"))
|
||||
apiTok := strings.TrimSpace(os.Getenv("EVOBGP_SCHEDULER_BEARER"))
|
||||
if os.Getenv("EVOBGP_SCHEDULER_STANDALONE") == "1" && apiBase == "" {
|
||||
log.Fatal("evobgp-scheduler: EVOBGP_SCHEDULER_STANDALONE=1 requires EVOBGP_CONTROL_PLANE_URL and EVOBGP_SCHEDULER_BEARER (split deploy must not use in-process jobs.Registry)")
|
||||
}
|
||||
deps := &scheduler.Deps{
|
||||
Store: st,
|
||||
HTTP: &http.Client{Timeout: 45 * time.Second},
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/** @type {import('@commitlint/types').UserConfig} */
|
||||
module.exports = {
|
||||
extends: ['@commitlint/config-conventional'],
|
||||
plugins: [
|
||||
{
|
||||
rules: {
|
||||
'scope-no-commas': ({ scope }) => {
|
||||
if (scope && scope.includes(',')) {
|
||||
return [
|
||||
false,
|
||||
'scope must not contain commas (semantic-release will not parse the commit type)'
|
||||
];
|
||||
}
|
||||
return [true];
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
rules: {
|
||||
'scope-no-commas': [2, 'always']
|
||||
}
|
||||
};
|
||||
@@ -3,3 +3,6 @@
|
||||
|
||||
EVOBGP_REGISTRY=git.shts.su/denozord
|
||||
EVOBGP_IMAGE_TAG=latest
|
||||
|
||||
# Для защищенного Web UI (Traefik + Let's Encrypt + Cloudflare DNS challenge)
|
||||
# используйте второй файл рядом: .env.web-sec (шаблон: .env.web-sec.example)
|
||||
@@ -0,0 +1,11 @@
|
||||
# TLS для Traefik (profile production). Скопируйте в .env.remote-speaker-tls
|
||||
|
||||
# FQDN agent API (DNS only в Cloudflare → IP этой VPS)
|
||||
AGENT_DOMAIN=bgp-dc2.example.com
|
||||
|
||||
# Let's Encrypt + Cloudflare DNS challenge (как evobgp-edge на CP)
|
||||
LETSENCRYPT_EMAIL=ops@example.com
|
||||
CF_DNS_API_TOKEN=
|
||||
|
||||
# IP основного сервера (Panel) — единственный источник wake-up / health
|
||||
PANEL_IP_WHITELIST=203.0.113.1/32
|
||||
@@ -0,0 +1,22 @@
|
||||
# Скопируйте в .env.remote-speaker рядом с docker-compose.remote-speaker.yaml
|
||||
# Значения agent_secret и node token — из Web UI после создания спикера.
|
||||
|
||||
EVOBGP_REGISTRY=git.shts.su/denozord
|
||||
EVOBGP_IMAGE_TAG=latest
|
||||
|
||||
# Control plane (HTTPS в prod)
|
||||
EVOBGP_CONTROL_PLANE_URL=https://cp.example.com:8080
|
||||
|
||||
# Из карточки спикера в панели
|
||||
EVOBGP_SPEAKER_ID=00000000-0000-0000-0000-000000000001
|
||||
EVOBGP_AGENT_SECRET=change-me-from-ui-once
|
||||
EVOBGP_NODE_TOKEN=evobgp_node_token_from_access
|
||||
|
||||
# GET /v1/bundle/signing-public-key (operator) или env CP EVOBGP_BUNDLE_SEED_HEX
|
||||
EVOBGP_BUNDLE_PUBKEY_BASE64=
|
||||
|
||||
# Fallback polling (profile fallback)
|
||||
EVOBGP_SYNC_INTERVAL_SEC=300
|
||||
|
||||
# Lab profile plain — порт agent на хосте
|
||||
EVOBGP_AGENT_PORT=8443
|
||||
@@ -0,0 +1,24 @@
|
||||
# Standalone stack env (Linux): stack.microvps-full.yaml
|
||||
# Использование:
|
||||
# cp .env.stack.microvps-full.example .env.stack.microvps-full
|
||||
# docker compose --env-file .env.stack.microvps-full -f stack.microvps-full.yaml up -d
|
||||
|
||||
# Образы EvoBGP
|
||||
EVOBGP_REGISTRY=git.shts.su/denozord
|
||||
EVOBGP_IMAGE_TAG=latest
|
||||
|
||||
# Защищенный Web UI (Traefik + Let's Encrypt + Cloudflare DNS challenge)
|
||||
WEBUI_DOMAIN=bgp.shz.su
|
||||
WEBUI_IP_WHITELIST=109.174.26.78/32,87.103.241.8/32
|
||||
LETSENCRYPT_EMAIL=admin@shz.su
|
||||
CF_DNS_API_TOKEN=cfut_3D1i0MNBVX6MNSsjcFytsfSlyB4B15t7H3DYXuzq22011588
|
||||
|
||||
# Auto-updater (проверка registry образов и точечный restart контейнеров)
|
||||
# 0 = выключен, 1 = включен
|
||||
AUTO_UPDATE_ENABLED=0
|
||||
# Интервал проверки обновлений (сек), минимум 30
|
||||
AUTO_UPDATE_INTERVAL_SEC=300
|
||||
# Сервисы для автообновления (через запятую)
|
||||
AUTO_UPDATE_SERVICES=evobgp-all,evobgp-web
|
||||
# Защищенные сервисы, которые updater никогда не перезапускает
|
||||
AUTO_UPDATE_PROTECTED_SERVICES=bird2
|
||||
@@ -0,0 +1,16 @@
|
||||
# Параметры защищенного Web UI (Traefik + Let's Encrypt DNS challenge через Cloudflare).
|
||||
# Используйте вместе с deploy/compose/.env:
|
||||
# docker compose --env-file .env --env-file .env.web-sec ...
|
||||
|
||||
# FQDN для Web UI (A/AAAA запись должна указывать на VPS; Cloudflare: DNS only).
|
||||
WEBUI_DOMAIN=bgp.example.com
|
||||
|
||||
# Разрешенные IP/CIDR (через запятую).
|
||||
# Пример: один IP + подсеть офиса.
|
||||
WEBUI_IP_WHITELIST=203.0.113.10/32,198.51.100.0/24
|
||||
|
||||
# Email для ACME аккаунта Let's Encrypt.
|
||||
LETSENCRYPT_EMAIL=admin@example.com
|
||||
|
||||
# Cloudflare API token с правами Zone:DNS:Edit только на нужную зону.
|
||||
CF_DNS_API_TOKEN=replace_me
|
||||
@@ -7,6 +7,7 @@
|
||||
# docker compose -f docker-compose.yaml -f docker-compose.microvps-full.yaml --profile microvps-full down
|
||||
#
|
||||
# Лимиты под хост ~1 ГиБ: сумма лимитов контейнеров ~800 МиБ + запас ОС/Docker. При OOM увеличьте RAM VPS или уберите prometheus/nats из профиля (отдельная правка compose).
|
||||
# Postgres ниже ~240–256 МиБ часто не успевает пройти healthcheck / падает по памяти — не уменьшайте postgres без tuned postgresql.conf.
|
||||
|
||||
services:
|
||||
evobgp-all:
|
||||
@@ -23,7 +24,7 @@ services:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.45"
|
||||
memory: 180M
|
||||
memory: 256M
|
||||
|
||||
bird2:
|
||||
deploy:
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
# Удалённый BGP-спикер (Remnawave-style): bird2 + evobgp-agent + Traefik (LE).
|
||||
# См. docs/remote-speakers.md
|
||||
#
|
||||
# cp .env.remote-speaker.example .env.remote-speaker
|
||||
# cp .env.remote-speaker-tls.example .env.remote-speaker-tls
|
||||
# docker compose -f docker-compose.remote-speaker.yaml \
|
||||
# --env-file .env.remote-speaker --env-file .env.remote-speaker-tls up -d
|
||||
#
|
||||
# Profiles:
|
||||
# production (default) — bird2 host + agent + evobgp-edge
|
||||
# plain — bird2 + agent без Traefik (lab)
|
||||
# fallback — + sync-bundle polling
|
||||
|
||||
name: evobgp-remote-speaker
|
||||
|
||||
x-logging: &default-logging
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
services:
|
||||
bird2:
|
||||
profiles: ["production", "plain", "fallback"]
|
||||
image: ${EVOBGP_REGISTRY:-git.shts.su/denozord}/evobgp-bird2:${EVOBGP_IMAGE_TAG:-latest}
|
||||
restart: unless-stopped
|
||||
network_mode: host
|
||||
cap_add:
|
||||
- NET_ADMIN
|
||||
# sysctls нельзя с network_mode: host — включите ip_forward на VPS (см. docs/remote-speakers.md)
|
||||
volumes:
|
||||
- bird_etc:/etc/bird
|
||||
- bird_run:/run/bird
|
||||
logging: *default-logging
|
||||
|
||||
evobgp-agent:
|
||||
profiles: ["production"]
|
||||
image: ${EVOBGP_REGISTRY:-git.shts.su/denozord}/evobgp-agent:${EVOBGP_IMAGE_TAG:-latest}
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- bird2
|
||||
cap_add:
|
||||
- NET_ADMIN
|
||||
environment:
|
||||
EVOBGP_AGENT_LISTEN: ":8443"
|
||||
EVOBGP_AGENT_SECRET: ${EVOBGP_AGENT_SECRET:?set EVOBGP_AGENT_SECRET}
|
||||
EVOBGP_CONTROL_PLANE_URL: ${EVOBGP_CONTROL_PLANE_URL:?set EVOBGP_CONTROL_PLANE_URL}
|
||||
EVOBGP_NODE_TOKEN: ${EVOBGP_NODE_TOKEN:?set EVOBGP_NODE_TOKEN}
|
||||
EVOBGP_SPEAKER_ID: ${EVOBGP_SPEAKER_ID:?set EVOBGP_SPEAKER_ID}
|
||||
EVOBGP_BUNDLE_PUBKEY_BASE64: ${EVOBGP_BUNDLE_PUBKEY_BASE64:?set EVOBGP_BUNDLE_PUBKEY_BASE64}
|
||||
EVOBGP_BIRD_EXTRACT_DIR: /etc/bird
|
||||
EVOBGP_BIRDC_SOCKET: /run/bird/bird.ctl
|
||||
volumes:
|
||||
- bird_etc:/etc/bird
|
||||
- bird_run:/run/bird
|
||||
entrypoint: ["/usr/local/bin/evobgp-agent"]
|
||||
command: ["serve", "-socket=/run/bird/bird.ctl"]
|
||||
networks:
|
||||
- speaker-net
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.http.routers.evobgp-agent.rule=Host(`${AGENT_DOMAIN}`)
|
||||
- traefik.http.routers.evobgp-agent.entrypoints=websecure
|
||||
- traefik.http.routers.evobgp-agent.tls=true
|
||||
- traefik.http.routers.evobgp-agent.tls.certresolver=letsencrypt
|
||||
- traefik.http.routers.evobgp-agent.middlewares=panel-ipwhitelist@docker
|
||||
- traefik.http.middlewares.panel-ipwhitelist.ipallowlist.sourcerange=${PANEL_IP_WHITELIST}
|
||||
- traefik.http.services.evobgp-agent.loadbalancer.server.port=8443
|
||||
logging: *default-logging
|
||||
|
||||
evobgp-agent-plain:
|
||||
profiles: ["plain", "fallback"]
|
||||
image: ${EVOBGP_REGISTRY:-git.shts.su/denozord}/evobgp-agent:${EVOBGP_IMAGE_TAG:-latest}
|
||||
restart: unless-stopped
|
||||
network_mode: host
|
||||
depends_on:
|
||||
- bird2
|
||||
cap_add:
|
||||
- NET_ADMIN
|
||||
environment:
|
||||
EVOBGP_AGENT_LISTEN: "${EVOBGP_AGENT_PORT:-8443}"
|
||||
EVOBGP_AGENT_SECRET: ${EVOBGP_AGENT_SECRET:?set EVOBGP_AGENT_SECRET}
|
||||
EVOBGP_CONTROL_PLANE_URL: ${EVOBGP_CONTROL_PLANE_URL:?set EVOBGP_CONTROL_PLANE_URL}
|
||||
EVOBGP_NODE_TOKEN: ${EVOBGP_NODE_TOKEN:?set EVOBGP_NODE_TOKEN}
|
||||
EVOBGP_SPEAKER_ID: ${EVOBGP_SPEAKER_ID:?set EVOBGP_SPEAKER_ID}
|
||||
EVOBGP_BUNDLE_PUBKEY_BASE64: ${EVOBGP_BUNDLE_PUBKEY_BASE64:?set EVOBGP_BUNDLE_PUBKEY_BASE64}
|
||||
EVOBGP_BIRD_EXTRACT_DIR: /etc/bird
|
||||
EVOBGP_BIRDC_SOCKET: /run/bird/bird.ctl
|
||||
volumes:
|
||||
- bird_etc:/etc/bird
|
||||
- bird_run:/run/bird
|
||||
entrypoint: ["/usr/local/bin/evobgp-agent"]
|
||||
command: ["serve", "-listen=:${EVOBGP_AGENT_PORT:-8443}", "-socket=/run/bird/bird.ctl"]
|
||||
logging: *default-logging
|
||||
|
||||
evobgp-edge:
|
||||
profiles: ["production"]
|
||||
image: traefik:latest
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- evobgp-agent
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
environment:
|
||||
DOCKER_API_VERSION: "1.44"
|
||||
CF_DNS_API_TOKEN: ${CF_DNS_API_TOKEN:?set CF_DNS_API_TOKEN}
|
||||
command:
|
||||
- --api.dashboard=false
|
||||
- --providers.docker=true
|
||||
- --providers.docker.exposedbydefault=false
|
||||
- --entrypoints.web.address=:80
|
||||
- --entrypoints.websecure.address=:443
|
||||
- --entrypoints.web.http.redirections.entrypoint.to=websecure
|
||||
- --entrypoints.web.http.redirections.entrypoint.scheme=https
|
||||
- --certificatesresolvers.letsencrypt.acme.email=${LETSENCRYPT_EMAIL:?set LETSENCRYPT_EMAIL}
|
||||
- --certificatesresolvers.letsencrypt.acme.storage=/letsencrypt/acme.json
|
||||
- --certificatesresolvers.letsencrypt.acme.dnschallenge=true
|
||||
- --certificatesresolvers.letsencrypt.acme.dnschallenge.provider=cloudflare
|
||||
- --certificatesresolvers.letsencrypt.acme.dnschallenge.delaybeforecheck=15
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
- traefik_letsencrypt:/letsencrypt
|
||||
networks:
|
||||
- speaker-net
|
||||
logging: *default-logging
|
||||
|
||||
sync-bundle:
|
||||
profiles: ["fallback"]
|
||||
image: ${EVOBGP_REGISTRY:-git.shts.su/denozord}/evobgp-node:${EVOBGP_IMAGE_TAG:-latest}
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- bird2
|
||||
environment:
|
||||
EVOBGP_CONTROL_PLANE_URL: ${EVOBGP_CONTROL_PLANE_URL:?set EVOBGP_CONTROL_PLANE_URL}
|
||||
EVOBGP_NODE_TOKEN: ${EVOBGP_NODE_TOKEN:?set EVOBGP_NODE_TOKEN}
|
||||
EVOBGP_SPEAKER_ID: ${EVOBGP_SPEAKER_ID:?set EVOBGP_SPEAKER_ID}
|
||||
EVOBGP_BUNDLE_PUBKEY_BASE64: ${EVOBGP_BUNDLE_PUBKEY_BASE64:?set EVOBGP_BUNDLE_PUBKEY_BASE64}
|
||||
EVOBGP_SYNC_INTERVAL_SEC: ${EVOBGP_SYNC_INTERVAL_SEC:-300}
|
||||
volumes:
|
||||
- bird_etc:/etc/bird
|
||||
- bird_run:/run/bird
|
||||
- ../../scripts/sync-bundle.sh:/usr/local/bin/sync-bundle.sh:ro
|
||||
entrypoint: ["/bin/sh", "/usr/local/bin/sync-bundle.sh"]
|
||||
network_mode: host
|
||||
logging: *default-logging
|
||||
|
||||
networks:
|
||||
speaker-net:
|
||||
|
||||
volumes:
|
||||
bird_etc:
|
||||
bird_run:
|
||||
traefik_letsencrypt:
|
||||
name: evobgp_speaker_traefik_letsencrypt
|
||||
@@ -45,6 +45,8 @@ services:
|
||||
profiles: ["reference", "microvps", "microvps-full"]
|
||||
image: postgres:16-alpine
|
||||
restart: unless-stopped
|
||||
# Дефолтный /dev/shm в Docker (64 МиБ) мало для Postgres; иначе ошибки shared memory при старте.
|
||||
shm_size: "256mb"
|
||||
environment:
|
||||
POSTGRES_USER: evobgp
|
||||
POSTGRES_PASSWORD: evobgp
|
||||
@@ -55,7 +57,8 @@ services:
|
||||
test: ["CMD-SHELL", "pg_isready -U evobgp -d evobgp"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
retries: 12
|
||||
start_period: 45s
|
||||
logging: *default-logging
|
||||
deploy:
|
||||
resources:
|
||||
@@ -93,7 +96,7 @@ services:
|
||||
<<: *env-ref
|
||||
EVOBGP_HTTP_ADDR: ":8080"
|
||||
EVOBGP_SEED_DEMO: "1"
|
||||
# Local reference only: allows Bearer dev for scheduler HTTP client (EVOBGP_SCHEDULER_BEARER).
|
||||
# DEV ONLY — не для production. Bearer dev + слабые demo-секреты (см. docs/access.md).
|
||||
EVOBGP_DEV_INSECURE: "1"
|
||||
EVOBGP_BIRDC_SOCKET: /run/bird/bird.ctl
|
||||
EVOBGP_BIRDC_INTERVAL: 30s
|
||||
@@ -123,6 +126,8 @@ services:
|
||||
condition: service_started
|
||||
environment:
|
||||
<<: *env-ref
|
||||
# Split deploy: scheduler must enqueue jobs via API, not in-process Registry (ARCH-04).
|
||||
EVOBGP_SCHEDULER_STANDALONE: "1"
|
||||
EVOBGP_CONTROL_PLANE_URL: http://evobgp-api:8080
|
||||
EVOBGP_SCHEDULER_BEARER: dev
|
||||
logging: *default-logging
|
||||
@@ -240,8 +245,15 @@ services:
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- evobgp-all
|
||||
ports:
|
||||
- "3000:80"
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.http.routers.evobgp-web.rule=Host(`${WEBUI_DOMAIN}`)
|
||||
- traefik.http.routers.evobgp-web.entrypoints=websecure
|
||||
- traefik.http.routers.evobgp-web.tls=true
|
||||
- traefik.http.routers.evobgp-web.tls.certresolver=letsencrypt
|
||||
- traefik.http.routers.evobgp-web.middlewares=webui-ipwhitelist@docker
|
||||
- traefik.http.middlewares.webui-ipwhitelist.ipallowlist.sourcerange=${WEBUI_IP_WHITELIST}
|
||||
- traefik.http.services.evobgp-web.loadbalancer.server.port=80
|
||||
logging: *default-logging
|
||||
deploy:
|
||||
resources:
|
||||
@@ -249,6 +261,41 @@ services:
|
||||
cpus: "0.5"
|
||||
memory: 128M
|
||||
|
||||
evobgp-edge:
|
||||
profiles: ["microvps-full"]
|
||||
image: traefik:latest
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- evobgp-web-microvps
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
environment:
|
||||
DOCKER_API_VERSION: "1.44"
|
||||
CF_DNS_API_TOKEN: ${CF_DNS_API_TOKEN}
|
||||
command:
|
||||
- --api.dashboard=false
|
||||
- --providers.docker=true
|
||||
- --providers.docker.exposedbydefault=false
|
||||
- --entrypoints.web.address=:80
|
||||
- --entrypoints.websecure.address=:443
|
||||
- --entrypoints.web.http.redirections.entrypoint.to=websecure
|
||||
- --entrypoints.web.http.redirections.entrypoint.scheme=https
|
||||
- --certificatesresolvers.letsencrypt.acme.email=${LETSENCRYPT_EMAIL}
|
||||
- --certificatesresolvers.letsencrypt.acme.storage=/letsencrypt/acme.json
|
||||
- --certificatesresolvers.letsencrypt.acme.dnschallenge=true
|
||||
- --certificatesresolvers.letsencrypt.acme.dnschallenge.provider=cloudflare
|
||||
- --certificatesresolvers.letsencrypt.acme.dnschallenge.delaybeforecheck=15
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
- traefik_letsencrypt:/letsencrypt
|
||||
logging: *default-logging
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.35"
|
||||
memory: 128M
|
||||
|
||||
prometheus-microvps:
|
||||
profiles: ["microvps-full"]
|
||||
image: prom/prometheus:v2.54.1
|
||||
@@ -337,3 +384,4 @@ volumes:
|
||||
pgdata:
|
||||
bird_etc:
|
||||
bird_run:
|
||||
traefik_letsencrypt:
|
||||
@@ -0,0 +1,343 @@
|
||||
# Standalone stack (без profiles): Portainer / `docker compose -f stack.microvps-full.yaml up -d`
|
||||
# Эквивалент microvps-full из docker-compose.yaml + docker-compose.microvps-full.yaml,
|
||||
# с встроенными configs для Prometheus (как у вас).
|
||||
#
|
||||
# Postgres: shm_size + start_period — иначе часто «dependency postgres failed» на слабом хосте.
|
||||
# Для защищенного Web UI задайте переменные окружения перед запуском:
|
||||
# WEBUI_DOMAIN, WEBUI_IP_WHITELIST, LETSENCRYPT_EMAIL, CF_DNS_API_TOKEN
|
||||
# Cloudflare запись для WEBUI_DOMAIN: DNS only (серый облачок).
|
||||
#
|
||||
# ACME / Let's Encrypt: путь задан в evobgp-edge (--certificatesresolvers...storage).
|
||||
# Имя тома traefik_letsencrypt зафиксировано (volumes.traefik_letsencrypt.name), иначе при
|
||||
# другом имени стека в Portainer или смене project name создаётся новый пустой том —
|
||||
# Traefik не находит acme.json и отдаёт дефолтный сертификат до новой выдачи LE.
|
||||
# Не использовать `docker compose down -v` без бэкапа. Если раньше был том с префиксом
|
||||
# проекта, перенесите acme.json в том evobgp_traefik_letsencrypt.
|
||||
#
|
||||
# Долгий сбор логов в файлы на хосте: сервис stack-runtime-logs пишет в каталог
|
||||
# ./runtime-logs/ (рядом с этим compose-файлом) по одному файлу на сервис.
|
||||
# Автообновление сервисов из registry (без перезапуска bird2): stack-auto-updater.
|
||||
# Настройки через .env: AUTO_UPDATE_ENABLED, AUTO_UPDATE_INTERVAL_SEC,
|
||||
# AUTO_UPDATE_SERVICES, AUTO_UPDATE_PROTECTED_SERVICES.
|
||||
# Имя проекта в Docker должно совпадать с label com.docker.compose.project:
|
||||
# при смене `name:` или имени стека в Portainer задайте COMPOSE_PROJECT_NAME.
|
||||
# Требуется доступ к docker.sock (полные права на демон — осознанно).
|
||||
name: evobgp-microvps-full
|
||||
|
||||
configs:
|
||||
prometheus_yml:
|
||||
content: |
|
||||
global:
|
||||
scrape_interval: 15s
|
||||
evaluation_interval: 15s
|
||||
rule_files:
|
||||
- /etc/prometheus/alerts.yml
|
||||
scrape_configs:
|
||||
- job_name: evobgp-all
|
||||
metrics_path: /metrics
|
||||
static_configs:
|
||||
- targets: ["evobgp-all:8080"]
|
||||
prometheus_alerts_yml:
|
||||
content: |
|
||||
groups: []
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
restart: unless-stopped
|
||||
shm_size: "256mb"
|
||||
environment:
|
||||
POSTGRES_USER: evobgp
|
||||
POSTGRES_PASSWORD: evobgp
|
||||
POSTGRES_DB: evobgp
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U evobgp -d evobgp"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 12
|
||||
start_period: 45s
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
nats:
|
||||
image: nats:2.10-alpine
|
||||
restart: unless-stopped
|
||||
command: ["-js", "-m", "8222"]
|
||||
ports:
|
||||
- "4222:4222"
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
bird2:
|
||||
image: ${EVOBGP_REGISTRY:-git.shts.su/denozord}/evobgp-bird2:${EVOBGP_IMAGE_TAG:-latest}
|
||||
restart: unless-stopped
|
||||
cap_add:
|
||||
- NET_ADMIN
|
||||
sysctls:
|
||||
net.ipv4.ip_forward: "1"
|
||||
net.ipv6.conf.all.forwarding: "1"
|
||||
volumes:
|
||||
- bird_etc:/etc/bird
|
||||
- bird_run:/run/bird
|
||||
ports:
|
||||
- "179:179/tcp"
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
evobgp-agent:
|
||||
image: ${EVOBGP_REGISTRY:-git.shts.su/denozord}/evobgp-agent:${EVOBGP_IMAGE_TAG:-latest}
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
bird2:
|
||||
condition: service_started
|
||||
cap_add:
|
||||
- NET_ADMIN
|
||||
volumes:
|
||||
- bird_etc:/etc/bird
|
||||
- bird_run:/run/bird
|
||||
entrypoint: ["/usr/local/bin/evobgp-agent"]
|
||||
command: ["watch", "-socket=/run/bird/bird.ctl", "-watch-interval=30s"]
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
evobgp-all:
|
||||
image: ${EVOBGP_REGISTRY:-git.shts.su/denozord}/evobgp-all:${EVOBGP_IMAGE_TAG:-latest}
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
nats:
|
||||
condition: service_started
|
||||
bird2:
|
||||
condition: service_started
|
||||
ports:
|
||||
- "8080:8080"
|
||||
environment:
|
||||
EVOBGP_DATABASE_URL: postgres://evobgp:evobgp@postgres:5432/evobgp?sslmode=disable
|
||||
EVOBGP_BROKER_URL: nats://nats:4222
|
||||
EVOBGP_HTTP_ADDR: ":8080"
|
||||
EVOBGP_SEED_DEMO: "1"
|
||||
EVOBGP_BIRDC_SOCKET: /run/bird/bird.ctl
|
||||
EVOBGP_BIRDC_INTERVAL: 30s
|
||||
EVOBGP_BIRD_ACTIVE_DIR: /etc/bird
|
||||
EVOBGP_BIRD_STAGING_DIR: /tmp/evobgp-bird-staging
|
||||
# DEV ONLY — не для production (см. docs/access.md).
|
||||
EVOBGP_DEV_INSECURE: "1"
|
||||
volumes:
|
||||
- bird_etc:/etc/bird
|
||||
- bird_run:/run/bird:ro
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
evobgp-web:
|
||||
image: ${EVOBGP_REGISTRY:-git.shts.su/denozord}/evobgp-web-all:${EVOBGP_IMAGE_TAG:-latest}
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
evobgp-all:
|
||||
condition: service_started
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.http.routers.evobgp-web.rule=Host(`${WEBUI_DOMAIN}`)
|
||||
- traefik.http.routers.evobgp-web.entrypoints=websecure
|
||||
- traefik.http.routers.evobgp-web.tls=true
|
||||
- traefik.http.routers.evobgp-web.tls.certresolver=letsencrypt
|
||||
- traefik.http.routers.evobgp-web.middlewares=webui-ipwhitelist@docker
|
||||
- traefik.http.middlewares.webui-ipwhitelist.ipallowlist.sourcerange=${WEBUI_IP_WHITELIST}
|
||||
- traefik.http.services.evobgp-web.loadbalancer.server.port=80
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
evobgp-edge:
|
||||
image: traefik:latest
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
evobgp-web:
|
||||
condition: service_started
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
environment:
|
||||
DOCKER_API_VERSION: "1.44"
|
||||
CF_DNS_API_TOKEN: ${CF_DNS_API_TOKEN}
|
||||
command:
|
||||
- --log.level=INFO
|
||||
- --api.dashboard=false
|
||||
- --providers.docker=true
|
||||
- --providers.docker.exposedbydefault=false
|
||||
- --entrypoints.web.address=:80
|
||||
- --entrypoints.websecure.address=:443
|
||||
- --entrypoints.web.http.redirections.entrypoint.to=websecure
|
||||
- --entrypoints.web.http.redirections.entrypoint.scheme=https
|
||||
- --certificatesresolvers.letsencrypt.acme.email=${LETSENCRYPT_EMAIL}
|
||||
- --certificatesresolvers.letsencrypt.acme.storage=/letsencrypt/acme.json
|
||||
- --certificatesresolvers.letsencrypt.acme.dnschallenge=true
|
||||
- --certificatesresolvers.letsencrypt.acme.dnschallenge.provider=cloudflare
|
||||
- --certificatesresolvers.letsencrypt.acme.dnschallenge.delaybeforecheck=15
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
- traefik_letsencrypt:/letsencrypt
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
prometheus:
|
||||
image: prom/prometheus:v2.54.1
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
evobgp-all:
|
||||
condition: service_started
|
||||
ports:
|
||||
- "9090:9090"
|
||||
configs:
|
||||
- source: prometheus_yml
|
||||
target: /etc/prometheus/prometheus.yml
|
||||
- source: prometheus_alerts_yml
|
||||
target: /etc/prometheus/alerts.yml
|
||||
command:
|
||||
- --config.file=/etc/prometheus/prometheus.yml
|
||||
- --storage.tsdb.path=/prometheus
|
||||
- --storage.tsdb.retention.time=7d
|
||||
- --web.enable-lifecycle
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
stack-runtime-logs:
|
||||
image: docker:27-cli
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
evobgp-all:
|
||||
condition: service_started
|
||||
environment:
|
||||
COMPOSE_PROJECT_NAME: ${COMPOSE_PROJECT_NAME:-evobgp-microvps-full}
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
- type: bind
|
||||
source: ./runtime-logs
|
||||
target: /logs
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command:
|
||||
- |
|
||||
set -eu
|
||||
mkdir -p /logs
|
||||
PROJECT=$$COMPOSE_PROJECT_NAME
|
||||
SERVICES="postgres nats bird2 evobgp-agent evobgp-all evobgp-web evobgp-edge prometheus"
|
||||
log_one() {
|
||||
svc=$$1
|
||||
f="/logs/$$svc.log"
|
||||
while true; do
|
||||
cid=$$(docker ps -q \
|
||||
-f "label=com.docker.compose.service=$$svc" \
|
||||
-f "label=com.docker.compose.project=$$PROJECT" | head -n1)
|
||||
if [ -n "$$cid" ]; then
|
||||
echo "---- $$(date -u +"%Y-%m-%dT%H:%M:%SZ") attach $$svc $$cid ----" >> "$$f"
|
||||
docker logs -f --timestamps "$$cid" >> "$$f" 2>&1 || true
|
||||
fi
|
||||
sleep 3
|
||||
done
|
||||
}
|
||||
for s in $$SERVICES; do log_one "$$s" & done
|
||||
wait
|
||||
|
||||
stack-auto-updater:
|
||||
image: docker:27-cli
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
evobgp-all:
|
||||
condition: service_started
|
||||
environment:
|
||||
COMPOSE_PROJECT_NAME: ${COMPOSE_PROJECT_NAME:-evobgp-microvps-full}
|
||||
AUTO_UPDATE_ENABLED: ${AUTO_UPDATE_ENABLED:-0}
|
||||
AUTO_UPDATE_INTERVAL_SEC: ${AUTO_UPDATE_INTERVAL_SEC:-300}
|
||||
AUTO_UPDATE_SERVICES: ${AUTO_UPDATE_SERVICES:-evobgp-all,evobgp-web}
|
||||
AUTO_UPDATE_PROTECTED_SERVICES: ${AUTO_UPDATE_PROTECTED_SERVICES:-bird2}
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
- type: bind
|
||||
source: ./stack.microvps-full.yaml
|
||||
target: /stack/stack.microvps-full.yaml
|
||||
read_only: true
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command:
|
||||
- |
|
||||
set -eu
|
||||
PROJECT=$$COMPOSE_PROJECT_NAME
|
||||
INTERVAL=$$AUTO_UPDATE_INTERVAL_SEC
|
||||
ENABLED=$$AUTO_UPDATE_ENABLED
|
||||
if [ "$$ENABLED" != "1" ]; then
|
||||
echo "auto-updater disabled: AUTO_UPDATE_ENABLED=$$ENABLED"
|
||||
while true; do sleep 3600; done
|
||||
fi
|
||||
if [ "$$INTERVAL" -lt 30 ]; then
|
||||
echo "auto-updater interval too low ($$INTERVAL), forcing to 30"
|
||||
INTERVAL=30
|
||||
fi
|
||||
echo "auto-updater started: project=$$PROJECT interval=$$INTERVAL services=$$AUTO_UPDATE_SERVICES protected=$$AUTO_UPDATE_PROTECTED_SERVICES"
|
||||
while true; do
|
||||
TS=$$(date -u +"%Y-%m-%dT%H:%M:%SZ")
|
||||
SERVICES_LIST=$$(echo "$$AUTO_UPDATE_SERVICES" | tr ',' ' ')
|
||||
PROTECTED_LIST=$$(echo "$$AUTO_UPDATE_PROTECTED_SERVICES" | tr ',' ' ')
|
||||
for svc in $$SERVICES_LIST; do
|
||||
if [ -z "$$svc" ]; then
|
||||
continue
|
||||
fi
|
||||
skip=0
|
||||
for protected in $$PROTECTED_LIST; do
|
||||
if [ "$$svc" = "$$protected" ]; then
|
||||
echo "$$TS skip protected service '$$svc'"
|
||||
skip=1
|
||||
break
|
||||
fi
|
||||
done
|
||||
if [ "$$skip" = "1" ]; then
|
||||
continue
|
||||
fi
|
||||
before=$$(docker image inspect "$$(docker compose -p "$$PROJECT" -f /stack/stack.microvps-full.yaml config --images $$svc | tail -n1)" --format '{{.Id}}' 2>/dev/null || true)
|
||||
pull_out=$$(docker compose -p "$$PROJECT" -f /stack/stack.microvps-full.yaml pull $$svc 2>&1 || true)
|
||||
echo "$$TS pull $$svc: $$pull_out"
|
||||
after=$$(docker image inspect "$$(docker compose -p "$$PROJECT" -f /stack/stack.microvps-full.yaml config --images $$svc | tail -n1)" --format '{{.Id}}' 2>/dev/null || true)
|
||||
if [ -n "$$after" ] && [ "$$before" != "$$after" ]; then
|
||||
echo "$$TS update detected for $$svc, restarting container"
|
||||
docker compose -p "$$PROJECT" -f /stack/stack.microvps-full.yaml up -d --no-deps $$svc
|
||||
else
|
||||
echo "$$TS no update for $$svc"
|
||||
fi
|
||||
done
|
||||
sleep "$$INTERVAL"
|
||||
done
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
bird_etc:
|
||||
bird_run:
|
||||
traefik_letsencrypt:
|
||||
name: evobgp_traefik_letsencrypt
|
||||
@@ -0,0 +1,56 @@
|
||||
# Docker-образы EvoBGP
|
||||
|
||||
## CI (Gitea Actions)
|
||||
|
||||
Сборка образов — **`docker buildx bake`** (`deploy/docker/docker-bake.hcl`), не отдельные `docker build`.
|
||||
|
||||
**Publish:** push в `main` после quality gates — job **release** в [.gitea/workflows/ci.yaml](../.gitea/workflows/ci.yaml): semantic-release + bake с `VERSION` из релиза.
|
||||
|
||||
Локально BuildKit также кэширует `/go/pkg/mod` и `~/.cache/go-build` через `RUN --mount=type=cache`.
|
||||
|
||||
| Было | Стало |
|
||||
|------|--------|
|
||||
| 8× `go mod download` + 8× `go build` (разные BIN) | 1× download + 1× компиляция всех `cmd/*` |
|
||||
| 2× сборка BIRD из исходников (api, all) | 1× stage `birdc`, копируется в runtime |
|
||||
| 2× `npm ci` (web, web-all) | 1× `web-deps` + 1× `web-build` + два nginx-образа (общий артефакт) |
|
||||
| 8 runner'ов с checkout/login | 1 job `docker-go`, 1 job `docker-web` |
|
||||
|
||||
Кэш registry (переменные bake):
|
||||
|
||||
- `git.shts.su/<owner>/evobgp-buildcache:go-buildcache` — **запись** только из target `go-build-all`
|
||||
- `git.shts.su/<owner>/evobgp-buildcache:web-buildcache` — **запись** только из target `web-build`
|
||||
|
||||
Остальные bake-target’ы только `cache-from` (чтение). Параллельный `cache-to` в один ref ломает manifest в registry (`content descriptor … not found`).
|
||||
|
||||
Локально BuildKit также кэширует `/go/pkg/mod` и `~/.cache/go-build` через `RUN --mount=type=cache`.
|
||||
|
||||
Если CI падает на «not found» после смены схемы кэша — один раз удалите теги `evobgp-buildcache:go-buildcache` и `:web-buildcache` в registry и пересоберите.
|
||||
|
||||
## Локальная сборка
|
||||
|
||||
Из корня репозитория:
|
||||
|
||||
```bash
|
||||
cd deploy/docker
|
||||
export REGISTRY=git.shts.su/<owner>
|
||||
export IMAGE_TAG=latest
|
||||
export SHORT_SHA=$(git rev-parse --short HEAD)
|
||||
export VERSION=dev
|
||||
export BUILD_TIME=
|
||||
sh write-bake-override.sh
|
||||
docker buildx bake --allow=fs.read=../.. -f docker-bake.hcl -f docker-bake.override.hcl go-images
|
||||
docker buildx bake --allow=fs.read=../.. -f docker-bake.hcl -f docker-bake.override.hcl web-images
|
||||
```
|
||||
|
||||
В `docker-bake.hcl`: `context = "../.."` (корень репо), `dockerfile = "deploy/docker/…"` (путь от корня репо). **CI:** `write-bake-override.sh` + `--allow=fs.read=$GITHUB_WORKSPACE` в `.gitea/workflows/ci.yaml`.
|
||||
|
||||
Один образ (legacy):
|
||||
|
||||
```bash
|
||||
docker build -f deploy/docker/gobinary/Dockerfile \
|
||||
--target build-all \
|
||||
--build-arg BIN=evobgp-api \
|
||||
-t evobgp-api:local .
|
||||
```
|
||||
|
||||
Runtime-образы в bake ожидают stage `build-all` (через bake contexts), не отдельный `--build-arg BIN` на старый target `build`.
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/bin/sh
|
||||
# Сборка BIRD из официального tarball (версия задаётся BIRD_VERSION, по умолчанию 2.14).
|
||||
# Запуск от root (Docker) или через sudo на хосте. Префикс установки: /usr/local.
|
||||
# birdc требует ncurses + readline; в runtime-образе gobinary — libncurses6 + libreadline8.
|
||||
set -eu
|
||||
BIRD_VERSION="${BIRD_VERSION:-2.14}"
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends \
|
||||
build-essential \
|
||||
ca-certificates \
|
||||
curl \
|
||||
flex \
|
||||
bison \
|
||||
libncurses-dev \
|
||||
libreadline-dev
|
||||
|
||||
cd /tmp
|
||||
rm -rf "bird-${BIRD_VERSION}"
|
||||
curl -fsSL "https://bird.network.cz/download/bird-${BIRD_VERSION}.tar.gz" | tar xz
|
||||
cd "bird-${BIRD_VERSION}"
|
||||
./configure --prefix=/usr/local --enable-client
|
||||
make -j"$(nproc)"
|
||||
make install
|
||||
cd /
|
||||
rm -rf "/tmp/bird-${BIRD_VERSION}"
|
||||
|
||||
apt-get purge -y build-essential flex bison libncurses-dev libreadline-dev
|
||||
apt-get autoremove -y
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
@@ -1,9 +1,11 @@
|
||||
# BIRD 2 alongside evobgp-agent; share /etc/bird with the agent container (plan §4.1).
|
||||
FROM public.ecr.aws/docker/library/debian:bookworm-slim
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends bird2 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
# BIRD из репозитория Ubuntu (Noble 24.04 LTS) — актуальнее пакета Debian bookworm.
|
||||
# Сборка из корня репозитория: docker build -f deploy/docker/bird2/Dockerfile .
|
||||
# Зеркало ECR Public вместо прямого pull с Docker Hub.
|
||||
FROM public.ecr.aws/docker/library/ubuntu:noble
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends bird2 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY deploy/bird/bird.conf /etc/bird/bird.conf
|
||||
RUN mkdir -p /etc/bird/bird.d
|
||||
EXPOSE 179
|
||||
# Foreground for Docker; configs on shared volume override this file at runtime.
|
||||
CMD ["bird", "-f", "-c", "/etc/bird/bird.conf"]
|
||||
@@ -0,0 +1,265 @@
|
||||
# Единая сборка образов EvoBGP (buildx bake: -f deploy/docker/docker-bake.hcl).
|
||||
# context = "../.." — корень репозитория (относительно этого файла).
|
||||
# dockerfile — путь от корня репозитория (относительно context).
|
||||
# Переменные: REGISTRY, IMAGE_TAG, CACHE_REF_GO, CACHE_REF_WEB
|
||||
|
||||
variable "REGISTRY" {
|
||||
default = "git.shts.su/evobgp"
|
||||
}
|
||||
|
||||
variable "IMAGE_TAG" {
|
||||
default = "latest"
|
||||
}
|
||||
|
||||
variable "SHORT_SHA" {
|
||||
default = "dev"
|
||||
}
|
||||
|
||||
variable "SHA_FULL" {
|
||||
default = ""
|
||||
}
|
||||
|
||||
variable "VERSION" {
|
||||
default = "dev"
|
||||
}
|
||||
|
||||
variable "BUILD_TIME" {
|
||||
default = ""
|
||||
}
|
||||
|
||||
variable "CACHE_REF_GO" {
|
||||
default = ""
|
||||
}
|
||||
|
||||
variable "CACHE_REF_WEB" {
|
||||
default = ""
|
||||
}
|
||||
|
||||
function "go-cache-from" {
|
||||
params = []
|
||||
result = notequal("", CACHE_REF_GO) ? ["type=registry,ref=${CACHE_REF_GO}"] : []
|
||||
}
|
||||
|
||||
# Экспорт кэша — только go-build-all / web-build (один writer на ref).
|
||||
# Несколько target с cache-to в один ref и mode=max дают гонку в registry
|
||||
# (content descriptor not found при параллельном bake).
|
||||
function "go-cache-to-export" {
|
||||
params = []
|
||||
result = notequal("", CACHE_REF_GO) ? ["type=registry,ref=${CACHE_REF_GO},mode=max"] : []
|
||||
}
|
||||
|
||||
function "web-cache-from" {
|
||||
params = []
|
||||
result = notequal("", CACHE_REF_WEB) ? ["type=registry,ref=${CACHE_REF_WEB}"] : []
|
||||
}
|
||||
|
||||
function "web-cache-to-export" {
|
||||
params = []
|
||||
result = notequal("", CACHE_REF_WEB) ? ["type=registry,ref=${CACHE_REF_WEB},mode=max"] : []
|
||||
}
|
||||
|
||||
group "default" {
|
||||
targets = ["go-images", "web-images", "evobgp-bird2"]
|
||||
}
|
||||
|
||||
group "go-images" {
|
||||
targets = [
|
||||
"evobgp-api",
|
||||
"evobgp-all",
|
||||
"evobgp-scheduler",
|
||||
"evobgp-ingest",
|
||||
"evobgp-render",
|
||||
"evobgp-deploy",
|
||||
"evobgp-node",
|
||||
"evobgp-agent",
|
||||
]
|
||||
}
|
||||
|
||||
# web-deps / web-build — только зависимости (contexts), без tags; при --push в группе не указывать.
|
||||
group "web-images" {
|
||||
targets = ["evobgp-web", "evobgp-web-all"]
|
||||
}
|
||||
|
||||
# --- Go: go mod download → все cmd/* → birdc (один раз) → runtime-образы ---
|
||||
|
||||
target "go-deps" {
|
||||
context = "../.."
|
||||
dockerfile = "deploy/docker/gobinary/Dockerfile"
|
||||
target = "deps"
|
||||
platforms = ["linux/amd64"]
|
||||
cache-from = go-cache-from()
|
||||
}
|
||||
|
||||
target "go-build-all" {
|
||||
context = "../.."
|
||||
dockerfile = "deploy/docker/gobinary/Dockerfile"
|
||||
target = "build-all"
|
||||
platforms = ["linux/amd64"]
|
||||
args = {
|
||||
VERSION = VERSION
|
||||
GIT_SHA = notequal("", SHA_FULL) ? SHA_FULL : SHORT_SHA
|
||||
BUILD_TIME = BUILD_TIME
|
||||
}
|
||||
contexts = {
|
||||
deps = "target:go-deps"
|
||||
}
|
||||
cache-from = go-cache-from()
|
||||
cache-to = go-cache-to-export()
|
||||
}
|
||||
|
||||
target "go-birdc" {
|
||||
context = "../.."
|
||||
dockerfile = "deploy/docker/gobinary/Dockerfile"
|
||||
target = "birdc"
|
||||
platforms = ["linux/amd64"]
|
||||
cache-from = go-cache-from()
|
||||
}
|
||||
|
||||
target "_go-runtime" {
|
||||
context = "../.."
|
||||
dockerfile = "deploy/docker/gobinary/Dockerfile"
|
||||
target = "runtime"
|
||||
platforms = ["linux/amd64"]
|
||||
contexts = {
|
||||
build-all = "target:go-build-all"
|
||||
}
|
||||
cache-from = go-cache-from()
|
||||
}
|
||||
|
||||
target "_go-runtime-birdc" {
|
||||
context = "../.."
|
||||
dockerfile = "deploy/docker/gobinary/Dockerfile"
|
||||
target = "runtime-birdc"
|
||||
platforms = ["linux/amd64"]
|
||||
contexts = {
|
||||
build-all = "target:go-build-all"
|
||||
birdc = "target:go-birdc"
|
||||
}
|
||||
cache-from = go-cache-from()
|
||||
}
|
||||
|
||||
function "image-tags" {
|
||||
params = [name]
|
||||
result = concat(
|
||||
notequal("", SHA_FULL) ? [
|
||||
"${REGISTRY}/${name}:${IMAGE_TAG}",
|
||||
"${REGISTRY}/${name}:${SHORT_SHA}",
|
||||
"${REGISTRY}/${name}:sha-${SHA_FULL}",
|
||||
] : [
|
||||
"${REGISTRY}/${name}:${IMAGE_TAG}",
|
||||
"${REGISTRY}/${name}:${SHORT_SHA}",
|
||||
],
|
||||
notequal(VERSION, "dev") && notequal(VERSION, "") ? [
|
||||
"${REGISTRY}/${name}:v${VERSION}",
|
||||
"${REGISTRY}/${name}:${VERSION}",
|
||||
] : []
|
||||
)
|
||||
}
|
||||
|
||||
target "evobgp-api" {
|
||||
inherits = ["_go-runtime-birdc"]
|
||||
args = { BIN = "evobgp-api" }
|
||||
tags = image-tags("evobgp-api")
|
||||
}
|
||||
|
||||
target "evobgp-all" {
|
||||
inherits = ["_go-runtime-birdc"]
|
||||
args = { BIN = "evobgp-all" }
|
||||
tags = image-tags("evobgp-all")
|
||||
}
|
||||
|
||||
target "evobgp-scheduler" {
|
||||
inherits = ["_go-runtime"]
|
||||
args = { BIN = "evobgp-scheduler" }
|
||||
tags = image-tags("evobgp-scheduler")
|
||||
}
|
||||
|
||||
target "evobgp-ingest" {
|
||||
inherits = ["_go-runtime"]
|
||||
args = { BIN = "evobgp-ingest" }
|
||||
tags = image-tags("evobgp-ingest")
|
||||
}
|
||||
|
||||
target "evobgp-render" {
|
||||
inherits = ["_go-runtime"]
|
||||
args = { BIN = "evobgp-render" }
|
||||
tags = image-tags("evobgp-render")
|
||||
}
|
||||
|
||||
target "evobgp-deploy" {
|
||||
inherits = ["_go-runtime"]
|
||||
args = { BIN = "evobgp-deploy" }
|
||||
tags = image-tags("evobgp-deploy")
|
||||
}
|
||||
|
||||
target "evobgp-node" {
|
||||
inherits = ["_go-runtime"]
|
||||
args = { BIN = "evobgp-node" }
|
||||
tags = image-tags("evobgp-node")
|
||||
}
|
||||
|
||||
target "evobgp-agent" {
|
||||
context = "../.."
|
||||
dockerfile = "deploy/docker/evobgp-agent/Dockerfile"
|
||||
platforms = ["linux/amd64"]
|
||||
contexts = {
|
||||
build-all = "target:go-build-all"
|
||||
}
|
||||
cache-from = go-cache-from()
|
||||
tags = image-tags("evobgp-agent")
|
||||
}
|
||||
|
||||
# --- Web: npm ci (кэш) → build → nginx ---
|
||||
|
||||
target "web-deps" {
|
||||
context = "../.."
|
||||
dockerfile = "deploy/docker/evobgp-web/Dockerfile"
|
||||
target = "deps"
|
||||
platforms = ["linux/amd64"]
|
||||
cache-from = web-cache-from()
|
||||
}
|
||||
|
||||
target "web-build" {
|
||||
context = "../.."
|
||||
dockerfile = "deploy/docker/evobgp-web/Dockerfile"
|
||||
target = "build"
|
||||
platforms = ["linux/amd64"]
|
||||
contexts = {
|
||||
deps = "target:web-deps"
|
||||
}
|
||||
cache-from = web-cache-from()
|
||||
cache-to = web-cache-to-export()
|
||||
}
|
||||
|
||||
target "evobgp-web" {
|
||||
context = "../.."
|
||||
dockerfile = "deploy/docker/evobgp-web/Dockerfile"
|
||||
target = "web"
|
||||
platforms = ["linux/amd64"]
|
||||
contexts = {
|
||||
web-artifacts = "target:web-build"
|
||||
}
|
||||
args = { EVOBGP_UPSTREAM = "evobgp-api" }
|
||||
cache-from = web-cache-from()
|
||||
tags = image-tags("evobgp-web")
|
||||
}
|
||||
|
||||
target "evobgp-web-all" {
|
||||
context = "../.."
|
||||
dockerfile = "deploy/docker/evobgp-web/Dockerfile"
|
||||
target = "web"
|
||||
platforms = ["linux/amd64"]
|
||||
contexts = {
|
||||
web-artifacts = "target:web-build"
|
||||
}
|
||||
args = { EVOBGP_UPSTREAM = "evobgp-all" }
|
||||
cache-from = web-cache-from()
|
||||
tags = image-tags("evobgp-web-all")
|
||||
}
|
||||
|
||||
target "evobgp-bird2" {
|
||||
context = "../.."
|
||||
dockerfile = "deploy/docker/bird2/Dockerfile"
|
||||
platforms = ["linux/amd64"]
|
||||
tags = image-tags("evobgp-bird2")
|
||||
}
|
||||
@@ -1,14 +1,10 @@
|
||||
# evobgp-agent CLI (parse-check, birdc configure); install bird2 so `bird -p` matches bird2 image (plan §13).
|
||||
# См. gobinary/Dockerfile — ECR Public вместо прямого pull с Docker Hub (устойчивость CI).
|
||||
FROM public.ecr.aws/docker/library/golang:1.22-bookworm AS build
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
COPY . .
|
||||
RUN go build -trimpath -ldflags="-s -w" -o /out/evobgp-agent ./cmd/evobgp-agent
|
||||
|
||||
FROM public.ecr.aws/docker/library/debian:bookworm-slim
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends bird2 ca-certificates \
|
||||
# syntax=docker/dockerfile:1.7
|
||||
# Агент: бинарь из общего build-all (docker-bake.hcl → contexts.build-all), bird2 из apt.
|
||||
FROM public.ecr.aws/docker/library/ubuntu:noble
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends bird2 ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY --from=build /out/evobgp-agent /usr/local/bin/evobgp-agent
|
||||
ARG BIN=evobgp-agent
|
||||
COPY --from=build-all /out/${BIN} /usr/local/bin/evobgp-agent
|
||||
WORKDIR /etc/bird
|
||||
ENTRYPOINT ["/usr/local/bin/evobgp-agent"]
|
||||
@@ -1,14 +1,19 @@
|
||||
# Статическая панель EvoBGP (SvelteKit) + nginx как reverse-proxy к evobgp-api (/v1, /metrics).
|
||||
# ECR Public — то же содержимое, что library/node и library/nginx на Docker Hub.
|
||||
FROM public.ecr.aws/docker/library/node:22-alpine AS build
|
||||
# syntax=docker/dockerfile:1.7
|
||||
# Статическая панель EvoBGP (SvelteKit) + nginx.
|
||||
# Финальный stage `web` ожидает bake-контекст web-artifacts (= target:web-build).
|
||||
FROM public.ecr.aws/docker/library/node:22-alpine AS deps
|
||||
WORKDIR /web
|
||||
COPY web/package.json web/package-lock.json ./
|
||||
RUN npm ci
|
||||
RUN --mount=type=cache,target=/root/.npm,sharing=locked \
|
||||
npm ci
|
||||
|
||||
FROM deps AS build
|
||||
COPY web/ ./
|
||||
RUN npm run build
|
||||
|
||||
FROM public.ecr.aws/docker/library/nginx:1.27-alpine
|
||||
FROM public.ecr.aws/docker/library/nginx:1.27-alpine AS web
|
||||
ARG EVOBGP_UPSTREAM=evobgp-api
|
||||
COPY deploy/docker/evobgp-web/nginx.conf /tmp/nginx-default.conf
|
||||
RUN sed -e "s/evobgp-api/${EVOBGP_UPSTREAM}/g" /tmp/nginx-default.conf > /etc/nginx/conf.d/default.conf && rm -f /tmp/nginx-default.conf
|
||||
COPY --from=build /web/build /usr/share/nginx/html
|
||||
RUN sed -e "s/evobgp-api/${EVOBGP_UPSTREAM}/g" /tmp/nginx-default.conf > /etc/nginx/conf.d/default.conf \
|
||||
&& rm -f /tmp/nginx-default.conf
|
||||
COPY --from=web-artifacts /web/build /usr/share/nginx/html
|
||||
@@ -5,8 +5,14 @@ server {
|
||||
gzip on;
|
||||
gzip_types text/css application/javascript application/json image/svg+xml;
|
||||
|
||||
# Docker embedded DNS: без resolver nginx кэширует IP upstream при старте —
|
||||
# после recreate evobgp-all остаётся 502 (connection refused на старый IP).
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
set $evobgp_upstream evobgp-api;
|
||||
|
||||
location /v1/ {
|
||||
proxy_pass http://evobgp-api:8080/v1/;
|
||||
# С переменной в proxy_pass нельзя полагаться на замену URI — передаём $request_uri целиком.
|
||||
proxy_pass http://$evobgp_upstream:8080$request_uri;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
@@ -15,7 +21,7 @@ server {
|
||||
}
|
||||
|
||||
location = /metrics {
|
||||
proxy_pass http://evobgp-api:8080/metrics;
|
||||
proxy_pass http://$evobgp_upstream:8080/metrics;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
|
||||
@@ -1,19 +1,69 @@
|
||||
# Универсальная сборка бинаря из cmd/* (ARG BIN=evobgp-api | evobgp-all).
|
||||
# INSTALL_BIRDC=1 ставит bird2 в рантайм-образ для EVOBGP_BIRDC_SOCKET (poll метрик birdc).
|
||||
# Базовые образы из ECR Public (официальное зеркало library/*), чтобы CI не зависел от auth.docker.io.
|
||||
FROM public.ecr.aws/docker/library/golang:1.22-bookworm AS build
|
||||
# syntax=docker/dockerfile:1.7
|
||||
# Универсальная сборка бинарей cmd/* (ARG BIN) или всех сразу (target build-all).
|
||||
# INSTALL_BIRDC=1 — birdc из stage birdc (собирается один раз, переиспользуется api/all).
|
||||
# CI: docker buildx bake -f deploy/docker/docker-bake.hcl
|
||||
FROM public.ecr.aws/docker/library/golang:1.24-bookworm AS deps
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
RUN --mount=type=cache,target=/go/pkg/mod,sharing=locked \
|
||||
go mod download
|
||||
|
||||
FROM deps AS build-all
|
||||
COPY . .
|
||||
ARG VERSION=dev
|
||||
ARG GIT_SHA=unknown
|
||||
ARG BUILD_TIME=
|
||||
RUN --mount=type=cache,target=/go/pkg/mod,sharing=locked \
|
||||
--mount=type=cache,target=/root/.cache/go-build,sharing=locked \
|
||||
set -eux; \
|
||||
mkdir -p /out; \
|
||||
for d in cmd/*/; do \
|
||||
name="$(basename "$d")"; \
|
||||
CGO_ENABLED=0 go build -trimpath \
|
||||
-ldflags="-s -w \
|
||||
-X evobgp/internal/version.Version=${VERSION} \
|
||||
-X evobgp/internal/version.GitSHA=${GIT_SHA} \
|
||||
-X evobgp/internal/version.BuildTime=${BUILD_TIME}" \
|
||||
-o "/out/${name}" "./cmd/${name}"; \
|
||||
done
|
||||
|
||||
# Один бинарь (локальная сборка); в CI — build-all + runtime.
|
||||
FROM deps AS build
|
||||
COPY . .
|
||||
ARG BIN=evobgp-api
|
||||
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/evobgp ./cmd/${BIN}
|
||||
ARG VERSION=dev
|
||||
ARG GIT_SHA=unknown
|
||||
ARG BUILD_TIME=
|
||||
RUN --mount=type=cache,target=/go/pkg/mod,sharing=locked \
|
||||
--mount=type=cache,target=/root/.cache/go-build,sharing=locked \
|
||||
CGO_ENABLED=0 go build -trimpath \
|
||||
-ldflags="-s -w \
|
||||
-X evobgp/internal/version.Version=${VERSION} \
|
||||
-X evobgp/internal/version.GitSHA=${GIT_SHA} \
|
||||
-X evobgp/internal/version.BuildTime=${BUILD_TIME}" \
|
||||
-o /out/evobgp "./cmd/${BIN}"
|
||||
|
||||
FROM public.ecr.aws/docker/library/debian:bookworm-slim
|
||||
ARG INSTALL_BIRDC=0
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates \
|
||||
&& if [ "$INSTALL_BIRDC" = "1" ]; then apt-get install -y --no-install-recommends bird2; fi \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY --from=build /out/evobgp /usr/local/bin/evobgp
|
||||
FROM public.ecr.aws/docker/library/debian:bookworm-slim AS birdc
|
||||
ARG BIRD_VERSION=2.14
|
||||
COPY deploy/docker/bird/bird-from-source.sh /tmp/bird-from-source.sh
|
||||
RUN chmod +x /tmp/bird-from-source.sh \
|
||||
&& BIRD_VERSION="${BIRD_VERSION}" /tmp/bird-from-source.sh \
|
||||
&& rm -f /tmp/bird-from-source.sh
|
||||
|
||||
FROM public.ecr.aws/docker/library/debian:bookworm-slim AS runtime-base
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
FROM runtime-base AS runtime
|
||||
ARG BIN=evobgp-api
|
||||
COPY --from=build-all /out/${BIN} /usr/local/bin/evobgp
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["/usr/local/bin/evobgp"]
|
||||
|
||||
FROM runtime AS runtime-birdc
|
||||
# birdc: динамическая линковка readline + ncurses (debian bookworm).
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends libreadline8 libncurses6 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY --from=birdc /usr/local/sbin/bird /usr/local/sbin/birdc /usr/local/sbin/
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env sh
|
||||
# Writes docker-bake.override.hcl for CI (buildx without --var support).
|
||||
set -eu
|
||||
OUT="${1:-docker-bake.override.hcl}"
|
||||
REGISTRY="${REGISTRY:?REGISTRY required}"
|
||||
IMAGE_TAG="${IMAGE_TAG:-latest}"
|
||||
SHORT_SHA="${SHORT_SHA:-dev}"
|
||||
SHA_FULL="${SHA_FULL:-}"
|
||||
VERSION="${VERSION:-dev}"
|
||||
BUILD_TIME="${BUILD_TIME:-}"
|
||||
CACHE_REF_GO="${CACHE_REF_GO:-}"
|
||||
CACHE_REF_WEB="${CACHE_REF_WEB:-}"
|
||||
cat >"$OUT" <<EOF
|
||||
# Generated by deploy/docker/write-bake-override.sh — do not commit.
|
||||
variable "REGISTRY" {
|
||||
default = "${REGISTRY}"
|
||||
}
|
||||
variable "IMAGE_TAG" {
|
||||
default = "${IMAGE_TAG}"
|
||||
}
|
||||
variable "SHORT_SHA" {
|
||||
default = "${SHORT_SHA}"
|
||||
}
|
||||
variable "SHA_FULL" {
|
||||
default = "${SHA_FULL}"
|
||||
}
|
||||
variable "VERSION" {
|
||||
default = "${VERSION}"
|
||||
}
|
||||
variable "BUILD_TIME" {
|
||||
default = "${BUILD_TIME}"
|
||||
}
|
||||
variable "CACHE_REF_GO" {
|
||||
default = "${CACHE_REF_GO}"
|
||||
}
|
||||
variable "CACHE_REF_WEB" {
|
||||
default = "${CACHE_REF_WEB}"
|
||||
}
|
||||
EOF
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
## По роли читателя
|
||||
|
||||
- **ИИ-агент / ассистент в репозитории** — [../AGENTS.md](../AGENTS.md): с чего начать чтение, карта `internal/` и `cmd/`, что не тащить в контекст. **Инженерные правила:** [../.cursor/rules/engineering.mdc](../.cursor/rules/engineering.mdc) (общие), [../.cursor/rules/web-shadcn.mdc](../.cursor/rules/web-shadcn.mdc) (Web UI), [../.cursor/rules/networking-bird.mdc](../.cursor/rules/networking-bird.mdc) (BIRD2/BGP/IP).
|
||||
- **Оператор / DevOps** — [quickstart.md](quickstart.md), [architecture.md](architecture.md), [access.md](access.md), [deploy/compose/docker-compose.yaml](../deploy/compose/docker-compose.yaml).
|
||||
- **Разработчик бэкенда или интегратор API** — [api.md](api.md), [access.md](access.md), [openapi.yaml](openapi.yaml), исходники маршрутов в `internal/httpapi/`.
|
||||
- **Разработчик фронтенда** — [quickstart.md](quickstart.md) (раздел про `web/` и CORS), [api.md](api.md), [../web/README.md](../web/README.md).
|
||||
@@ -15,12 +16,39 @@
|
||||
| [overview.md](overview.md) | Ключевые возможности системы |
|
||||
| [quickstart.md](quickstart.md) | Быстрый запуск: готовые образы из `git.shts.su`, Docker Compose, локальный Go, веб |
|
||||
| [architecture.md](architecture.md) | Компоненты, потоки данных, пакеты |
|
||||
| [manual.md](manual.md) | Подробное руководство по модулям, процессам и API |
|
||||
| [api.md](api.md) | REST: префикс `/v1`, публичные маршруты, ссылки на OpenAPI |
|
||||
| [router-lists-ui-integration.md](router-lists-ui-integration.md) | Интеграция `router-lists-ui` с EvoBGP API (`DOMAINS/IP_RANGES/AS_PREFIXES/communities`) |
|
||||
| [access.md](access.md) | Выдача доступа: API-ключи, роли, нода, CORS |
|
||||
| [remote-speakers.md](remote-speakers.md) | Удалённые BGP-реплики: Traefik, agent sync, compose |
|
||||
| [releasing.md](releasing.md) | Автоматические релизы, Conventional Commits, CI |
|
||||
| [openapi.yaml](openapi.yaml) | Источник правды по контракту API |
|
||||
| [OPENAPI-GITEA.md](OPENAPI-GITEA.md) | Как открыть HTML-документацию API (в т.ч. из Gitea) |
|
||||
| [evobgp-api-sketches.md](evobgp-api-sketches.md) | Ранний черновик идей API (контекст, не замена OpenAPI) |
|
||||
|
||||
## Инженерные правила (Cursor / разработка)
|
||||
|
||||
| Файл | Область |
|
||||
|------|---------|
|
||||
| [../.cursor/rules/engineering.mdc](../.cursor/rules/engineering.mdc) | Go, API, migrations, security, enforcement |
|
||||
| [../.cursor/rules/web-shadcn.mdc](../.cursor/rules/web-shadcn.mdc) | SvelteKit, shadcn-svelte |
|
||||
| [../.cursor/rules/networking-bird.mdc](../.cursor/rules/networking-bird.mdc) | BIRD2, BGP policy, IP/CIDR |
|
||||
| [../.cursor/rules/conventional-commits.mdc](../.cursor/rules/conventional-commits.mdc) | Conventional Commits (заголовок EN, тело RU) |
|
||||
|
||||
### Сообщения коммитов (Cursor)
|
||||
|
||||
После `git add`:
|
||||
|
||||
| Способ | Skill + rule + `staged-context.ps1` |
|
||||
|--------|-------------------------------------|
|
||||
| Agent → **`/commit-message`** или «сгенерируй коммит по staged» | **Да** |
|
||||
| Кнопка **✨ Generate commit message** в Source Control | **Нет** (только diff + история; [ограничение Cursor](https://forum.cursor.com/t/how-to-set-prompt-for-generate-commit-message/148606)) |
|
||||
|
||||
Рекомендуемый workflow: Agent Chat → **`/commit-message`** ([команда](../.cursor/commands/commit-message.md), [скилл](../.cursor/skills/commit-message/SKILL.md), [правило](../.cursor/rules/conventional-commits.mdc)). Агент **обязан первым делом** запустить `scripts/commit/staged-context.ps1` (заголовок EN, тело RU, auto-split).
|
||||
|
||||
Просмотр групп вручную: `powershell -NoProfile -File scripts/commit/staged-context.ps1 | ConvertFrom-Json`.
|
||||
|
||||
## Репозиторий и CI
|
||||
|
||||
- [../.gitea/README.md](../.gitea/README.md) — Gitea Actions, runner, сборка образов и push в Container Registry.
|
||||
- [releasing.md](releasing.md) — semantic-release, commit conventions, теги образов.
|
||||
+36
-4
@@ -22,6 +22,19 @@ opkey|01ARZ3NDEKTSV4RRFFQ69G5FAV|operator,nodekey|01ARZ3NDEKTSV4RRFFQ69G5FAV|nod
|
||||
|
||||
При включённом демо-сиде сервер при старте может вывести в лог готовую подсказку с реальным `tenant_id` из БД — см. лог `evobgp-api` / `evobgp-all`.
|
||||
|
||||
Ключи из `EVOBGP_API_KEYS` загружаются при старте и **дополняют** ключи из таблицы `api_key` в БД (break-glass / bootstrap). После первого operator-ключа можно создавать остальные через API или веб-настройки.
|
||||
|
||||
### Управление через API и UI
|
||||
|
||||
При подключённой БД operator может:
|
||||
|
||||
- `GET|POST /v1/api-keys`, `GET|PATCH|DELETE /v1/api-keys/{id}`, `POST /v1/api-keys/{id}/rotate` — см. OpenAPI, тег **API keys**.
|
||||
- В веб-панели: **Права доступа** (`/access`) → блок «API-ключи» (только для роли `operator`). Токен для браузера — в **Настройки** (`/settings`).
|
||||
|
||||
Полный токен возвращается **один раз** в ответе `201` (создание) и `200` (ротация). В списках — только `prefix` (первые 8 символов). В БД хранится SHA-256 токена, не plaintext.
|
||||
|
||||
`GET /v1/auth/session` — текущие `tenant_id` и `role` (для UI).
|
||||
|
||||
### Роли
|
||||
|
||||
| Роль | Уровень | Назначение |
|
||||
@@ -33,11 +46,16 @@ opkey|01ARZ3NDEKTSV4RRFFQ69G5FAV|operator,nodekey|01ARZ3NDEKTSV4RRFFQ69G5FAV|nod
|
||||
|
||||
Обратное ограничение: для эндпоинтов ноды требуется именно роль **`node`**; остальные роли получают отказ.
|
||||
|
||||
### Режим разработки `EVOBGP_DEV_INSECURE`
|
||||
### Токен `dev` (локальная разработка)
|
||||
|
||||
Если установлено `EVOBGP_DEV_INSECURE=1` и в store доступен демо-tenant (`DemoIDs`), то запрос с заголовком **`Authorization: Bearer dev`** получает контекст **`operator`** для этого tenant.
|
||||
Если в store доступен демо-tenant (`DemoIDs`, обычно `EVOBGP_SEED_DEMO` не равен `0`), заголовок **`Authorization: Bearer dev`** даёт роль **`operator`** для этого tenant. **Не зависит** от `EVOBGP_DEV_INSECURE`.
|
||||
|
||||
**Запрещено** в продакшене: любой, кто знает заголовок, получает полные права оператора на демо-данные.
|
||||
**Запрещено** в продакшене: не оставляйте demo-seed с известным токеном `dev` на боевых данных. Переменная `EVOBGP_DEV_INSECURE` в текущей версии **не влияет** на аутентификацию (оставлена в compose для совместимости; не включайте в production — см. SEC-02 в инженерных правилах).
|
||||
|
||||
### Синхронные «тяжёлые» GET (control plane)
|
||||
|
||||
- `POST /v1/modules/{module_id}/cdn-sources/preview` — загрузка CDN в том же HTTP-запросе (лимит тела ~8 MiB, см. OpenAPI).
|
||||
- `GET /v1/bird/status` (если маршрут включён в деплое) — опрос локального `birdc`, таймаут сервера ~12 с.
|
||||
|
||||
### Детерминированный ключ подписи бандлов (тесты)
|
||||
|
||||
@@ -45,7 +63,9 @@ opkey|01ARZ3NDEKTSV4RRFFQ69G5FAV|operator,nodekey|01ARZ3NDEKTSV4RRFFQ69G5FAV|nod
|
||||
|
||||
## Публичный ключ бандла для нод
|
||||
|
||||
При старте API в лог печатается строка **bundle signing public key (base64)**. Её нужно передать администратору реплики и использовать в `evobgp-node`:
|
||||
При старте API в лог печатается строка **bundle signing public key (base64)**. Альтернатива для operator: **`GET /v1/bundle/signing-public-key`** → поле `public_key_base64` для `EVOBGP_BUNDLE_PUBKEY_BASE64` на реплике.
|
||||
|
||||
Использование в `evobgp-node` / agent:
|
||||
|
||||
```text
|
||||
evobgp-node verify-bundle -f bundle.tar.gz -pubkey-base64 "<из_лога_API>"
|
||||
@@ -58,6 +78,17 @@ evobgp-node apply-bundle -f bundle.tar.gz -extract-dir /path/to/dir -pubkey-base
|
||||
evobgp-node pull-bundle -base-url http://control.example:8080 -token "<node_token>" -speaker-id "<uuid>"
|
||||
```
|
||||
|
||||
## Panel→Node dispatch (удалённые спикеры)
|
||||
|
||||
На control plane (prod):
|
||||
|
||||
```text
|
||||
EVOBGP_NODE_DISPATCH_ENABLED=1
|
||||
EVOBGP_BUNDLE_SEED_HEX=<32 bytes hex, стабильный>
|
||||
```
|
||||
|
||||
После `deploy_apply` CP шлёт `POST https://AGENT_DOMAIN/v1/agent/sync` с `Authorization: Bearer <agent_secret>`. На реплике — `EVOBGP_AGENT_SECRET`, Traefik `PANEL_IP_WHITELIST`. Подробнее: [remote-speakers.md](remote-speakers.md).
|
||||
|
||||
## CORS для веб-интерфейса
|
||||
|
||||
Браузерные запросы с другого origin требуют заголовков CORS на API. Задайте список разрешённых origin через **`EVOBGP_CORS_ORIGINS`** (через запятую), например:
|
||||
@@ -88,6 +119,7 @@ http://localhost:5173,http://127.0.0.1:5173,https://ui.example.com
|
||||
| GET модули, ревизии, peers, speakers | да | да | да | нет |
|
||||
| POST/PATCH/DELETE CRUD сущностей | нет | да | да | нет |
|
||||
| apply, rollback, PATCH settings | нет | нет | да | нет |
|
||||
| Управление API-ключами (`/v1/api-keys`) | нет | нет | да | нет |
|
||||
| bundle, latest revision, enroll | нет | нет | нет | да |
|
||||
|
||||
Точные проверки по каждому маршруту — в коде `internal/httpapi` и в схеме безопасности операций в OpenAPI.
|
||||
|
||||
@@ -44,10 +44,17 @@
|
||||
- `GET|POST /v1/communities`
|
||||
- `GET|PATCH|DELETE /v1/communities/{id}`
|
||||
|
||||
### API keys
|
||||
|
||||
- `GET /v1/auth/session` — tenant и роль текущего ключа
|
||||
- `GET|POST /v1/api-keys` — список и создание (operator)
|
||||
- `GET|PATCH|DELETE /v1/api-keys/{id}`, `POST /v1/api-keys/{id}/rotate`
|
||||
|
||||
### Peers
|
||||
|
||||
- `GET /v1/peers`, `POST /v1/peers`
|
||||
- `GET|PATCH|DELETE /v1/peers/{id}`
|
||||
- Для `POST|PATCH|DELETE` peer запускается быстрый job `peer_reconcile` (без module ingest/сбора префиксов); после него автоматически ставится apply на спикеры.
|
||||
|
||||
### Speakers
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
| `evobgp-render` | По умолчанию только heartbeat; при `EVOBGP_RENDER_AUTOPUBLISH=1` выставляет всем спикерам tenant последнюю ревизию (упрощение для демо). |
|
||||
| `evobgp-deploy` | Периодически логирует **drift**: `last_applied_revision_id` vs опубликованная ревизия для ноды. |
|
||||
| `evobgp-node` | CLI реплики: `pull-bundle`, `verify-bundle`, `apply-bundle`. |
|
||||
| `evobgp-agent` | Локальный агент рядом с BIRD (например `watch` по сокету). |
|
||||
| `evobgp-agent` | Локальный агент рядом с BIRD: `watch`, **`serve`** (Panel→Node sync API на реплике). |
|
||||
|
||||
В Docker Compose профиль **reference** запускает отдельные контейнеры под `evobgp-api` и четыре воркера; профиль **microvps** использует один контейнер `evobgp-all`.
|
||||
|
||||
@@ -40,8 +40,12 @@
|
||||
| `observability` | Метрики Prometheus, HTTP middleware. |
|
||||
| `broker` | Опциональный `EVOBGP_BROKER_URL` для будущей шины; сейчас задачи только in-process (`jobs.Registry`), пакет лишь логирует факт настройки URL. |
|
||||
| `pipeline` | Ingest+render в одном шаге для `module_refresh`: выборка префиксов (CDN/AS/IP/пустые DOMAINS), `CreateRenderRevision`, превью BIRD через `birdfmt`. |
|
||||
| `nodedispatch` | Panel→Node HTTP wake-up (`POST /v1/agent/sync`) после `deploy_apply`. |
|
||||
| `agentserver` | HTTP API на реплике (`serve`): sync + health для Traefik. |
|
||||
|
||||
## Диаграмма: эталонный Compose (reference)
|
||||
## Удалённые спикеры
|
||||
|
||||
Реплики на отдельных VPS: [remote-speakers.md](remote-speakers.md). CP публикует ревизию и при `EVOBGP_NODE_DISPATCH_ENABLED=1` будит agent; agent тянет signed bundle и применяет BIRD. Compose: `deploy/compose/docker-compose.remote-speaker.yaml`.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
|
||||
@@ -59,7 +59,7 @@
|
||||
|
||||
| Метод | Путь | Описание |
|
||||
|-------|------|----------|
|
||||
| `GET` | `/v1/modules/{module_id}/as-entries` | Список ASN/префиксов. |
|
||||
| `GET` | `/v1/modules/{module_id}/as-entries` | Список записей: ASN + community. |
|
||||
| `POST` | `/v1/modules/{module_id}/as-entries` | Добавить. |
|
||||
| `PATCH` | `/v1/modules/{module_id}/as-entries/{entry_id}` | Обновить. |
|
||||
| `DELETE` | `/v1/modules/{module_id}/as-entries/{entry_id}` | Удалить. |
|
||||
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
# Полное руководство по EvoBGP
|
||||
|
||||
Этот документ объединяет эксплуатационное и разработческое описание системы: что делает каждый процесс, как двигаются данные, какие API использовать и где искать причины инцидентов.
|
||||
|
||||
## 1. Назначение системы
|
||||
|
||||
EvoBGP управляет генерацией и применением BGP-конфигураций на основе модулей источников префиксов (`AS_PREFIXES`, `CDN_CIDRS`, `DOMAINS`, `IP_RANGES`).
|
||||
|
||||
Система разделена на:
|
||||
- **control plane**: API, БД, jobs, рендер ревизий, публикация и подписание бандлов;
|
||||
- **data plane**: BIRD и связанный агент/нода для применения ревизий.
|
||||
|
||||
## 2. Компоненты и роли бинарников (`cmd/*`)
|
||||
|
||||
### `evobgp-api`
|
||||
- Основной HTTP API.
|
||||
- Поднимает маршруты из `internal/httpapi`.
|
||||
- Работает с `store`/`repository`, jobs и аутентификацией.
|
||||
|
||||
### `evobgp-all`
|
||||
- Монолитный режим: API + scheduler + ingest + render + deploy в одном процессе.
|
||||
- Удобен для компактных окружений (`microvps`).
|
||||
|
||||
### `evobgp-scheduler`
|
||||
- Периодически запускает `module_refresh` по расписанию/интервалам.
|
||||
- В reference-профиле может стучаться в API и/или работать через store.
|
||||
|
||||
### `evobgp-ingest`
|
||||
- Периодически делает prefetch внешних CDN-источников (ETag/доступность).
|
||||
|
||||
### `evobgp-render`
|
||||
- Ведёт рендер-цикл; в режиме autopublish может назначать последнюю ревизию на спикеры.
|
||||
|
||||
### `evobgp-deploy`
|
||||
- Диагностирует drift: различия между опубликованной и применённой ревизией.
|
||||
|
||||
### `evobgp-node`
|
||||
- CLI-нода для edge: загрузка бандла, верификация подписи, применение.
|
||||
|
||||
### `evobgp-agent`
|
||||
- Локальный агент рядом с BIRD (наблюдение и служебные операции).
|
||||
|
||||
## 3. Карта внутренних модулей (`internal/*`)
|
||||
|
||||
### API и доступ
|
||||
- `internal/httpapi`: маршруты, auth, CORS, problem+json, CRUD, jobs endpoints.
|
||||
|
||||
### Данные
|
||||
- `internal/store`: бизнес-контракты бэкенда.
|
||||
- `internal/repository`: PostgreSQL-реализация.
|
||||
- `internal/db`: коннект и миграции.
|
||||
|
||||
### Jobs/pipeline
|
||||
- `internal/jobs`: очередь задач и worker.
|
||||
- `internal/pipeline`: `module_refresh`, сбор источников, материализация, рендер-превью.
|
||||
- `internal/scheduler`, `internal/ingest`, `internal/render`, `internal/deploy`: фоновые циклы.
|
||||
|
||||
### BIRD и бандлы
|
||||
- `internal/birdfmt`: генерация конфигурации BIRD.
|
||||
- `internal/birddeploy`: применение конфигурации и интеграция с `birdc`.
|
||||
- `internal/bundle`, `internal/signing`: упаковка и криптографическая проверка.
|
||||
|
||||
### Наблюдаемость и служебные
|
||||
- `internal/observability`: метрики/middleware.
|
||||
- `internal/asnresolve`: внешние резолвы ASN.
|
||||
- `internal/broker`: задел под внешний брокер.
|
||||
- `internal/config`, `internal/platform`: параметры среды и платформенные адаптеры.
|
||||
|
||||
## 4. Сквозной поток данных
|
||||
|
||||
1. Оператор меняет данные модуля (CRUD источников, peers/speakers, настройки).
|
||||
2. Включённый модуль триггерит `module_refresh`.
|
||||
3. `jobs.Worker` вызывает `pipeline.RefreshModule`.
|
||||
4. Pipeline собирает префиксы всех enabled-модулей tenant, строит materialized snapshot.
|
||||
5. Создаётся ревизия и BIRD preview.
|
||||
6. По операциям deploy/apply ревизия применяется на спикере.
|
||||
7. Нода получает бандл, проверяет подпись, применяет локально.
|
||||
|
||||
## 5. API: ключевые группы и сценарии
|
||||
|
||||
Источник истины контракта: `docs/openapi.yaml`.
|
||||
|
||||
### Основные группы endpoint-ов
|
||||
- `Modules`: модули и их общие параметры.
|
||||
- `AS Entries`, `CDN Sources`, `Domain Entries`, `IP Range Entries`: источники префиксов.
|
||||
- `Peers`, `Speakers`: сетевая топология применения.
|
||||
- `Revisions`, `Deploy`, `Jobs`: жизненный цикл ревизий и фоновых задач.
|
||||
- `Settings`: глобальные KV-настройки.
|
||||
- `Node`: edge-флоу бандлов/enrollment.
|
||||
|
||||
### Типовой сценарий оператора
|
||||
1. Создать/обновить модуль и его источники.
|
||||
2. Дождаться или инициировать refresh.
|
||||
3. Проверить ревизию и diff.
|
||||
4. Выполнить apply на целевой спикер.
|
||||
5. Проверить health/monitoring/jobs.
|
||||
|
||||
## 6. Настройки и доступ
|
||||
|
||||
### Аутентификация/роли
|
||||
- Роли и правила доступа: `docs/access.md`.
|
||||
- Для мутаций критичных сущностей требуется `editor`/`operator`.
|
||||
|
||||
### Настройки (`/v1/settings`)
|
||||
- KV c ключами BIRD и дополнительными feature flags.
|
||||
- Ключевые параметры BIRD: `bird_router_id`, `bird_local_ipv4`, `bird_local_ipv6`, `bird_local_asn`, `bird_bgp_source_ipv4`, `bird_bgp_source_ipv6`.
|
||||
- **Tenant settings** — глобальный default. **Per-speaker** override: `meta_json.bird_bgp_source_ipv4` / `node_ipv4` в карточке спикера (Web UI → Сеть → Спикеры); pipeline накладывает overlay при сборке бандла для реплики. См. [remote-speakers.md](remote-speakers.md).
|
||||
|
||||
## 7. Эксплуатация и runbook
|
||||
|
||||
### Что проверять при инцидентах
|
||||
1. Статус API и БД.
|
||||
2. Состояние jobs (`module_refresh`, `deploy_apply`), ошибки в job meta.
|
||||
3. Состояние внешних источников (CDN/DoH/ASN).
|
||||
4. Состояние BIRD и применённой ревизии на спикере.
|
||||
|
||||
### Частые причины проблем
|
||||
- Невалидные данные источников (непарсящийся JSON/plaintext для CDN).
|
||||
- Неполные настройки BIRD.
|
||||
- Ошибки внешних upstream (RIPEstat/DoH/CDN).
|
||||
- Расхождение published/applied ревизии.
|
||||
|
||||
## 8. Разработка и расширение
|
||||
|
||||
### Где вносить изменения
|
||||
- Новый endpoint: `internal/httpapi` + обновление `docs/openapi.yaml`.
|
||||
- Новая логика источника: `internal/pipeline` + соответствующие CRUD/store/repository.
|
||||
- Новая операция UI: `web/src/routes/*` и `web/src/lib/components/*`.
|
||||
|
||||
### Рекомендации по качеству
|
||||
- Для изменений API всегда обновлять `docs/openapi.yaml`.
|
||||
- Для изменений UI держаться единого набора компонентов shadcn-svelte и Lucide.
|
||||
- Для pipeline-изменений добавлять метрики стадии и явные trigger-метки job.
|
||||
|
||||
## 9. Индекс исходников (быстрый вход)
|
||||
|
||||
- Архитектура: `docs/architecture.md`
|
||||
- API обзор: `docs/api.md`
|
||||
- Контракт API: `docs/openapi.yaml`
|
||||
- Доступ/роли: `docs/access.md`
|
||||
- Web запуск: `web/README.md`
|
||||
- Compose: `deploy/compose/docker-compose.yaml`
|
||||
|
||||
+880
-22
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -8,7 +8,7 @@ EvoBGP — это control plane для описания источников п
|
||||
|
||||
| Тип | Назначение |
|
||||
|-----|------------|
|
||||
| `AS_PREFIXES` | ASN и связанные префиксы |
|
||||
| `AS_PREFIXES` | Номера AS и привязка к BGP community (без статического CIDR в записи) |
|
||||
| `CDN_CIDRS` | CIDR из внешних CDN-источников (URL, виды источников) |
|
||||
| `DOMAINS` | FQDN с привязкой к BGP community; опционально DoH-профили |
|
||||
| `IP_RANGES` | Статические CIDR + `community_id` (данные в БД, без внешнего ingest по URL) |
|
||||
|
||||
+48
-7
@@ -109,35 +109,72 @@ docker compose --profile microvps down -v
|
||||
|
||||
Из каталога `deploy\compose` (как в варианте 1: `.env` из `.env.example`, при необходимости `docker login git.shts.su`):
|
||||
|
||||
1. Подготовьте отдельный файл параметров защищенного UI:
|
||||
|
||||
```powershell
|
||||
Copy-Item .env.web-sec.example .env.web-sec -Force
|
||||
```
|
||||
|
||||
2. Заполните в `.env.web-sec`:
|
||||
- `WEBUI_DOMAIN` — домен панели;
|
||||
- `WEBUI_IP_WHITELIST` — список разрешенных IP/CIDR через запятую;
|
||||
- `LETSENCRYPT_EMAIL` — email для ACME;
|
||||
- `CF_DNS_API_TOKEN` — Cloudflare token для `DNS challenge` (минимальные права `Zone:DNS:Edit` на нужной зоне).
|
||||
|
||||
3. В Cloudflare для `WEBUI_DOMAIN` используйте запись в режиме **DNS only** (серый облачок), указывающую на публичный IP VPS.
|
||||
|
||||
4. Запускайте compose с двумя env-файлами:
|
||||
|
||||
```powershell
|
||||
# С ужатыми лимитами и EVOBGP_BROKER_URL=nats://… (ориентир под ~1 ГиБ RAM на хосте)
|
||||
docker compose -f docker-compose.yaml -f docker-compose.microvps-full.yaml --profile microvps-full pull
|
||||
docker compose -f docker-compose.yaml -f docker-compose.microvps-full.yaml --profile microvps-full up -d
|
||||
docker compose --env-file .env --env-file .env.web-sec -f docker-compose.yaml -f docker-compose.microvps-full.yaml --profile microvps-full pull
|
||||
docker compose --env-file .env --env-file .env.web-sec -f docker-compose.yaml -f docker-compose.microvps-full.yaml --profile microvps-full up -d
|
||||
```
|
||||
|
||||
Только профиль `microvps-full` и **без** файла `docker-compose.microvps-full.yaml` (лимиты как в базовом compose, без принудительной подстановки брокера в `evobgp-all`):
|
||||
|
||||
```powershell
|
||||
docker compose --profile microvps-full pull
|
||||
docker compose --profile microvps-full up -d
|
||||
docker compose --env-file .env --env-file .env.web-sec --profile microvps-full pull
|
||||
docker compose --env-file .env --env-file .env.web-sec --profile microvps-full up -d
|
||||
```
|
||||
|
||||
При необходимости задайте брокер вручную для `evobgp-all` (override или `.env` рядом с compose): `EVOBGP_BROKER_URL=nats://nats:4222`.
|
||||
|
||||
| Порт | Назначение |
|
||||
|------|------------|
|
||||
| **3000** | Web UI (nginx → API под капотом) |
|
||||
| **80** | HTTP вход (редирект на HTTPS через Traefik) |
|
||||
| **443** | HTTPS Web UI (Traefik + Let's Encrypt) |
|
||||
| **8080** | Прямой HTTP API (`evobgp-all`) |
|
||||
| **9090** | Prometheus (`prometheus-microvps`) |
|
||||
| **4222** | NATS |
|
||||
| **179** | BGP (BIRD2), как в варианте 1 |
|
||||
|
||||
Проверка UI: откройте `http://<IP-вашей-VPS>:3000`. Health API: `http://<IP>:8080/v1/health`.
|
||||
Проверка UI:
|
||||
- `http://<WEBUI_DOMAIN>` должен редиректить на `https://<WEBUI_DOMAIN>`;
|
||||
- с IP из `WEBUI_IP_WHITELIST` UI доступен по HTTPS;
|
||||
- с неразрешенного IP Traefik вернет `403`.
|
||||
|
||||
Health API: `http://<IP>:8080/v1/health`.
|
||||
|
||||
### Auto-updater для standalone stack (без рестарта BIRD2)
|
||||
|
||||
Для `stack.microvps-full.yaml` можно включить автообновление только выбранных сервисов (например, `evobgp-all,evobgp-web`) по digest образов в registry.
|
||||
|
||||
В файле `deploy\compose\.env.stack.microvps-full`:
|
||||
|
||||
- `AUTO_UPDATE_ENABLED=1` — включить updater;
|
||||
- `AUTO_UPDATE_INTERVAL_SEC=300` — период проверки;
|
||||
- `AUTO_UPDATE_SERVICES=evobgp-all,evobgp-web` — allowlist сервисов;
|
||||
- `AUTO_UPDATE_PROTECTED_SERVICES=bird2` — список защищённых сервисов (по умолчанию `bird2`).
|
||||
|
||||
Updater делает `pull` и при изменении образа выполняет `up -d --no-deps` только для сервиса из allowlist. `bird2` в обновление не попадает, пока явно указан в protected-списке.
|
||||
|
||||
Важно: updater использует доступ к `docker.sock` (высокие привилегии), включайте осознанно.
|
||||
|
||||
Остановка (если поднимали с двумя `-f`):
|
||||
|
||||
```powershell
|
||||
docker compose -f docker-compose.yaml -f docker-compose.microvps-full.yaml --profile microvps-full down
|
||||
docker compose --env-file .env --env-file .env.web-sec -f docker-compose.yaml -f docker-compose.microvps-full.yaml --profile microvps-full down
|
||||
```
|
||||
|
||||
## Вариант 2: Docker, профиль reference
|
||||
@@ -166,6 +203,10 @@ docker compose --profile reference up -d
|
||||
|
||||
В **evobgp-all** (microvps) те же пакеты крутятся в одном процессе и используют общий `jobs.Registry` без HTTP.
|
||||
|
||||
## Удалённые BGP-спикеры
|
||||
|
||||
Реплики на отдельных VPS (bird2 + agent + Traefik): см. **[remote-speakers.md](remote-speakers.md)**. На CP включите `EVOBGP_NODE_DISPATCH_ENABLED=1` и зафиксируйте `EVOBGP_BUNDLE_SEED_HEX`. Compose: `deploy/compose/docker-compose.remote-speaker.yaml`.
|
||||
|
||||
## Вариант 3: Локально без Docker (только API)
|
||||
|
||||
1. Поднимите PostgreSQL и создайте БД (или используйте существующую).
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
# Релизы и версионирование EvoBGP
|
||||
|
||||
EvoBGP использует [Conventional Commits](https://www.conventionalcommits.org/) и [semantic-release](https://semantic-release.gitbook.io/) для полностью автоматических релизов на Gitea (`git.shts.su`). Ручное повышение версии в коде не требуется.
|
||||
|
||||
## Как определяется версия
|
||||
|
||||
| Тип коммита | Bump |
|
||||
|-------------|------|
|
||||
| `feat` | minor (1.0.0 → 1.1.0) |
|
||||
| `fix`, `perf`, `ci`, `refactor` | patch (1.5.1 → 1.5.2) |
|
||||
| `feat!`, `fix!` или `BREAKING CHANGE:` в теле | major (1.0.0 → 2.0.0) |
|
||||
| `docs`, `chore`, `test` | без релиза |
|
||||
|
||||
**Scope:** один идентификатор **без запятых** (`web`, `httpapi`, `api`). Заголовок `refactor(a, b): …` **не парсится** semantic-release → релиз не создаётся (commitlint на PR это тоже отклонит). Подробнее — раздел «Scope и semantic-release» ниже.
|
||||
|
||||
`refactor` — patch без новых функций: перестройка кода/UI при том же поведении для пользователя. По semver на одном уровне с `fix`, но семантически «мельче» `feat` (не minor).
|
||||
|
||||
Отдельного суффикса `1.x.y.fix` в semver нет: «fix» в Conventional Commits означает **patch** (третья цифра). Для починки пайплайна без смены продукта — `fix(ci):` или `ci:` (оба дают patch после настройки `.releaserc.json`).
|
||||
|
||||
Первый релиз при отсутствии git-тегов — **1.0.0**, если есть releasable-коммиты.
|
||||
|
||||
**Как не перепутать `feat` и `fix`:** см. раздел «Выбор type: semver, а не «красивые слова»» в [.cursor/rules/conventional-commits.mdc](../.cursor/rules/conventional-commits.mdc). Кратко: `feat` — новая возможность (minor); `fix` — починка ожидаемого поведения (patch); follow-up баги после недавнего `feat` — всегда `fix`, даже если diff большой.
|
||||
|
||||
Подробные правила сообщений коммитов: [.cursor/rules/conventional-commits.mdc](../.cursor/rules/conventional-commits.mdc).
|
||||
|
||||
## CI-пайплайн (один push в main)
|
||||
|
||||
```text
|
||||
push/merge в main
|
||||
→ CI: openapi, web, go, bird2 (параллельно)
|
||||
→ job release (в том же workflow, после quality gates):
|
||||
→ semantic-release: git tag vX.Y.Z на текущий commit (без доп. commit)
|
||||
→ Gitea Release + CHANGELOG.md как attachment
|
||||
→ docker buildx bake с VERSION=X.Y.Z
|
||||
→ образы: latest, vX.Y.Z, X.Y.Z, sha-*, короткий SHA
|
||||
```
|
||||
|
||||
Pull request: только quality gates + commitlint; релиз и образы **не** публикуются.
|
||||
|
||||
Workflow: [.gitea/workflows/ci.yaml](../.gitea/workflows/ci.yaml) (job **release**).
|
||||
|
||||
Конфиг semantic-release: [.releaserc.json](../.releaserc.json) — без `@semantic-release/git` (CHANGELOG не коммитится в репозиторий).
|
||||
|
||||
## Секреты Gitea
|
||||
|
||||
Один PAT — **`ACTIONS_PAT`** (Settings → Actions → Secrets).
|
||||
|
||||
| Право PAT | Зачем |
|
||||
|-----------|--------|
|
||||
| push tags | git tag `vX.Y.Z` на commit merge |
|
||||
| releases | Gitea Release + notes |
|
||||
| packages (Container Registry) | push образов |
|
||||
|
||||
Fallback: **`gitea.token`** (нужны права на releases и packages).
|
||||
|
||||
## Источник правды для версии в runtime
|
||||
|
||||
Semver из git-тега пробрасывается в Go-бинарники через `-ldflags` при сборке Docker (`deploy/docker/gobinary/Dockerfile`). Пакет [`internal/version`](../internal/version/version.go):
|
||||
|
||||
- локально (`go run`) — `version: "dev"`
|
||||
- в образе после релиза — совпадает с тегом (например `1.2.3`)
|
||||
|
||||
API: `GET /version`, `GET /v1/version` — поля `version`, `git_sha`, `build_time`.
|
||||
|
||||
Web UI показывает версию из API (footer sidebar, страница «Мониторинг»).
|
||||
|
||||
## Scope и semantic-release
|
||||
|
||||
Парсер [conventional-commits-parser](https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-commits-parser) (его использует semantic-release) **не понимает запятые в scope**:
|
||||
|
||||
| Заголовок | Парсится | Релиз |
|
||||
|-----------|----------|-------|
|
||||
| `refactor(web): fix layout` | да, `refactor` | patch |
|
||||
| `refactor(NetworkOverviewTab, NetworkSpeakersCard): fix layout` | **нет**, `type: null` | **нет** |
|
||||
|
||||
Правило: **один scope** из таблицы в [.cursor/rules/conventional-commits.mdc](../.cursor/rules/conventional-commits.mdc) (`web`, `httpapi`, `api`, …).
|
||||
|
||||
На push в `main` job **release** запускает `scripts/commit/verify-release-commits.mjs` — в логе будут предупреждения о непарсящихся коммитах.
|
||||
|
||||
Если релиз «не создался», а CI зелёный: смотрите лог release — часто `No releasable commits`. Исправление: новый коммит с корректным заголовком (например `refactor(web): …`).
|
||||
|
||||
## CHANGELOG
|
||||
|
||||
Release notes — в Gitea Release; файл `CHANGELOG.md` генерируется в CI и прикрепляется как asset, **не** попадает в git history.
|
||||
|
||||
## Проверка после релиза
|
||||
|
||||
1. Один run workflow **CI** на push в main: job **release** зелёный.
|
||||
2. Gitea: тег `vX.Y.Z` на том же commit, что и merge; Release с notes.
|
||||
3. Container Registry: `evobgp-api:vX.Y.Z`, `evobgp-api:X.Y.Z`, `evobgp-api:latest`.
|
||||
4. `curl http://localhost:8080/version` → `"version":"X.Y.Z"`.
|
||||
|
||||
## Первый релиз (bootstrap)
|
||||
|
||||
Merge в `main` с `feat(release): ...` → **v1.0.0** в том же CI run.
|
||||
@@ -0,0 +1,118 @@
|
||||
# Удалённые BGP-спикеры (Remnawave-style)
|
||||
|
||||
Runbook для реплик **bird2 + evobgp-agent** на отдельных VPS. Control plane (`evobgp-all`) инициирует доставку после `module_refresh` → `deploy_apply`; реплика **не** собирает префиксы сама.
|
||||
|
||||
## Модель
|
||||
|
||||
| Remnawave | EvoBGP |
|
||||
|-----------|--------|
|
||||
| Panel → Node:PORT | CP POST `https://AGENT_DOMAIN/v1/agent/sync` |
|
||||
| SECRET_KEY | `agent_secret` (Bearer) |
|
||||
| Copy compose | Web UI → карточка спикера |
|
||||
| Push Xray JSON | Wake-up → pull signed bundle → verify Ed25519 → apply |
|
||||
|
||||
Подробнее: [architecture.md](architecture.md).
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
1. **CP (microvps-full):** зафиксируйте `EVOBGP_BUNDLE_SEED_HEX` (32 байта hex) — стабильный ключ подписи бандлов.
|
||||
2. **Web UI → Сеть → Спикеры:** создайте спикер `role=replica`, укажите **Agent domain**, **IP ноды**, **BGP source** (по умолчанию = IP ноды).
|
||||
3. Сохраните **`agent_secret`** (показывается один раз) и скопируйте **docker-compose** из UI.
|
||||
4. Выдайте **node API-ключ** ([access.md](access.md)) для `EVOBGP_NODE_TOKEN`.
|
||||
5. `GET /v1/bundle/signing-public-key` → `EVOBGP_BUNDLE_PUBKEY_BASE64` на реплике.
|
||||
6. На VPS реплики:
|
||||
```bash
|
||||
cd deploy/compose
|
||||
cp .env.remote-speaker.example .env.remote-speaker
|
||||
cp .env.remote-speaker-tls.example .env.remote-speaker-tls
|
||||
# заполните переменные из UI
|
||||
docker compose -f docker-compose.remote-speaker.yaml \
|
||||
--env-file .env.remote-speaker --env-file .env.remote-speaker-tls \
|
||||
--profile production up -d
|
||||
```
|
||||
7. **CP:** `EVOBGP_NODE_DISPATCH_ENABLED=1` — Panel шлёт wake-up после publish.
|
||||
8. Cloudflare: `AGENT_DOMAIN` → IP VPS, **DNS only** (как Web UI в [quickstart.md](quickstart.md)).
|
||||
|
||||
## Compose-профили
|
||||
|
||||
| Profile | Состав |
|
||||
|---------|--------|
|
||||
| `production` | bird2 (host) + agent + Traefik LE |
|
||||
| `plain` | bird2 + agent на хосте без Traefik (только lab) |
|
||||
| `fallback` | + `sync-bundle` polling (`scripts/sync-bundle.sh`) |
|
||||
|
||||
Файлы: [docker-compose.remote-speaker.yaml](../deploy/compose/docker-compose.remote-speaker.yaml).
|
||||
|
||||
## Firewall
|
||||
|
||||
| Порт | Кто | Зачем |
|
||||
|------|-----|-------|
|
||||
| **443** | IP CP (`PANEL_IP_WHITELIST`) | HTTPS dispatch, health, **`GET /v1/agent/bird/protocols`** (live peer sessions) |
|
||||
| **179** | BGP peers | Data plane |
|
||||
| **80** | ACME | Traefik → 443 |
|
||||
|
||||
## Подготовка VPS (перед `docker compose up`)
|
||||
|
||||
`bird2` — **`network_mode: host`**. Docker **не может** задать `net.ipv4.ip_forward` в таком контейнере; включите на **хосте**:
|
||||
|
||||
```bash
|
||||
sysctl -w net.ipv4.ip_forward=1
|
||||
sysctl -w net.ipv6.conf.all.forwarding=1
|
||||
echo 'net.ipv4.ip_forward=1' | tee /etc/sysctl.d/99-evobgp-bird.conf
|
||||
echo 'net.ipv6.conf.all.forwarding=1' >> /etc/sysctl.d/99-evobgp-bird.conf
|
||||
sysctl --system
|
||||
```
|
||||
|
||||
## Безопасность (три участка)
|
||||
|
||||
1. **CP → реплика:** HTTPS (LE) + Traefik ipallowlist + `agent_secret`.
|
||||
2. **Реплика → CP:** HTTPS + роль `node` (только bundle/latest/enroll).
|
||||
3. **Конфиг:** Ed25519 `bundle.sig`, SHA-256 manifest, `bird -p`, LKG на ноде.
|
||||
|
||||
Prod checklist:
|
||||
|
||||
- [ ] `EVOBGP_CONTROL_PLANE_URL=https://...`
|
||||
- [ ] `EVOBGP_NODE_DISPATCH_ENABLED=1` на CP
|
||||
- [ ] `EVOBGP_BUNDLE_SEED_HEX` на CP (не менять после выдачи pubkey репликам)
|
||||
- [ ] Уникальные `agent_secret` и node token на спикер
|
||||
- [ ] Не использовать profile `plain` в prod
|
||||
- [ ] Не отключать verify-bundle в agent
|
||||
|
||||
## Per-speaker BGP source
|
||||
|
||||
В UI: **IP ноды** (`meta_json.node_ipv4`) и **BGP source IPv4** (`bird_bgp_source_ipv4`, default = IP ноды). Pipeline накладывает overlay при `GET .../bundle/{revision_id}` — меняются `router id` и peer `local`.
|
||||
|
||||
Tenant `/v1/settings` (`bird_bgp_source_ipv4`) — fallback для master / если у спикера не задано.
|
||||
|
||||
## Drift и dispatch
|
||||
|
||||
- `published_revision_id` vs `last_applied_revision_id` — в UI и `evobgp-deploy`.
|
||||
- Job `deploy_apply` meta: `node_dispatch.results[]` — статус wake-up per speaker.
|
||||
- Canary: `POST /v1/speakers/{id}/apply` с `revision_id`.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Симптом | Проверка |
|
||||
|---------|----------|
|
||||
| `sysctl net.ipv4.ip_forward not allowed in host network` | Уберите sysctls из compose (уже так в main); включите ip_forward на VPS (см. выше) |
|
||||
| `no service selected` | `--profile production` или `COMPOSE_PROFILES=production` |
|
||||
| Offline в UI | `GET https://AGENT_DOMAIN/v1/agent/health` с CP; LE cert; whitelist |
|
||||
| dispatch error | CP logs job meta; firewall 443; `agent_secret` |
|
||||
| verify-bundle fail | pubkey совпадает с CP seed; пересоберите pubkey после смены seed |
|
||||
| BGP не поднимается | bird2 `network_mode: host`; peers; MD5 BGP отдельно от HTTP sync |
|
||||
|
||||
## Ограничения (scale-review)
|
||||
|
||||
- Peers **не** фильтруются по `speaker_id` — один tenant-wide peers fragment на все реплики.
|
||||
- Разные peer-наборы per site — отдельная итерация pipeline.
|
||||
- Если Panel не достучится до agent — включите profile `fallback` (polling).
|
||||
|
||||
## Связанные env
|
||||
|
||||
| Переменная | Где |
|
||||
|------------|-----|
|
||||
| `EVOBGP_NODE_DISPATCH_ENABLED=1` | CP |
|
||||
| `EVOBGP_AGENT_SECRET` | реплика |
|
||||
| `EVOBGP_NODE_TOKEN` | реплика |
|
||||
| `EVOBGP_BUNDLE_PUBKEY_BASE64` | реплика |
|
||||
| `PANEL_IP_WHITELIST` | Traefik на реплике |
|
||||
@@ -0,0 +1,119 @@
|
||||
# Интеграция router-lists-ui с EvoBGP API
|
||||
|
||||
Документ описывает подключение разделов `Домены`, `IP-диапазоны`, `AS`, `Community` из проекта `router-lists-ui` напрямую к EvoBGP API (`/v1`).
|
||||
|
||||
Источник правды по контракту: [openapi.yaml](openapi.yaml).
|
||||
|
||||
## 1. Базовые требования
|
||||
|
||||
- Base URL API: `https://<evobgp-host>/v1`
|
||||
- Аутентификация: `Authorization: Bearer <api_key>`
|
||||
- CORS на стороне EvoBGP: переменная `EVOBGP_CORS_ORIGINS`
|
||||
- Роли:
|
||||
- чтение: `viewer+`
|
||||
- изменение данных: `editor+`
|
||||
- apply/деплой: `operator`
|
||||
|
||||
## 2. Маппинг legacy -> EvoBGP
|
||||
|
||||
| Раздел UI | Legacy endpoint | EvoBGP endpoint |
|
||||
|---|---|---|
|
||||
| Домены | `/api/domains-new` | `/v1/modules?type=DOMAINS` + `/v1/modules/{module_id}/domain-entries` |
|
||||
| IP-диапазоны | `/api/ip-ranges` | `/v1/modules?type=IP_RANGES` + `/v1/modules/{module_id}/ip-range-entries` |
|
||||
| AS | `/api/asns` | `/v1/modules?type=AS_PREFIXES` + `/v1/modules/{module_id}/as-entries` |
|
||||
| Community | `/api/communities` | `/v1/communities` |
|
||||
|
||||
Для упрощённой интеграции доступен агрегированный endpoint: `GET /v1/router-lists/catalog` (модули + entries + communities в одном ответе).
|
||||
|
||||
## 3. Маппинг полей
|
||||
|
||||
| Legacy модель | EvoBGP модель | Комментарий |
|
||||
|---|---|---|
|
||||
| `{ domain, community }` | `DomainEntry { fqdn, community_id }` | `community` в UI резолвится в `community_id` через `/v1/communities` |
|
||||
| `{ ipRange, community }` | `IpRangeEntry { prefix, community_id }` | Для `IP_RANGES` `community_id` обязателен |
|
||||
| `{ domain, type }` (AS) | `AsEntry { asn, community_id }` | `domain` legacy = ASN |
|
||||
| `{ value, name }` (Community dict) | `BgpCommunity { community, title }` | `value -> community`, `name -> title` |
|
||||
|
||||
## 4. Алгоритм работы по разделам
|
||||
|
||||
### 4.1 Домены / IP / AS (общая схема)
|
||||
|
||||
1. Найти модуль нужного типа через `GET /v1/modules?type=...`.
|
||||
2. Если модуль отсутствует, создать через `POST /v1/modules`.
|
||||
3. Загрузить entries:
|
||||
- домены: `GET /v1/modules/{module_id}/domain-entries`
|
||||
- IP: `GET /v1/modules/{module_id}/ip-range-entries`
|
||||
- AS: `GET /v1/modules/{module_id}/as-entries`
|
||||
4. При сохранении:
|
||||
- удалить отсутствующие записи (`DELETE .../{entry_id}`)
|
||||
- обновить изменённые (`PATCH .../{entry_id}`)
|
||||
- добавить новые (`POST ...`)
|
||||
|
||||
### 4.2 Community
|
||||
|
||||
1. Получить список: `GET /v1/communities`
|
||||
2. Для сохранения diff:
|
||||
- новые -> `POST /v1/communities`
|
||||
- изменённые -> `PATCH /v1/communities/{id}`
|
||||
- удалённые -> `DELETE /v1/communities/{id}`
|
||||
|
||||
## 5. Разрешение community
|
||||
|
||||
- Перед работой с entries загрузить `/v1/communities`.
|
||||
- Основной путь: сопоставление по `id`.
|
||||
- Для UI-формы использовать значение `community` (например, `65001:120`) и перед записью преобразовывать в `community_id`.
|
||||
- Если community не найдена:
|
||||
- для `IP_RANGES` считать ошибкой валидации;
|
||||
- для `DOMAINS` и `AS_PREFIXES` можно передать `null` только если это допускается бизнес-логикой.
|
||||
|
||||
## 6. Пагинация и ошибки
|
||||
|
||||
- Списки используют `cursor + limit`.
|
||||
- Формат ошибок: `application/problem+json` (RFC 9457).
|
||||
- Базовая обработка:
|
||||
- `401` — неверный/отсутствующий токен
|
||||
- `403` — недостаточно прав
|
||||
- `404` — ресурс не найден
|
||||
- `422` — ошибка валидации
|
||||
|
||||
## 7. Примеры (PowerShell)
|
||||
|
||||
```powershell
|
||||
$base = "http://localhost:8080/v1"
|
||||
$token = "YOUR_API_KEY"
|
||||
$h = @{ Authorization = "Bearer $token" }
|
||||
|
||||
# 1) Найти модуль DOMAINS
|
||||
$modules = Invoke-RestMethod -Uri "$base/modules?type=DOMAINS&limit=50" -Headers $h
|
||||
$moduleId = $modules.items[0].id
|
||||
|
||||
# 2) Прочитать домены
|
||||
Invoke-RestMethod -Uri "$base/modules/$moduleId/domain-entries?limit=100" -Headers $h
|
||||
```
|
||||
|
||||
```powershell
|
||||
# Создать community
|
||||
$body = @{
|
||||
community = "65001:120"
|
||||
title = "Video"
|
||||
} | ConvertTo-Json
|
||||
|
||||
Invoke-RestMethod -Method Post -Uri "$base/communities" -Headers $h -ContentType "application/json" -Body $body
|
||||
```
|
||||
|
||||
## 8. Настройки router-lists-ui для прямой интеграции
|
||||
|
||||
Рекомендуемые переменные frontend:
|
||||
|
||||
- `VITE_EVOBGP_API_URL` (по умолчанию `/v1`)
|
||||
- `VITE_EVOBGP_API_TOKEN` (опционально; либо хранить токен в `localStorage` как `evobgp_api_token`)
|
||||
|
||||
Для dev-прокси Vite добавить маршрут `/v1 -> http://localhost:8080`.
|
||||
|
||||
## 9. Контрольный список интеграции
|
||||
|
||||
- [ ] `Домены`: list/create/update/delete работают через `/v1/modules/{id}/domain-entries`
|
||||
- [ ] `IP-диапазоны`: list/create/update/delete работают через `/v1/modules/{id}/ip-range-entries`
|
||||
- [ ] `AS`: list/create/update/delete работают через `/v1/modules/{id}/as-entries`
|
||||
- [ ] `Community`: CRUD работает через `/v1/communities`
|
||||
- [ ] ошибки `problem+json` корректно отображаются в UI
|
||||
@@ -1,10 +1,11 @@
|
||||
module evobgp
|
||||
|
||||
go 1.22
|
||||
go 1.24.0
|
||||
|
||||
require (
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.7.2
|
||||
github.com/miekg/dns v1.1.72
|
||||
github.com/prometheus/client_golang v1.20.5
|
||||
modernc.org/sqlite v1.34.5
|
||||
)
|
||||
@@ -24,10 +25,13 @@ require (
|
||||
github.com/prometheus/common v0.55.0 // indirect
|
||||
github.com/prometheus/procfs v0.15.1 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
golang.org/x/crypto v0.31.0 // indirect
|
||||
golang.org/x/sync v0.10.0 // indirect
|
||||
golang.org/x/sys v0.28.0 // indirect
|
||||
golang.org/x/text v0.21.0 // indirect
|
||||
golang.org/x/crypto v0.46.0 // indirect
|
||||
golang.org/x/mod v0.31.0 // indirect
|
||||
golang.org/x/net v0.48.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/sys v0.39.0 // indirect
|
||||
golang.org/x/text v0.32.0 // indirect
|
||||
golang.org/x/tools v0.40.0 // indirect
|
||||
google.golang.org/protobuf v1.34.2 // indirect
|
||||
modernc.org/libc v1.55.3 // indirect
|
||||
modernc.org/mathutil v1.6.0 // indirect
|
||||
|
||||
@@ -28,6 +28,8 @@ github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0
|
||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI=
|
||||
github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
|
||||
@@ -49,19 +51,21 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=
|
||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
|
||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||
golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
|
||||
golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg=
|
||||
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
||||
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
||||
golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
|
||||
golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
|
||||
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
|
||||
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
package agentserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"evobgp/internal/birdfmt"
|
||||
"evobgp/internal/nodecli"
|
||||
)
|
||||
|
||||
// Config holds evobgp-agent serve settings.
|
||||
type Config struct {
|
||||
Listen string
|
||||
Secret string
|
||||
ControlPlaneURL string
|
||||
NodeToken string
|
||||
SpeakerID string
|
||||
PubKeyB64 string
|
||||
PubKeyHex string
|
||||
ExtractDir string
|
||||
BirdBin string
|
||||
BirdcBin string
|
||||
Socket string
|
||||
SyncTimeout time.Duration
|
||||
LastSync func() (revisionID string, at time.Time)
|
||||
OnSyncSuccess func(revisionID string)
|
||||
}
|
||||
|
||||
// Server serves Panel→Node internal API (Remnawave-style wake-up).
|
||||
type Server struct {
|
||||
cfg Config
|
||||
mux *http.ServeMux
|
||||
}
|
||||
|
||||
// New builds an agent HTTP server.
|
||||
func New(cfg Config) *Server {
|
||||
s := &Server{cfg: cfg, mux: http.NewServeMux()}
|
||||
s.mux.HandleFunc("GET /v1/agent/health", s.handleHealth)
|
||||
s.mux.HandleFunc("GET /v1/agent/bird/protocols", s.handleBirdProtocols)
|
||||
s.mux.HandleFunc("POST /v1/agent/sync", s.handleSync)
|
||||
return s
|
||||
}
|
||||
|
||||
// Handler returns the root HTTP handler.
|
||||
func (s *Server) Handler() http.Handler {
|
||||
return s.mux
|
||||
}
|
||||
|
||||
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorize(r) {
|
||||
writeProblem(w, http.StatusUnauthorized, "missing or invalid Authorization")
|
||||
return
|
||||
}
|
||||
body := map[string]any{
|
||||
"ok": true,
|
||||
"speaker_id": strings.TrimSpace(s.cfg.SpeakerID),
|
||||
}
|
||||
if s.cfg.LastSync != nil {
|
||||
if rev, at := s.cfg.LastSync(); rev != "" {
|
||||
body["last_applied_revision_id"] = rev
|
||||
body["last_sync_at"] = at.UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, body)
|
||||
}
|
||||
|
||||
func (s *Server) handleBirdProtocols(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorize(r) {
|
||||
writeProblem(w, http.StatusUnauthorized, "missing or invalid Authorization")
|
||||
return
|
||||
}
|
||||
sock := strings.TrimSpace(s.cfg.Socket)
|
||||
if sock == "" {
|
||||
writeProblem(w, http.StatusServiceUnavailable, "EVOBGP_BIRDC_SOCKET not configured")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
out, err := birdfmt.ShowProtocols(ctx, sock, strings.TrimSpace(s.cfg.BirdcBin))
|
||||
if err != nil {
|
||||
log.Printf("agentserver: bird protocols: %v", err)
|
||||
writeProblem(w, http.StatusBadGateway, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"ok": true,
|
||||
"sessions": birdfmt.ParseBGPSessions(out),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorize(r) {
|
||||
writeProblem(w, http.StatusUnauthorized, "missing or invalid Authorization")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
RevisionID string `json:"revision_id"`
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&req)
|
||||
|
||||
timeout := s.cfg.SyncTimeout
|
||||
if timeout <= 0 {
|
||||
timeout = 45 * time.Second
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
res, err := nodecli.SyncBundle(ctx, nodecli.SyncConfig{
|
||||
BaseURL: s.cfg.ControlPlaneURL,
|
||||
Token: s.cfg.NodeToken,
|
||||
SpeakerID: s.cfg.SpeakerID,
|
||||
RevisionID: strings.TrimSpace(req.RevisionID),
|
||||
PubKeyB64: s.cfg.PubKeyB64,
|
||||
PubKeyHex: s.cfg.PubKeyHex,
|
||||
ExtractDir: s.cfg.ExtractDir,
|
||||
BirdBin: s.cfg.BirdBin,
|
||||
BirdcBin: s.cfg.BirdcBin,
|
||||
Socket: s.cfg.Socket,
|
||||
Timeout: timeout,
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("agentserver: sync: %v", err)
|
||||
writeProblem(w, http.StatusBadGateway, err.Error())
|
||||
return
|
||||
}
|
||||
if s.cfg.OnSyncSuccess != nil {
|
||||
s.cfg.OnSyncSuccess(res.RevisionID)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"ok": true,
|
||||
"applied_revision_id": res.RevisionID,
|
||||
"main_config": res.MainConfig,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) authorize(r *http.Request) bool {
|
||||
secret := strings.TrimSpace(s.cfg.Secret)
|
||||
if secret == "" {
|
||||
return false
|
||||
}
|
||||
h := r.Header.Get("Authorization")
|
||||
const prefix = "Bearer "
|
||||
if !strings.HasPrefix(h, prefix) {
|
||||
return false
|
||||
}
|
||||
return strings.TrimSpace(h[len(prefix):]) == secret
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func writeProblem(w http.ResponseWriter, status int, detail string) {
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"title": http.StatusText(status),
|
||||
"status": status,
|
||||
"detail": detail,
|
||||
})
|
||||
}
|
||||
|
||||
// ListenAndServe starts the agent HTTP server on cfg.Listen.
|
||||
func ListenAndServe(cfg Config) error {
|
||||
if strings.TrimSpace(cfg.Listen) == "" {
|
||||
cfg.Listen = ":8443"
|
||||
}
|
||||
srv := &http.Server{
|
||||
Addr: cfg.Listen,
|
||||
Handler: New(cfg).Handler(),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
}
|
||||
log.Printf("evobgp-agent serve: listening on %s speaker=%s", cfg.Listen, cfg.SpeakerID)
|
||||
return srv.ListenAndServe()
|
||||
}
|
||||
|
||||
// ConfigFromEnv builds Config from EVOBGP_* environment variables.
|
||||
func ConfigFromEnv() (Config, error) {
|
||||
cfg := Config{
|
||||
Listen: envOr("EVOBGP_AGENT_LISTEN", ":8443"),
|
||||
Secret: strings.TrimSpace(os.Getenv("EVOBGP_AGENT_SECRET")),
|
||||
ControlPlaneURL: strings.TrimSpace(os.Getenv("EVOBGP_CONTROL_PLANE_URL")),
|
||||
NodeToken: strings.TrimSpace(os.Getenv("EVOBGP_NODE_TOKEN")),
|
||||
SpeakerID: strings.TrimSpace(os.Getenv("EVOBGP_SPEAKER_ID")),
|
||||
PubKeyB64: strings.TrimSpace(os.Getenv("EVOBGP_BUNDLE_PUBKEY_BASE64")),
|
||||
PubKeyHex: strings.TrimSpace(os.Getenv("EVOBGP_BUNDLE_PUBKEY_HEX")),
|
||||
ExtractDir: envOr("EVOBGP_BIRD_EXTRACT_DIR", "/etc/bird"),
|
||||
BirdBin: strings.TrimSpace(os.Getenv("EVOBGP_BIRD_BIN")),
|
||||
BirdcBin: strings.TrimSpace(os.Getenv("EVOBGP_BIRDC_BIN")),
|
||||
Socket: strings.TrimSpace(os.Getenv("EVOBGP_BIRDC_SOCKET")),
|
||||
SyncTimeout: 45 * time.Second,
|
||||
}
|
||||
if cfg.Secret == "" {
|
||||
return cfg, fmt.Errorf("agentserver: EVOBGP_AGENT_SECRET required")
|
||||
}
|
||||
if cfg.ControlPlaneURL == "" || cfg.NodeToken == "" || cfg.SpeakerID == "" {
|
||||
return cfg, fmt.Errorf("agentserver: EVOBGP_CONTROL_PLANE_URL, EVOBGP_NODE_TOKEN, EVOBGP_SPEAKER_ID required")
|
||||
}
|
||||
if cfg.PubKeyB64 == "" && cfg.PubKeyHex == "" {
|
||||
return cfg, fmt.Errorf("agentserver: EVOBGP_BUNDLE_PUBKEY_BASE64 or EVOBGP_BUNDLE_PUBKEY_HEX required")
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func envOr(key, def string) string {
|
||||
if v := strings.TrimSpace(os.Getenv(key)); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package agentserver_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"evobgp/internal/agentserver"
|
||||
)
|
||||
|
||||
func TestAgentHealth_requiresAuth(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := httptest.NewServer(agentserver.New(agentserver.Config{
|
||||
Secret: "test-secret",
|
||||
SpeakerID: "sp-1",
|
||||
}).Handler())
|
||||
defer srv.Close()
|
||||
|
||||
resp, err := http.Get(srv.URL + "/v1/agent/health")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("want 401, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
req, _ := http.NewRequest(http.MethodGet, srv.URL+"/v1/agent/health", nil)
|
||||
req.Header.Set("Authorization", "Bearer test-secret")
|
||||
resp2, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp2.Body.Close() }()
|
||||
if resp2.StatusCode != http.StatusOK {
|
||||
t.Fatalf("want 200, got %d", resp2.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentSync_badAuth(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := httptest.NewServer(agentserver.New(agentserver.Config{
|
||||
Secret: "right",
|
||||
SpeakerID: "sp-1",
|
||||
ControlPlaneURL: "http://127.0.0.1:1",
|
||||
NodeToken: "tok",
|
||||
PubKeyB64: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
|
||||
ExtractDir: t.TempDir(),
|
||||
}).Handler())
|
||||
defer srv.Close()
|
||||
|
||||
req, _ := http.NewRequest(http.MethodPost, srv.URL+"/v1/agent/sync", strings.NewReader("{}"))
|
||||
req.Header.Set("Authorization", "Bearer wrong")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("want 401, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
// Package asnresolve fetches IP prefixes announced by an ASN (control-plane ingest).
|
||||
package asnresolve
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DefaultRIPEStatURL is the RIPEstat announced-prefixes data call (no API key).
|
||||
const DefaultRIPEStatURL = "https://stat.ripe.net/data/announced-prefixes/data.json"
|
||||
|
||||
// DefaultASOverviewURL is the RIPEstat as-overview data call (holder / org name, no API key).
|
||||
const DefaultASOverviewURL = "https://stat.ripe.net/data/as-overview/data.json"
|
||||
|
||||
// AnnouncedPrefixes returns currently announced IPv4/IPv6 prefixes for the ASN (best-effort via RIPEstat).
|
||||
func AnnouncedPrefixes(ctx context.Context, hc *http.Client, asn int64) ([]netip.Prefix, error) {
|
||||
if hc == nil {
|
||||
hc = http.DefaultClient
|
||||
}
|
||||
base := strings.TrimSpace(os.Getenv("EVOBGP_RIPESTAT_ANNOUNCED_PREFIXES_URL"))
|
||||
if base == "" {
|
||||
base = DefaultRIPEStatURL
|
||||
}
|
||||
u := fmt.Sprintf("%s?resource=AS%d", strings.TrimSuffix(base, "?"), asn)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("User-Agent", "evobgp-asnresolve/1.0")
|
||||
|
||||
resp, err := hc.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ripestat fetch AS%d: %w", asn, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, 32<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("ripestat AS%d: HTTP %s: %s", asn, resp.Status, truncateForErr(body, 200))
|
||||
}
|
||||
|
||||
var wrap struct {
|
||||
Status string `json:"status"`
|
||||
Data struct {
|
||||
Prefixes []struct {
|
||||
Prefix string `json:"prefix"`
|
||||
} `json:"prefixes"`
|
||||
} `json:"data"`
|
||||
Messages [][]string `json:"messages"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &wrap); err != nil {
|
||||
return nil, fmt.Errorf("ripestat AS%d: json: %w", asn, err)
|
||||
}
|
||||
if wrap.Status != "" && wrap.Status != "ok" {
|
||||
return nil, fmt.Errorf("ripestat AS%d: status %q", asn, wrap.Status)
|
||||
}
|
||||
|
||||
var out []netip.Prefix
|
||||
for _, row := range wrap.Data.Prefixes {
|
||||
p := strings.TrimSpace(row.Prefix)
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
pfx, err := netip.ParsePrefix(p)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, pfx.Masked())
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].String() < out[j].String() })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ASHolderName returns the holder / organization label for the ASN from RIPEstat as-overview (best-effort).
|
||||
func ASHolderName(ctx context.Context, hc *http.Client, asn int64) (string, error) {
|
||||
if hc == nil {
|
||||
hc = http.DefaultClient
|
||||
}
|
||||
base := strings.TrimSpace(os.Getenv("EVOBGP_RIPESTAT_AS_OVERVIEW_URL"))
|
||||
if base == "" {
|
||||
base = DefaultASOverviewURL
|
||||
}
|
||||
u := fmt.Sprintf("%s?resource=AS%d", strings.TrimSuffix(base, "?"), asn)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("User-Agent", "evobgp-asnresolve/1.0")
|
||||
|
||||
resp, err := hc.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("ripestat as-overview AS%d: %w", asn, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("ripestat as-overview AS%d: HTTP %s: %s", asn, resp.Status, truncateForErr(body, 200))
|
||||
}
|
||||
|
||||
var wrap struct {
|
||||
Status string `json:"status"`
|
||||
Data struct {
|
||||
Holder string `json:"holder"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &wrap); err != nil {
|
||||
return "", fmt.Errorf("ripestat as-overview AS%d: json: %w", asn, err)
|
||||
}
|
||||
if wrap.Status != "" && wrap.Status != "ok" {
|
||||
return "", fmt.Errorf("ripestat as-overview AS%d: status %q", asn, wrap.Status)
|
||||
}
|
||||
return strings.TrimSpace(wrap.Data.Holder), nil
|
||||
}
|
||||
|
||||
func truncateForErr(b []byte, n int) string {
|
||||
s := string(b)
|
||||
if len(s) > n {
|
||||
return s[:n] + "…"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// PolitePause is a short delay between upstream ASN lookups (same refresh).
|
||||
func PolitePause() {
|
||||
d := 150 * time.Millisecond
|
||||
if s := strings.TrimSpace(os.Getenv("EVOBGP_ASN_RESOLVE_PAUSE_MS")); s != "" {
|
||||
if ms, err := parsePositiveInt(s); err == nil && ms > 0 {
|
||||
d = time.Duration(ms) * time.Millisecond
|
||||
}
|
||||
}
|
||||
time.Sleep(d)
|
||||
}
|
||||
|
||||
func parsePositiveInt(s string) (int, error) {
|
||||
n, err := strconv.Atoi(s)
|
||||
if err != nil || n <= 0 {
|
||||
return 0, fmt.Errorf("invalid")
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package asnresolve
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAnnouncedPrefixes_Mock(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Query().Get("resource") != "AS64496" {
|
||||
t.Fatalf("resource: %q", r.URL.Query().Get("resource"))
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"status":"ok","data":{"prefixes":[{"prefix":"203.0.113.0/24"},{"prefix":"2001:db8::/32"}]}}`))
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
t.Setenv("EVOBGP_RIPESTAT_ANNOUNCED_PREFIXES_URL", ts.URL)
|
||||
t.Setenv("EVOBGP_ASN_RESOLVE_PAUSE_MS", "1")
|
||||
|
||||
pfx, err := AnnouncedPrefixes(context.Background(), ts.Client(), 64496)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(pfx) != 2 {
|
||||
t.Fatalf("got %d prefixes", len(pfx))
|
||||
}
|
||||
if pfx[0].String() != "2001:db8::/32" || pfx[1].String() != "203.0.113.0/24" {
|
||||
t.Fatalf("order or values: %#v", pfx)
|
||||
}
|
||||
}
|
||||
|
||||
func TestASHolderName_Mock(t *testing.T) {
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Query().Get("resource") != "AS64496" {
|
||||
t.Fatalf("resource: %q", r.URL.Query().Get("resource"))
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"status":"ok","data":{"holder":"Example Networks Ltd"}}`))
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
t.Setenv("EVOBGP_RIPESTAT_AS_OVERVIEW_URL", ts.URL)
|
||||
|
||||
name, err := ASHolderName(context.Background(), ts.Client(), 64496)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if name != "Example Networks Ltd" {
|
||||
t.Fatalf("holder: %q", name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// Package authkey generates API tokens and derives lookup hashes (no persistence).
|
||||
package authkey
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
const tokenPrefix = "evobgp_"
|
||||
|
||||
// GenerateToken returns a new bearer token (evobgp_ + 32 random bytes, base64url).
|
||||
func GenerateToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("authkey: generate token: %w", err)
|
||||
}
|
||||
return tokenPrefix + base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// HashToken returns SHA-256 of the full token (32 bytes).
|
||||
func HashToken(token string) []byte {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
// Prefix returns the first 8 characters of the token for display.
|
||||
func Prefix(token string) string {
|
||||
if len(token) <= 8 {
|
||||
return token
|
||||
}
|
||||
return token[:8]
|
||||
}
|
||||
@@ -43,6 +43,9 @@ func ApplyRevision(ctx context.Context, ctl *birdfmt.BirdCtl, rev *store.Revisio
|
||||
// Phase 1: write staging tree
|
||||
for rel, content := range rev.PreviewFragments {
|
||||
rel = strings.TrimPrefix(rel, "/")
|
||||
if !isDeployableBirdFragment(rel) {
|
||||
continue
|
||||
}
|
||||
dst := filepath.Join(staging, rel)
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
|
||||
return err
|
||||
@@ -70,6 +73,9 @@ func ApplyRevision(ctx context.Context, ctl *birdfmt.BirdCtl, rev *store.Revisio
|
||||
// Phase 2: atomic swap into active
|
||||
for rel, content := range rev.PreviewFragments {
|
||||
rel = strings.TrimPrefix(rel, "/")
|
||||
if !isDeployableBirdFragment(rel) {
|
||||
continue
|
||||
}
|
||||
dst := filepath.Join(active, rel)
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
|
||||
_ = restoreLKG(lkg, active)
|
||||
@@ -93,6 +99,11 @@ func ApplyRevision(ctx context.Context, ctl *birdfmt.BirdCtl, rev *store.Revisio
|
||||
return nil
|
||||
}
|
||||
|
||||
// isDeployableBirdFragment skips UI-only preview keys (e.g. flattened full config) not referenced from bird.conf.
|
||||
func isDeployableBirdFragment(rel string) bool {
|
||||
return rel != "" && !strings.HasPrefix(rel, "_")
|
||||
}
|
||||
|
||||
func snapshotBirdTree(activeRoot, dstRoot string) error {
|
||||
if err := os.MkdirAll(dstRoot, 0o755); err != nil {
|
||||
return err
|
||||
|
||||
@@ -5,6 +5,108 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// BGP template names referenced by generated peers (BIRD 2).
|
||||
const (
|
||||
BGPTemplateNameV4 = "bgp_template"
|
||||
BGPTemplateNameV6 = "bgp_template_v6"
|
||||
)
|
||||
|
||||
// BGPTemplatesOptions holds ASN and export filters for template bgp bgp_template (+ v6 mirror).
|
||||
// Templates use "local as <asn>;" only (no local IP); peers add neighbor / multihop / passive and optional "local … as …" override.
|
||||
type BGPTemplatesOptions struct {
|
||||
LocalASN uint32
|
||||
ExportFilterV4 string
|
||||
ExportFilterV6 string
|
||||
}
|
||||
|
||||
// RenderBGPTemplates renders two template bgp blocks (IPv4 and IPv6 AFI).
|
||||
func RenderBGPTemplates(opts BGPTemplatesOptions) (string, error) {
|
||||
if opts.LocalASN == 0 {
|
||||
return "", fmt.Errorf("birdfmt: template local ASN must be non-zero")
|
||||
}
|
||||
exp4 := "all"
|
||||
if strings.TrimSpace(opts.ExportFilterV4) != "" {
|
||||
exp4 = "filter " + strings.TrimSpace(opts.ExportFilterV4)
|
||||
}
|
||||
exp6 := "all"
|
||||
if strings.TrimSpace(opts.ExportFilterV6) != "" {
|
||||
exp6 = "filter " + strings.TrimSpace(opts.ExportFilterV6)
|
||||
}
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "template bgp %s {\n", BGPTemplateNameV4)
|
||||
fmt.Fprintf(&b, " local as %d;\n", opts.LocalASN)
|
||||
b.WriteString(" ipv4 {\n")
|
||||
b.WriteString(" import none;\n")
|
||||
b.WriteString(" export ")
|
||||
b.WriteString(exp4)
|
||||
b.WriteString(";\n")
|
||||
b.WriteString(" };\n")
|
||||
b.WriteString(" hold time 90;\n")
|
||||
b.WriteString(" keepalive time 30;\n")
|
||||
b.WriteString("}\n\n")
|
||||
fmt.Fprintf(&b, "template bgp %s {\n", BGPTemplateNameV6)
|
||||
fmt.Fprintf(&b, " local as %d;\n", opts.LocalASN)
|
||||
b.WriteString(" ipv6 {\n")
|
||||
b.WriteString(" import none;\n")
|
||||
b.WriteString(" export ")
|
||||
b.WriteString(exp6)
|
||||
b.WriteString(";\n")
|
||||
b.WriteString(" };\n")
|
||||
b.WriteString(" hold time 90;\n")
|
||||
b.WriteString(" keepalive time 30;\n")
|
||||
b.WriteString("}\n")
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
// BGPPeerFromTemplateOptions describes protocol bgp NAME from TEMPLATE { … }.
|
||||
type BGPPeerFromTemplateOptions struct {
|
||||
ProtocolName string
|
||||
TemplateName string
|
||||
NeighborIP string
|
||||
NeighborASN uint32
|
||||
// If set, emits "local … as …" before neighbor (overrides template local/ASN for this peer).
|
||||
OverrideLocalIP string
|
||||
OverrideLocalASN uint32
|
||||
}
|
||||
|
||||
// RenderProtocolBGPFromTemplate renders protocol bgp … from TEMPLATE { neighbor; multihop; passive; }.
|
||||
func RenderProtocolBGPFromTemplate(opts BGPPeerFromTemplateOptions) (string, error) {
|
||||
if strings.TrimSpace(opts.ProtocolName) == "" {
|
||||
return "", fmt.Errorf("birdfmt: protocol name is required")
|
||||
}
|
||||
if strings.TrimSpace(opts.TemplateName) == "" {
|
||||
return "", fmt.Errorf("birdfmt: template name is required")
|
||||
}
|
||||
if strings.TrimSpace(opts.NeighborIP) == "" {
|
||||
return "", fmt.Errorf("birdfmt: neighbor is required")
|
||||
}
|
||||
if opts.NeighborASN == 0 {
|
||||
return "", fmt.Errorf("birdfmt: neighbor ASN must be non-zero")
|
||||
}
|
||||
if opts.OverrideLocalIP != "" && opts.OverrideLocalASN == 0 {
|
||||
return "", fmt.Errorf("birdfmt: override local ASN is required when override local IP is set")
|
||||
}
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString("protocol bgp ")
|
||||
b.WriteString(strings.TrimSpace(opts.ProtocolName))
|
||||
b.WriteString(" from ")
|
||||
b.WriteString(strings.TrimSpace(opts.TemplateName))
|
||||
b.WriteString(" {\n")
|
||||
if ip := strings.TrimSpace(opts.OverrideLocalIP); ip != "" {
|
||||
b.WriteString(" local ")
|
||||
b.WriteString(ip)
|
||||
fmt.Fprintf(&b, " as %d;\n", opts.OverrideLocalASN)
|
||||
}
|
||||
b.WriteString(" neighbor ")
|
||||
b.WriteString(strings.TrimSpace(opts.NeighborIP))
|
||||
fmt.Fprintf(&b, " as %d;\n", opts.NeighborASN)
|
||||
b.WriteString(" multihop;\n")
|
||||
b.WriteString(" passive;\n")
|
||||
b.WriteString("}\n")
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
// BGPPeerIPv4Options describes a single BGP session (BIRD 2, IPv4 AF).
|
||||
type BGPPeerIPv4Options struct {
|
||||
ProtocolName string // e.g. evobgp_peer_uplink
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package birdfmt
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// BGPSession is one BGP protocol block from `birdc show protocols all`.
|
||||
type BGPSession struct {
|
||||
Name string `json:"name"`
|
||||
Neighbor string `json:"neighbor,omitempty"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
|
||||
// ParseBGPSessions extracts BGP protocol name, state, and neighbor (if present) from birdc output.
|
||||
func ParseBGPSessions(output string) []BGPSession {
|
||||
var out []BGPSession
|
||||
var cur *BGPSession
|
||||
for _, raw := range strings.Split(output, "\n") {
|
||||
line := strings.TrimRight(raw, "\r")
|
||||
trim := strings.TrimSpace(line)
|
||||
if trim == "" {
|
||||
cur = nil
|
||||
continue
|
||||
}
|
||||
low := strings.ToLower(trim)
|
||||
if strings.HasPrefix(low, "bird ") || strings.HasPrefix(low, "name ") || strings.HasPrefix(low, "table ") {
|
||||
continue
|
||||
}
|
||||
if !strings.HasPrefix(line, " ") && !strings.HasPrefix(line, "\t") {
|
||||
if isBGPProtocolSummaryRow(trim) {
|
||||
fields := strings.Fields(trim)
|
||||
state := extractBGPSessionStateLine(trim)
|
||||
if state == "" && len(fields) >= 4 {
|
||||
state = fields[3]
|
||||
}
|
||||
out = append(out, BGPSession{Name: fields[0], State: state})
|
||||
cur = &out[len(out)-1]
|
||||
} else {
|
||||
cur = nil
|
||||
}
|
||||
continue
|
||||
}
|
||||
if cur == nil {
|
||||
continue
|
||||
}
|
||||
for _, prefix := range []string{"Neighbor address:", "Neighbor Address:", "Neighbor:"} {
|
||||
if idx := strings.Index(trim, prefix); idx >= 0 {
|
||||
cur.Neighbor = strings.TrimSpace(trim[idx+len(prefix):])
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package birdfmt
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestParseBGPSessions_neighborAndState(t *testing.T) {
|
||||
sample := `
|
||||
BIRD 2.14 ready.
|
||||
Name Proto Table State Since Info
|
||||
device1 Device --- up 10:00:00
|
||||
evobgp_p_abc123 BGP master4 up 10:00:05 Established
|
||||
Neighbor address: 198.51.100.2
|
||||
Neighbor AS: 65001
|
||||
evobgp_p_def456 BGP master4 up 10:00:06 Active
|
||||
Neighbor address: 2001:db8::2
|
||||
`
|
||||
sessions := ParseBGPSessions(sample)
|
||||
if len(sessions) != 2 {
|
||||
t.Fatalf("got %d sessions want 2", len(sessions))
|
||||
}
|
||||
if sessions[0].Name != "evobgp_p_abc123" || sessions[0].State != "Established" || sessions[0].Neighbor != "198.51.100.2" {
|
||||
t.Fatalf("session0: %+v", sessions[0])
|
||||
}
|
||||
if sessions[1].Neighbor != "2001:db8::2" || sessions[1].State != "Active" {
|
||||
t.Fatalf("session1: %+v", sessions[1])
|
||||
}
|
||||
}
|
||||
@@ -27,3 +27,48 @@ func TestRenderProtocolBGPIPv4_ExportAll(t *testing.T) {
|
||||
t.Fatal(got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderBGPTemplates_Validation(t *testing.T) {
|
||||
_, err := RenderBGPTemplates(BGPTemplatesOptions{})
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderProtocolBGPFromTemplate_MultihopPassive(t *testing.T) {
|
||||
got, err := RenderProtocolBGPFromTemplate(BGPPeerFromTemplateOptions{
|
||||
ProtocolName: "evobgp_p_x",
|
||||
TemplateName: BGPTemplateNameV4,
|
||||
NeighborIP: "94.142.140.141",
|
||||
NeighborASN: 65002,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(got, "from bgp_template") {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if !strings.Contains(got, "multihop;") || !strings.Contains(got, "passive;") {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if strings.Contains(got, "source address") || strings.Contains(got, "strict bind") {
|
||||
t.Fatal(got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderProtocolBGPFromTemplate_OverrideLocal(t *testing.T) {
|
||||
got, err := RenderProtocolBGPFromTemplate(BGPPeerFromTemplateOptions{
|
||||
ProtocolName: "p",
|
||||
TemplateName: BGPTemplateNameV4,
|
||||
NeighborIP: "192.0.2.2",
|
||||
NeighborASN: 2,
|
||||
OverrideLocalIP: "10.0.0.1",
|
||||
OverrideLocalASN: 65099,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(got, "local 10.0.0.1 as 65099;") {
|
||||
t.Fatal(got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package birdfmt
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var standardPairRE = regexp.MustCompile(`^\s*(\d{1,5}):(\d{1,5})\s*$`)
|
||||
|
||||
// badCommunityAddRE matches invalid BIRD filter calls like bgp_community.add(65000,1)
|
||||
// (first argument is an int). Valid form is bgp_community.add((65000,1)); — note the pair tuple.
|
||||
var badCommunityAddRE = regexp.MustCompile(`\b(?:bgp_community|bgp_large_community)\.add\(\s*\d`)
|
||||
|
||||
// RouteCommunityAttrs returns BIRD 2 lines (indented with 4 spaces) for use inside a static `route … { … }` block.
|
||||
// Empty string means no community attributes.
|
||||
func RouteCommunityAttrs(kind, name, valueJSON string) (string, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
raw := strings.TrimSpace(valueJSON)
|
||||
if raw == "" {
|
||||
raw = "{}"
|
||||
}
|
||||
|
||||
if s, ok := parseLargeFromJSONLoose(raw); ok {
|
||||
if err := validateCommunityRouteBody(s); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
_ = kind // reserved for future kinds (e.g. extended communities)
|
||||
|
||||
if m := standardPairRE.FindStringSubmatch(name); len(m) == 3 {
|
||||
s, err := standardAddLine(m[1], m[2])
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return s, validateCommunityRouteBody(s)
|
||||
}
|
||||
|
||||
var obj map[string]any
|
||||
if json.Unmarshal([]byte(raw), &obj) == nil {
|
||||
if v, ok := obj["standard"].(string); ok {
|
||||
if m := standardPairRE.FindStringSubmatch(v); len(m) == 3 {
|
||||
s, err := standardAddLine(m[1], m[2])
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return s, validateCommunityRouteBody(s)
|
||||
}
|
||||
}
|
||||
if arr, ok := obj["standard"].([]any); ok {
|
||||
if len(arr) == 1 {
|
||||
return "", fmt.Errorf(`birdfmt: value_json "standard" must be a pair [a,b] or "a:b" string, got single element`)
|
||||
}
|
||||
if len(arr) == 2 {
|
||||
a, aok := numberToUint32String(arr[0])
|
||||
b, bok := numberToUint32String(arr[1])
|
||||
if aok && bok {
|
||||
s, err := standardAddLine(a, b)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return s, validateCommunityRouteBody(s)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var strVal string
|
||||
if json.Unmarshal([]byte(raw), &strVal) == nil {
|
||||
if m := standardPairRE.FindStringSubmatch(strVal); len(m) == 3 {
|
||||
s, err := standardAddLine(m[1], m[2])
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return s, validateCommunityRouteBody(s)
|
||||
}
|
||||
}
|
||||
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// validateCommunityRouteBody rejects lines that would make BIRD 2 fail parse-check with
|
||||
// "Argument 1 of 'add' expected clist / quad / ip / pair, got int" (wrong add() shape).
|
||||
func validateCommunityRouteBody(body string) error {
|
||||
body = strings.TrimSpace(body)
|
||||
if body == "" {
|
||||
return nil
|
||||
}
|
||||
for _, line := range strings.Split(body, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
if badCommunityAddRE.MatchString(line) {
|
||||
return fmt.Errorf("birdfmt: invalid community line (expected pair/triple tuple inside add(), e.g. bgp_community.add((65000,1));): %q", line)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func standardAddLine(a, b string) (string, error) {
|
||||
ai, err1 := strconv.ParseUint(strings.TrimSpace(a), 10, 16)
|
||||
bi, err2 := strconv.ParseUint(strings.TrimSpace(b), 10, 16)
|
||||
if err1 != nil || err2 != nil {
|
||||
return "", fmt.Errorf("birdfmt: standard community parts must be 0..65535 (%s:%s)", a, b)
|
||||
}
|
||||
return fmt.Sprintf(" bgp_community.add((%d,%d));", ai, bi), nil
|
||||
}
|
||||
|
||||
func parseLargeFromJSONLoose(raw string) (string, bool) {
|
||||
var obj map[string]any
|
||||
if json.Unmarshal([]byte(raw), &obj) != nil {
|
||||
return "", false
|
||||
}
|
||||
arr, ok := obj["large"].([]any)
|
||||
if !ok || len(arr) == 0 {
|
||||
return "", false
|
||||
}
|
||||
var b strings.Builder
|
||||
for _, row := range arr {
|
||||
triple, ok := row.([]any)
|
||||
if !ok || len(triple) != 3 {
|
||||
continue
|
||||
}
|
||||
a, ok1 := numberToUint32String(triple[0])
|
||||
bb, ok2 := numberToUint32String(triple[1])
|
||||
c, ok3 := numberToUint32String(triple[2])
|
||||
if !ok1 || !ok2 || !ok3 {
|
||||
continue
|
||||
}
|
||||
ai, _ := strconv.ParseUint(a, 10, 32)
|
||||
bi, _ := strconv.ParseUint(bb, 10, 32)
|
||||
ci, _ := strconv.ParseUint(c, 10, 32)
|
||||
fmt.Fprintf(&b, " bgp_large_community.add((%d,%d,%d));\n", ai, bi, ci)
|
||||
}
|
||||
s := strings.TrimRight(b.String(), "\r\n")
|
||||
return s, s != ""
|
||||
}
|
||||
|
||||
func numberToUint32String(v any) (string, bool) {
|
||||
switch x := v.(type) {
|
||||
case float64:
|
||||
if x < 0 || x > 4294967295 {
|
||||
return "", false
|
||||
}
|
||||
return strconv.FormatUint(uint64(x), 10), true
|
||||
case json.Number:
|
||||
n, err := x.Int64()
|
||||
if err != nil || n < 0 || n > 4294967295 {
|
||||
return "", false
|
||||
}
|
||||
return strconv.FormatUint(uint64(n), 10), true
|
||||
case int:
|
||||
if x < 0 || x > 4294967295 {
|
||||
return "", false
|
||||
}
|
||||
return strconv.FormatUint(uint64(x), 10), true
|
||||
case int64:
|
||||
if x < 0 || x > 4294967295 {
|
||||
return "", false
|
||||
}
|
||||
return strconv.FormatUint(uint64(x), 10), true
|
||||
case string:
|
||||
n, err := strconv.ParseUint(strings.TrimSpace(x), 10, 32)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
return strconv.FormatUint(n, 10), true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package birdfmt
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestRouteCommunityAttrs_StandardName(t *testing.T) {
|
||||
s, err := RouteCommunityAttrs("", "65000:120", "{}")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s != " bgp_community.add((65000,120));" {
|
||||
t.Fatalf("got %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteCommunityAttrs_LargeJSON(t *testing.T) {
|
||||
s, err := RouteCommunityAttrs("large", "x", `{"large":[[65000,1,2]]}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s != " bgp_large_community.add((65000,1,2));" {
|
||||
t.Fatalf("got %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteCommunityAttrs_StandardArrayOneElement(t *testing.T) {
|
||||
_, err := RouteCommunityAttrs("", "x", `{"standard":[65000]}`)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for single-element standard pair")
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,16 @@
|
||||
// Engineering rules for BIRD/BGP/IP: .cursor/rules/networking-bird.mdc
|
||||
//
|
||||
// Package birdfmt builds BIRD 2 configuration text: main bird.conf skeleton, include
|
||||
// fragments under bird.d/, export filters, static route protocols, and minimal BGP peer
|
||||
// blocks. Runtime helpers parse-check configs (bird -p) and reload (birdc configure).
|
||||
// fragments under bird.d/, export filters, static route protocols, BGP templates, and
|
||||
// BGP peer protocols (from template or standalone). Runtime helpers parse-check configs
|
||||
// (bird -p) and reload (birdc configure).
|
||||
//
|
||||
// # Layout
|
||||
//
|
||||
// Operator keeps a stable bird.conf (or generated skeleton) next to EvoBGP fragments:
|
||||
//
|
||||
// bird.conf — router id, protocol device, protocol direct, include lines
|
||||
// bird.d/evobgp_*.conf — generated prefixes, filters, peers (names from constants)
|
||||
// bird.d/evobgp_*.conf — generated prefixes, filters, BGP templates, peers (names from constants)
|
||||
//
|
||||
// Include order should list filter definitions before protocols that reference them
|
||||
// (see StandardIncludeFragments).
|
||||
|
||||
+56
-12
@@ -7,9 +7,42 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
const maxBGPASN = 4294967295
|
||||
|
||||
const filterPrefixChunkSize = 500
|
||||
|
||||
func writePrefixSetAcceptBlocks(b *strings.Builder, keys []string) {
|
||||
for i := 0; i < len(keys); i += filterPrefixChunkSize {
|
||||
end := i + filterPrefixChunkSize
|
||||
if end > len(keys) {
|
||||
end = len(keys)
|
||||
}
|
||||
chunk := keys[i:end]
|
||||
b.WriteString(" if net ~ [ ")
|
||||
b.WriteString(strings.Join(chunk, ", "))
|
||||
b.WriteString(" ] then accept;\n")
|
||||
}
|
||||
}
|
||||
|
||||
func filterUniqueASNs(pathASNs []int64) []int64 {
|
||||
seen := make(map[int64]struct{})
|
||||
for _, a := range pathASNs {
|
||||
if a >= 1 && a <= maxBGPASN {
|
||||
seen[a] = struct{}{}
|
||||
}
|
||||
}
|
||||
out := make([]int64, 0, len(seen))
|
||||
for a := range seen {
|
||||
out = append(out, a)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i] < out[j] })
|
||||
return out
|
||||
}
|
||||
|
||||
// RenderExportFilterIPv4 renders a BIRD 2 filter that accepts IPv4 routes whose prefix
|
||||
// is in prefixes (exact CIDR match via set membership), and rejects others.
|
||||
func RenderExportFilterIPv4(filterName string, prefixes []netip.Prefix) (string, error) {
|
||||
// is in prefixes (exact CIDR match via set membership), and/or routes whose AS_PATH
|
||||
// contains any of pathASNs (BIRD pattern [= * ASN =]), then rejects others.
|
||||
func RenderExportFilterIPv4(filterName string, prefixes []netip.Prefix, pathASNs []int64) (string, error) {
|
||||
if strings.TrimSpace(filterName) == "" {
|
||||
return "", fmt.Errorf("birdfmt: filter name is required")
|
||||
}
|
||||
@@ -27,24 +60,30 @@ func RenderExportFilterIPv4(filterName string, prefixes []netip.Prefix) (string,
|
||||
}
|
||||
sort.Strings(keys)
|
||||
|
||||
asns := filterUniqueASNs(pathASNs)
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString("filter ")
|
||||
b.WriteString(strings.TrimSpace(filterName))
|
||||
b.WriteString(" {\n")
|
||||
if len(keys) == 0 {
|
||||
if len(keys) > 0 {
|
||||
writePrefixSetAcceptBlocks(&b, keys)
|
||||
}
|
||||
for _, asn := range asns {
|
||||
fmt.Fprintf(&b, " if bgp_path ~ [= * %d =] then accept;\n", asn)
|
||||
}
|
||||
if len(keys) == 0 && len(asns) == 0 {
|
||||
b.WriteString(" reject;\n")
|
||||
} else {
|
||||
b.WriteString(" if net ~ [ ")
|
||||
b.WriteString(strings.Join(keys, ", "))
|
||||
b.WriteString(" ] then accept;\n")
|
||||
b.WriteString(" reject;\n")
|
||||
}
|
||||
b.WriteString("}\n")
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
// RenderExportFilterIPv6 renders a BIRD 2 filter for IPv6 prefixes (CIDR set, then reject).
|
||||
func RenderExportFilterIPv6(filterName string, prefixes []netip.Prefix) (string, error) {
|
||||
// RenderExportFilterIPv6 renders a BIRD 2 filter for IPv6 prefixes (CIDR set) and/or
|
||||
// AS_PATH matches, then reject.
|
||||
func RenderExportFilterIPv6(filterName string, prefixes []netip.Prefix, pathASNs []int64) (string, error) {
|
||||
if strings.TrimSpace(filterName) == "" {
|
||||
return "", fmt.Errorf("birdfmt: filter name is required")
|
||||
}
|
||||
@@ -62,16 +101,21 @@ func RenderExportFilterIPv6(filterName string, prefixes []netip.Prefix) (string,
|
||||
}
|
||||
sort.Strings(keys)
|
||||
|
||||
asns := filterUniqueASNs(pathASNs)
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString("filter ")
|
||||
b.WriteString(strings.TrimSpace(filterName))
|
||||
b.WriteString(" {\n")
|
||||
if len(keys) == 0 {
|
||||
if len(keys) > 0 {
|
||||
writePrefixSetAcceptBlocks(&b, keys)
|
||||
}
|
||||
for _, asn := range asns {
|
||||
fmt.Fprintf(&b, " if bgp_path ~ [= * %d =] then accept;\n", asn)
|
||||
}
|
||||
if len(keys) == 0 && len(asns) == 0 {
|
||||
b.WriteString(" reject;\n")
|
||||
} else {
|
||||
b.WriteString(" if net ~ [ ")
|
||||
b.WriteString(strings.Join(keys, ", "))
|
||||
b.WriteString(" ] then accept;\n")
|
||||
b.WriteString(" reject;\n")
|
||||
}
|
||||
b.WriteString("}\n")
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
)
|
||||
|
||||
func TestRenderExportFilterIPv4_Empty(t *testing.T) {
|
||||
got, err := RenderExportFilterIPv4("evobgp_x", nil)
|
||||
got, err := RenderExportFilterIPv4("evobgp_x", nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -21,7 +21,7 @@ func TestRenderExportFilterIPv4_Empty(t *testing.T) {
|
||||
|
||||
func TestRenderExportFilterIPv4_SkipsNonV4(t *testing.T) {
|
||||
v6 := netip.MustParsePrefix("2001:db8::/32")
|
||||
got, err := RenderExportFilterIPv4("f", []netip.Prefix{v6})
|
||||
got, err := RenderExportFilterIPv4("f", []netip.Prefix{v6}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -32,7 +32,7 @@ func TestRenderExportFilterIPv4_SkipsNonV4(t *testing.T) {
|
||||
|
||||
func TestRenderExportFilterIPv6(t *testing.T) {
|
||||
p := netip.MustParsePrefix("2001:db8::/32")
|
||||
got, err := RenderExportFilterIPv6("evobgp_export_v6", []netip.Prefix{p, p})
|
||||
got, err := RenderExportFilterIPv6("evobgp_export_v6", []netip.Prefix{p, p}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -45,3 +45,13 @@ func TestRenderExportFilterIPv6(t *testing.T) {
|
||||
t.Fatalf("mismatch\n--- got ---\n%s\n--- want ---\n%s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderExportFilterIPv4_ASPathOnly(t *testing.T) {
|
||||
got, err := RenderExportFilterIPv4("f", nil, []int64{65001, 65002})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(got, "bgp_path ~ [= * 65001 =]") || !strings.Contains(got, "bgp_path ~ [= * 65002 =]") {
|
||||
t.Fatal(got)
|
||||
}
|
||||
}
|
||||
@@ -9,11 +9,12 @@ import (
|
||||
const (
|
||||
DirBirdD = "bird.d"
|
||||
|
||||
FragmentPrefixesV4 = "evobgp_prefixes_v4.conf"
|
||||
FragmentPrefixesV6 = "evobgp_prefixes_v6.conf"
|
||||
FragmentFiltersV4 = "evobgp_filters_v4.conf"
|
||||
FragmentFiltersV6 = "evobgp_filters_v6.conf"
|
||||
FragmentPeers = "evobgp_peers.conf"
|
||||
FragmentPrefixesV4 = "evobgp_prefixes_v4.conf"
|
||||
FragmentPrefixesV6 = "evobgp_prefixes_v6.conf"
|
||||
FragmentFiltersV4 = "evobgp_filters_v4.conf"
|
||||
FragmentFiltersV6 = "evobgp_filters_v6.conf"
|
||||
FragmentBGPTemplate = "evobgp_bgp_template.conf"
|
||||
FragmentPeers = "evobgp_peers.conf"
|
||||
)
|
||||
|
||||
// FragmentIncludePath returns a POSIX include path such as bird.d/evobgp_prefixes_v4.conf.
|
||||
@@ -24,11 +25,12 @@ func FragmentIncludePath(fragmentBaseName string) string {
|
||||
return DirBirdD + "/" + fragmentBaseName
|
||||
}
|
||||
|
||||
// StandardIncludeFragments is the recommended order: filters before peers that reference them.
|
||||
// StandardIncludeFragments is the recommended order: filters before BGP templates and peers.
|
||||
func StandardIncludeFragments() []string {
|
||||
return []string{
|
||||
FragmentIncludePath(FragmentFiltersV4),
|
||||
FragmentIncludePath(FragmentFiltersV6),
|
||||
FragmentIncludePath(FragmentBGPTemplate),
|
||||
FragmentIncludePath(FragmentPrefixesV4),
|
||||
FragmentIncludePath(FragmentPrefixesV6),
|
||||
FragmentIncludePath(FragmentPeers),
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package birdfmt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// LocalBirdStatus is returned by GET /v1/bird/status (same host as birdc when socket is configured).
|
||||
type LocalBirdStatus struct {
|
||||
BirdcConfigured bool `json:"birdc_configured"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
ProtocolsExcerpt string `json:"protocols_excerpt,omitempty"`
|
||||
BGPSessionsTotal int `json:"bgp_sessions_total"`
|
||||
BGPEstablished int `json:"bgp_established"`
|
||||
// Healthy: null if birdc not configured; false if birdc failed or BGP sessions exist but none Established; true otherwise.
|
||||
Healthy *bool `json:"healthy"`
|
||||
}
|
||||
|
||||
// InspectLocalBird runs `birdc show protocols all` using EVOBGP_BIRDC_SOCKET / EVOBGP_BIRDC_BIN.
|
||||
func InspectLocalBird(ctx context.Context) LocalBirdStatus {
|
||||
sock := strings.TrimSpace(os.Getenv("EVOBGP_BIRDC_SOCKET"))
|
||||
if sock == "" {
|
||||
return LocalBirdStatus{
|
||||
BirdcConfigured: false,
|
||||
Message: "EVOBGP_BIRDC_SOCKET не задан на этом процессе — статус BIRD недоступен (типично, если birdc только на ноде со спикером).",
|
||||
Healthy: nil,
|
||||
}
|
||||
}
|
||||
bin := strings.TrimSpace(os.Getenv("EVOBGP_BIRDC_BIN"))
|
||||
out, err := ShowProtocols(ctx, sock, bin)
|
||||
if err != nil {
|
||||
f := false
|
||||
return LocalBirdStatus{
|
||||
BirdcConfigured: true,
|
||||
Error: err.Error(),
|
||||
Healthy: &f,
|
||||
}
|
||||
}
|
||||
sum := SummarizeProtocolsOutput(out)
|
||||
excerpt := out
|
||||
const maxExcerpt = 20000
|
||||
if len(excerpt) > maxExcerpt {
|
||||
excerpt = excerpt[:maxExcerpt] + "\n# … truncated …\n"
|
||||
}
|
||||
ok := sum.BGPSessionsTotal == 0 || sum.BGPEstablished > 0
|
||||
return LocalBirdStatus{
|
||||
BirdcConfigured: true,
|
||||
ProtocolsExcerpt: excerpt,
|
||||
BGPSessionsTotal: sum.BGPSessionsTotal,
|
||||
BGPEstablished: sum.BGPEstablished,
|
||||
Healthy: &ok,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package birdfmt
|
||||
|
||||
import "strings"
|
||||
|
||||
// PeerProtocolName returns the BIRD protocol name for a control-plane peer UUID.
|
||||
// Must stay in sync with pipeline peer rendering.
|
||||
func PeerProtocolName(peerID string) string {
|
||||
s := strings.ReplaceAll(strings.TrimSpace(peerID), "-", "")
|
||||
if len(s) > 16 {
|
||||
s = s[:16]
|
||||
}
|
||||
if s == "" {
|
||||
s = "x"
|
||||
}
|
||||
return "evobgp_p_" + s
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package birdfmt
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ProtocolsSummary is a lightweight parse of `birdc show protocols all` (BIRD 2).
|
||||
type ProtocolsSummary struct {
|
||||
BGPSessionsTotal int
|
||||
BGPEstablished int
|
||||
RawLineCount int
|
||||
}
|
||||
|
||||
// isBGPProtocolSummaryRow is true for BIRD "show protocols" summary rows where the
|
||||
// second column (Proto) is BGP. Substring checks are unsafe: names like evobgp_* contain "bgp".
|
||||
func isBGPProtocolSummaryRow(line string) bool {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
return false
|
||||
}
|
||||
low := strings.ToLower(line)
|
||||
if strings.HasPrefix(low, "name") || strings.HasPrefix(low, "table") {
|
||||
return false
|
||||
}
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) < 2 {
|
||||
return false
|
||||
}
|
||||
return strings.EqualFold(fields[1], "BGP")
|
||||
}
|
||||
|
||||
// SummarizeProtocolsOutput extracts BGP session heuristics from birdc output.
|
||||
func SummarizeProtocolsOutput(output string) ProtocolsSummary {
|
||||
var s ProtocolsSummary
|
||||
lines := strings.Split(output, "\n")
|
||||
s.RawLineCount = len(lines)
|
||||
for _, line := range lines {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
low := strings.ToLower(line)
|
||||
if !isBGPProtocolSummaryRow(line) {
|
||||
continue
|
||||
}
|
||||
s.BGPSessionsTotal++
|
||||
if strings.Contains(low, "established") {
|
||||
s.BGPEstablished++
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package birdfmt
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestSummarizeProtocolsOutput(t *testing.T) {
|
||||
sample := `name proto table state since info
|
||||
device1 Device --- up 10:00:00
|
||||
uplink BGP --- start 10:00:01 Established
|
||||
`
|
||||
s := SummarizeProtocolsOutput(sample)
|
||||
if s.BGPSessionsTotal != 1 || s.BGPEstablished != 1 {
|
||||
t.Fatalf("got %+v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSummarizeProtocolsOutput_evoBGPNameNotCountedAsBGP(t *testing.T) {
|
||||
sample := `Name Proto Table State Since Info
|
||||
evobgp_prefixes_v4 Static master4 up 17:32:14.631
|
||||
evobgp_prefixes_v6 Static master6 up 17:32:14.631
|
||||
`
|
||||
s := SummarizeProtocolsOutput(sample)
|
||||
if s.BGPSessionsTotal != 0 || s.BGPEstablished != 0 {
|
||||
t.Fatalf("evobgp_* static names must not match substring bgp: got %+v", s)
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ func CountEstablishedBGPSessions(showProtocolsOutput string) int {
|
||||
if line == "" || strings.HasPrefix(line, "name") || strings.HasPrefix(strings.ToLower(line), "table") {
|
||||
continue
|
||||
}
|
||||
if !strings.Contains(strings.ToLower(line), "bgp") {
|
||||
if !isBGPProtocolSummaryRow(line) {
|
||||
continue
|
||||
}
|
||||
if strings.Contains(strings.ToLower(line), "established") {
|
||||
@@ -50,3 +50,48 @@ func CountEstablishedBGPSessions(showProtocolsOutput string) int {
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// ParseBGPProtocolStates parses `birdc show protocols all` summary rows into protocol_name -> state.
|
||||
func ParseBGPProtocolStates(output string) map[string]string {
|
||||
out := make(map[string]string)
|
||||
for _, raw := range strings.Split(output, "\n") {
|
||||
line := strings.TrimSpace(raw)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
low := strings.ToLower(line)
|
||||
if strings.HasPrefix(low, "bird ") || strings.HasPrefix(low, "name ") || strings.HasPrefix(low, "table ") {
|
||||
continue
|
||||
}
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) < 4 {
|
||||
continue
|
||||
}
|
||||
if !strings.EqualFold(fields[1], "BGP") {
|
||||
continue
|
||||
}
|
||||
state := extractBGPSessionStateLine(line)
|
||||
if state == "" {
|
||||
state = fields[3]
|
||||
}
|
||||
out[fields[0]] = state
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func extractBGPSessionStateLine(line string) string {
|
||||
known := []string{
|
||||
"Established",
|
||||
"Idle",
|
||||
"Connect",
|
||||
"Active",
|
||||
"OpenSent",
|
||||
"OpenConfirm",
|
||||
}
|
||||
for _, st := range known {
|
||||
if strings.Contains(line, st) {
|
||||
return st
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -11,13 +11,13 @@ import (
|
||||
func TestStandardLayout_GeneratorMatchesFixtures(t *testing.T) {
|
||||
p4 := netip.MustParsePrefix("203.0.113.0/24")
|
||||
|
||||
f4, err := RenderExportFilterIPv4("evobgp_export_v4", []netip.Prefix{p4})
|
||||
f4, err := RenderExportFilterIPv4("evobgp_export_v4", []netip.Prefix{p4}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertFileEquals(t, "testdata/scenarios/standard_layout/bird.d/evobgp_filters_v4.conf", f4)
|
||||
|
||||
f6, err := RenderExportFilterIPv6("evobgp_export_v6", nil)
|
||||
f6, err := RenderExportFilterIPv6("evobgp_export_v6", nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -29,13 +29,21 @@ func TestStandardLayout_GeneratorMatchesFixtures(t *testing.T) {
|
||||
staticV6 := RenderStaticIPv6Protocol("evobgp_prefixes_v6", nil)
|
||||
assertFileEquals(t, "testdata/scenarios/standard_layout/bird.d/evobgp_prefixes_v6.conf", staticV6)
|
||||
|
||||
peer, err := RenderProtocolBGPIPv4(BGPPeerIPv4Options{
|
||||
tpl, err := RenderBGPTemplates(BGPTemplatesOptions{
|
||||
LocalASN: 65001,
|
||||
ExportFilterV4: "evobgp_export_v4",
|
||||
ExportFilterV6: "evobgp_export_v6",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertFileEquals(t, "testdata/scenarios/standard_layout/bird.d/evobgp_bgp_template.conf", tpl)
|
||||
|
||||
peer, err := RenderProtocolBGPFromTemplate(BGPPeerFromTemplateOptions{
|
||||
ProtocolName: "evobgp_peer_ci",
|
||||
LocalIP: "192.0.2.1",
|
||||
LocalASN: 65001,
|
||||
TemplateName: BGPTemplateNameV4,
|
||||
NeighborIP: "192.0.2.2",
|
||||
NeighborASN: 65002,
|
||||
ExportFilter: "evobgp_export_v4",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
package birdfmt
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// StaticRoute is one static route line in BIRD (optionally with a per-route body).
|
||||
type StaticRoute struct {
|
||||
Prefix netip.Prefix
|
||||
RouteBody string // optional lines inside `route P unreachable { ... }`
|
||||
}
|
||||
|
||||
// RenderStaticIPv4Routes renders a BIRD 2 protocol static block for IPv4.
|
||||
func RenderStaticIPv4Routes(protocolName string, routes []StaticRoute) string {
|
||||
if protocolName == "" {
|
||||
protocolName = "evobgp_prefixes_v4"
|
||||
}
|
||||
type key struct {
|
||||
p string
|
||||
b string
|
||||
}
|
||||
uniq := make(map[key]StaticRoute)
|
||||
for _, r := range routes {
|
||||
if !r.Prefix.Addr().Is4() {
|
||||
continue
|
||||
}
|
||||
p := r.Prefix.Masked()
|
||||
body := strings.TrimSpace(r.RouteBody)
|
||||
uniq[key{p.String(), body}] = StaticRoute{Prefix: p, RouteBody: body}
|
||||
}
|
||||
keys := make([]key, 0, len(uniq))
|
||||
for k := range uniq {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Slice(keys, func(i, j int) bool {
|
||||
if keys[i].p != keys[j].p {
|
||||
return keys[i].p < keys[j].p
|
||||
}
|
||||
return keys[i].b < keys[j].b
|
||||
})
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString("protocol static ")
|
||||
b.WriteString(protocolName)
|
||||
b.WriteString(" {\n ipv4;\n")
|
||||
for _, k := range keys {
|
||||
r := uniq[k]
|
||||
p := r.Prefix.String()
|
||||
if r.RouteBody == "" {
|
||||
b.WriteString(" route ")
|
||||
b.WriteString(p)
|
||||
b.WriteString(" unreachable;\n")
|
||||
continue
|
||||
}
|
||||
b.WriteString(" route ")
|
||||
b.WriteString(p)
|
||||
b.WriteString(" unreachable {\n")
|
||||
for _, line := range strings.Split(r.RouteBody, "\n") {
|
||||
line = strings.TrimRight(line, "\r")
|
||||
if strings.TrimSpace(line) == "" {
|
||||
continue
|
||||
}
|
||||
if !strings.HasPrefix(line, " ") && !strings.HasPrefix(line, "\t") {
|
||||
b.WriteString(" ")
|
||||
}
|
||||
b.WriteString(line)
|
||||
b.WriteByte('\n')
|
||||
}
|
||||
b.WriteString(" };\n")
|
||||
}
|
||||
b.WriteString("}\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// RenderStaticIPv6Routes renders a BIRD 2 protocol static block for IPv6.
|
||||
func RenderStaticIPv6Routes(protocolName string, routes []StaticRoute) string {
|
||||
if protocolName == "" {
|
||||
protocolName = "evobgp_prefixes_v6"
|
||||
}
|
||||
type key struct {
|
||||
p string
|
||||
b string
|
||||
}
|
||||
uniq := make(map[key]StaticRoute)
|
||||
for _, r := range routes {
|
||||
if !r.Prefix.Addr().Is6() {
|
||||
continue
|
||||
}
|
||||
p := r.Prefix.Masked()
|
||||
body := strings.TrimSpace(r.RouteBody)
|
||||
uniq[key{p.String(), body}] = StaticRoute{Prefix: p, RouteBody: body}
|
||||
}
|
||||
keys := make([]key, 0, len(uniq))
|
||||
for k := range uniq {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Slice(keys, func(i, j int) bool {
|
||||
if keys[i].p != keys[j].p {
|
||||
return keys[i].p < keys[j].p
|
||||
}
|
||||
return keys[i].b < keys[j].b
|
||||
})
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString("protocol static ")
|
||||
b.WriteString(protocolName)
|
||||
b.WriteString(" {\n ipv6;\n")
|
||||
for _, k := range keys {
|
||||
r := uniq[k]
|
||||
p := r.Prefix.String()
|
||||
if r.RouteBody == "" {
|
||||
b.WriteString(" route ")
|
||||
b.WriteString(p)
|
||||
b.WriteString(" unreachable;\n")
|
||||
continue
|
||||
}
|
||||
b.WriteString(" route ")
|
||||
b.WriteString(p)
|
||||
b.WriteString(" unreachable {\n")
|
||||
for _, line := range strings.Split(r.RouteBody, "\n") {
|
||||
line = strings.TrimRight(line, "\r")
|
||||
if strings.TrimSpace(line) == "" {
|
||||
continue
|
||||
}
|
||||
if !strings.HasPrefix(line, " ") && !strings.HasPrefix(line, "\t") {
|
||||
b.WriteString(" ")
|
||||
}
|
||||
b.WriteString(line)
|
||||
b.WriteByte('\n')
|
||||
}
|
||||
b.WriteString(" };\n")
|
||||
}
|
||||
b.WriteString("}\n")
|
||||
return b.String()
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package birdfmt
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRenderStaticIPv4Routes_WithCommunity(t *testing.T) {
|
||||
p := netip.MustParsePrefix("203.0.113.0/24")
|
||||
s := RenderStaticIPv4Routes("t", []StaticRoute{
|
||||
{Prefix: p, RouteBody: " bgp_community.add((65000,1));"},
|
||||
})
|
||||
if !strings.Contains(s, "route 203.0.113.0/24 unreachable {") {
|
||||
t.Fatalf("missing block: %s", s)
|
||||
}
|
||||
if !strings.Contains(s, "bgp_community.add((65000,1))") {
|
||||
t.Fatalf("missing community: %s", s)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ router id 192.0.2.1;
|
||||
|
||||
include "bird.d/evobgp_filters_v4.conf";
|
||||
include "bird.d/evobgp_filters_v6.conf";
|
||||
include "bird.d/evobgp_bgp_template.conf";
|
||||
include "bird.d/evobgp_prefixes_v4.conf";
|
||||
include "bird.d/evobgp_prefixes_v6.conf";
|
||||
include "bird.d/evobgp_peers.conf";
|
||||
|
||||
@@ -5,6 +5,7 @@ router id 192.0.2.1;
|
||||
|
||||
include "bird.d/evobgp_filters_v4.conf";
|
||||
include "bird.d/evobgp_filters_v6.conf";
|
||||
include "bird.d/evobgp_bgp_template.conf";
|
||||
include "bird.d/evobgp_prefixes_v4.conf";
|
||||
include "bird.d/evobgp_prefixes_v6.conf";
|
||||
include "bird.d/evobgp_peers.conf";
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
template bgp bgp_template {
|
||||
local as 65001;
|
||||
ipv4 {
|
||||
import none;
|
||||
export filter evobgp_export_v4;
|
||||
};
|
||||
hold time 90;
|
||||
keepalive time 30;
|
||||
}
|
||||
|
||||
template bgp bgp_template_v6 {
|
||||
local as 65001;
|
||||
ipv6 {
|
||||
import none;
|
||||
export filter evobgp_export_v6;
|
||||
};
|
||||
hold time 90;
|
||||
keepalive time 30;
|
||||
}
|
||||
+3
-6
@@ -1,8 +1,5 @@
|
||||
protocol bgp evobgp_peer_ci {
|
||||
local 192.0.2.1 as 65001;
|
||||
protocol bgp evobgp_peer_ci from bgp_template {
|
||||
neighbor 192.0.2.2 as 65002;
|
||||
ipv4 {
|
||||
import all;
|
||||
export filter evobgp_export_v4;
|
||||
};
|
||||
multihop;
|
||||
passive;
|
||||
}
|
||||
@@ -17,12 +17,12 @@ import (
|
||||
|
||||
// Manifest describes bundle contents for evobgp-node verification.
|
||||
type Manifest struct {
|
||||
RevisionID string `json:"revision_id"`
|
||||
SpeakerID string `json:"speaker_id,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Files []FileEntry `json:"files"`
|
||||
Algorithm string `json:"signature_algorithm"`
|
||||
PublicKeyB64 string `json:"public_key_base64"`
|
||||
RevisionID string `json:"revision_id"`
|
||||
SpeakerID string `json:"speaker_id,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Files []FileEntry `json:"files"`
|
||||
Algorithm string `json:"signature_algorithm"`
|
||||
PublicKeyB64 string `json:"public_key_base64"`
|
||||
}
|
||||
|
||||
// FileEntry is one file inside the bundle archive.
|
||||
@@ -47,6 +47,9 @@ func BuildGzippedTar(revisionID, speakerID string, fragments map[string]string,
|
||||
if p == "." || strings.HasPrefix(p, "..") {
|
||||
return nil, fmt.Errorf("bundle: invalid path %q", p)
|
||||
}
|
||||
if strings.HasPrefix(p, "_") {
|
||||
continue // UI-only preview aggregate, not shipped to nodes
|
||||
}
|
||||
norm[p] = content
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ func VerifyGzippedTar(bundle []byte, pub ed25519.PublicKey) (*VerifiedContents,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer gr.Close()
|
||||
defer func() { _ = gr.Close() }()
|
||||
|
||||
var manifestRaw []byte
|
||||
var sig []byte
|
||||
|
||||
@@ -6,9 +6,12 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"evobgp/migrations"
|
||||
|
||||
@@ -22,6 +25,17 @@ func OpenPostgresPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if max := os.Getenv("EVOBGP_DB_MAX_CONNS"); max != "" {
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(max)); err == nil && n > 0 {
|
||||
cfg.MaxConns = int32(n)
|
||||
}
|
||||
}
|
||||
if min := os.Getenv("EVOBGP_DB_MIN_CONNS"); min != "" {
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(min)); err == nil && n >= 0 {
|
||||
cfg.MinConns = int32(n)
|
||||
}
|
||||
}
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"sync"
|
||||
|
||||
"evobgp/internal/store"
|
||||
)
|
||||
|
||||
type apiKeyResolver struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
envByToken map[string]apiKeyRecord
|
||||
byHash map[string]apiKeyRecord
|
||||
}
|
||||
|
||||
func newAPIKeyResolver(envSpec string, st store.Backend) (*apiKeyResolver, error) {
|
||||
r := &apiKeyResolver{
|
||||
envByToken: make(map[string]apiKeyRecord),
|
||||
byHash: make(map[string]apiKeyRecord),
|
||||
}
|
||||
for _, rec := range parseAPIKeysSpec(envSpec) {
|
||||
r.envByToken[rec.token] = rec
|
||||
}
|
||||
return r, r.reloadFromStore(st)
|
||||
}
|
||||
|
||||
func (r *apiKeyResolver) reloadFromStore(st store.Backend) error {
|
||||
rows, err := st.ListActiveAPIKeyHashes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
byHash := make(map[string]apiKeyRecord, len(rows))
|
||||
for _, row := range rows {
|
||||
if len(row.TokenHash) != 32 {
|
||||
continue
|
||||
}
|
||||
byHash[hex.EncodeToString(row.TokenHash)] = apiKeyRecord{
|
||||
token: "",
|
||||
tenantID: row.TenantID,
|
||||
role: row.Role,
|
||||
keyID: row.ID,
|
||||
}
|
||||
}
|
||||
r.mu.Lock()
|
||||
r.byHash = byHash
|
||||
r.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *apiKeyResolver) Reload(st store.Backend) error {
|
||||
return r.reloadFromStore(st)
|
||||
}
|
||||
|
||||
func (r *apiKeyResolver) Lookup(raw string) (apiKeyRecord, bool) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
if rec, ok := r.envByToken[raw]; ok {
|
||||
return rec, true
|
||||
}
|
||||
sum := sha256.Sum256([]byte(raw))
|
||||
key := hex.EncodeToString(sum[:])
|
||||
rec, ok := r.byHash[key]
|
||||
return rec, ok
|
||||
}
|
||||
+13
-21
@@ -15,6 +15,7 @@ type Auth struct {
|
||||
TenantID string
|
||||
Role string // viewer, editor, operator, node
|
||||
Token string
|
||||
APIKeyID string // non-empty for DB-managed keys
|
||||
}
|
||||
|
||||
func authFromContext(ctx context.Context) (Auth, bool) {
|
||||
@@ -26,6 +27,7 @@ type apiKeyRecord struct {
|
||||
token string
|
||||
tenantID string
|
||||
role string
|
||||
keyID string // set for DB-managed keys (last_used_at)
|
||||
}
|
||||
|
||||
func parseAPIKeysSpec(spec string) []apiKeyRecord {
|
||||
@@ -54,20 +56,6 @@ func parseAPIKeysSpec(spec string) []apiKeyRecord {
|
||||
|
||||
func (s *Server) authMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if s.insecureDev {
|
||||
h := r.Header.Get("Authorization")
|
||||
const p = "Bearer "
|
||||
if strings.HasPrefix(h, p) {
|
||||
tok := strings.TrimSpace(strings.TrimPrefix(h, p))
|
||||
if tok == "dev" {
|
||||
if a, ok := s.devAuth(); ok {
|
||||
r = r.WithContext(context.WithValue(r.Context(), authCtxKey, a))
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
h := r.Header.Get("Authorization")
|
||||
const p = "Bearer "
|
||||
if !strings.HasPrefix(h, p) {
|
||||
@@ -75,18 +63,22 @@ func (s *Server) authMiddleware(next http.Handler) http.Handler {
|
||||
return
|
||||
}
|
||||
raw := strings.TrimSpace(strings.TrimPrefix(h, p))
|
||||
var matched *apiKeyRecord
|
||||
for i := range s.apiKeys {
|
||||
if s.apiKeys[i].token == raw {
|
||||
matched = &s.apiKeys[i]
|
||||
break
|
||||
if raw == "dev" {
|
||||
if a, ok := s.devAuth(); ok {
|
||||
r = r.WithContext(context.WithValue(r.Context(), authCtxKey, a))
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
if matched == nil {
|
||||
matched, ok := s.keyResolver.Lookup(raw)
|
||||
if !ok {
|
||||
writeProblem(w, http.StatusUnauthorized, "Unauthorized", "unknown api key")
|
||||
return
|
||||
}
|
||||
a := Auth{TenantID: matched.tenantID, Role: matched.role, Token: raw}
|
||||
a := Auth{TenantID: matched.tenantID, Role: matched.role, Token: raw, APIKeyID: matched.keyID}
|
||||
if matched.keyID != "" {
|
||||
go func(id string) { _ = s.store.TouchAPIKeyLastUsed(id) }(matched.keyID)
|
||||
}
|
||||
r = r.WithContext(context.WithValue(r.Context(), authCtxKey, a))
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
|
||||
@@ -15,6 +15,11 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// NewCDNHTTPClient returns the shared HTTP client for CDN and preview fetches (PERF-02 / ERR-03).
|
||||
func NewCDNHTTPClient() *http.Client {
|
||||
return &http.Client{Timeout: 45 * time.Second}
|
||||
}
|
||||
|
||||
// BootstrapWorkers opens the same store.Backend and jobs.Registry as New (without HTTP or bundle keys).
|
||||
// Used by standalone worker binaries (scheduler, ingest, …) that share PostgreSQL with the API.
|
||||
func BootstrapWorkers(ctx context.Context, opts Options) (store.Backend, *jobs.Registry, *pgxpool.Pool, error) {
|
||||
@@ -44,9 +49,25 @@ func BootstrapWorkers(ctx context.Context, opts Options) (store.Backend, *jobs.R
|
||||
backend = mem
|
||||
}
|
||||
|
||||
cdnHTTP := &http.Client{Timeout: 45 * time.Second}
|
||||
cdnHTTP := NewCDNHTTPClient()
|
||||
wk := &jobs.Worker{Store: backend, HTTPClient: cdnHTTP}
|
||||
reg := jobs.NewRegistry(wk.Process)
|
||||
wk.Registry = reg
|
||||
if pool != nil {
|
||||
audit := repository.NewJobAuditWriter(pool)
|
||||
reg.SetTerminalHook(func(j *jobs.Job) {
|
||||
if j == nil {
|
||||
return
|
||||
}
|
||||
st := j.Snapshot()
|
||||
status, _ := st["status"].(string)
|
||||
var errMsg *string
|
||||
if e, ok := st["error"].(string); ok && e != "" {
|
||||
errMsg = &e
|
||||
}
|
||||
audit.MarkTerminal(context.Background(), j.TenantID, j.ID, status, errMsg, time.Now().UTC())
|
||||
})
|
||||
}
|
||||
observability.RegisterStoreBackend(backend)
|
||||
return backend, reg, pool, nil
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"evobgp/internal/store"
|
||||
)
|
||||
|
||||
func parseListLimit(r *http.Request) int {
|
||||
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||
if limit <= 0 {
|
||||
return 50
|
||||
}
|
||||
if limit > 500 {
|
||||
return 500
|
||||
}
|
||||
return limit
|
||||
}
|
||||
|
||||
func strPtrOrNull(s string) any {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// writePaginatedListJSON returns a cursor/limit page as OpenAPI list envelopes (items, next_cursor, has_more).
|
||||
func writePaginatedListJSON[T any](w http.ResponseWriter, r *http.Request, all []T, toItem func(T) map[string]any) {
|
||||
page, next, more := store.PaginateOffset(all, r.URL.Query().Get("cursor"), parseListLimit(r))
|
||||
items := make([]map[string]any, 0, len(page))
|
||||
for _, x := range page {
|
||||
items = append(items, toItem(x))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"items": items, "next_cursor": strPtrOrNull(next), "has_more": more,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/netip"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"evobgp/internal/birdfmt"
|
||||
"evobgp/internal/nodedispatch"
|
||||
"evobgp/internal/store"
|
||||
)
|
||||
|
||||
const peerLiveCacheTTL = 15 * time.Second
|
||||
|
||||
type speakerBGPLive struct {
|
||||
SpeakerID string
|
||||
Label string
|
||||
Sessions []birdfmt.BGPSession
|
||||
Error string
|
||||
}
|
||||
|
||||
type peerLiveCacheEntry struct {
|
||||
at time.Time
|
||||
views []speakerBGPLive
|
||||
}
|
||||
|
||||
var peerLiveCache sync.Map // tenantID -> peerLiveCacheEntry
|
||||
|
||||
type peerSessionOnSpeaker struct {
|
||||
SpeakerID string `json:"speaker_id"`
|
||||
Label string `json:"label"`
|
||||
State string `json:"state"`
|
||||
PollError string `json:"poll_error,omitempty"`
|
||||
}
|
||||
|
||||
type liveSpeakerPoll struct {
|
||||
SpeakerID string `json:"speaker_id"`
|
||||
Label string `json:"label"`
|
||||
OK bool `json:"ok"`
|
||||
SessionCount int `json:"session_count"`
|
||||
PollError string `json:"poll_error,omitempty"`
|
||||
}
|
||||
|
||||
func speakerDisplayLabel(sp *store.Speaker) string {
|
||||
if sp == nil {
|
||||
return ""
|
||||
}
|
||||
meta := store.ParseSpeakerMeta(sp.MetaJSON)
|
||||
host := strings.TrimSpace(meta.AgentDomain)
|
||||
if host == "" {
|
||||
host = strings.TrimSpace(sp.Endpoint)
|
||||
}
|
||||
if strings.EqualFold(strings.TrimSpace(sp.Role), "master") {
|
||||
if host != "" {
|
||||
return "CP · " + host
|
||||
}
|
||||
return "CP (master)"
|
||||
}
|
||||
if host != "" {
|
||||
return host
|
||||
}
|
||||
return sp.ID
|
||||
}
|
||||
|
||||
func masterSpeakerID(speakers []*store.Speaker) string {
|
||||
for _, sp := range speakers {
|
||||
if sp != nil && strings.EqualFold(strings.TrimSpace(sp.Role), "master") {
|
||||
return sp.ID
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *Server) collectSpeakerBGPLive(ctx context.Context, tenantID string, fresh bool) []speakerBGPLive {
|
||||
if !fresh {
|
||||
if v, ok := peerLiveCache.Load(tenantID); ok {
|
||||
ent := v.(peerLiveCacheEntry)
|
||||
if time.Since(ent.at) < peerLiveCacheTTL {
|
||||
return ent.views
|
||||
}
|
||||
}
|
||||
}
|
||||
speakers := s.store.ListSpeakersForTenant(tenantID)
|
||||
views := make([]speakerBGPLive, 0, len(speakers)+1)
|
||||
|
||||
if sock := strings.TrimSpace(os.Getenv("EVOBGP_BIRDC_SOCKET")); sock != "" {
|
||||
v := speakerBGPLive{Label: "CP (local BIRD)"}
|
||||
if mid := masterSpeakerID(speakers); mid != "" {
|
||||
v.SpeakerID = mid
|
||||
for _, sp := range speakers {
|
||||
if sp != nil && sp.ID == mid {
|
||||
v.Label = speakerDisplayLabel(sp)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
out, err := birdfmt.ShowProtocols(ctx, sock, strings.TrimSpace(os.Getenv("EVOBGP_BIRDC_BIN")))
|
||||
if err != nil {
|
||||
v.Error = err.Error()
|
||||
} else {
|
||||
v.Sessions = birdfmt.ParseBGPSessions(out)
|
||||
}
|
||||
views = append(views, v)
|
||||
}
|
||||
|
||||
opts := nodedispatch.Options{Timeout: 8 * time.Second}
|
||||
type resWrap struct {
|
||||
sp *store.Speaker
|
||||
res nodedispatch.BirdProtocolsResult
|
||||
}
|
||||
ch := make(chan resWrap, len(speakers))
|
||||
var wg sync.WaitGroup
|
||||
for _, sp := range speakers {
|
||||
if sp == nil {
|
||||
continue
|
||||
}
|
||||
meta := store.ParseSpeakerMeta(sp.MetaJSON)
|
||||
if !store.SpeakerNeedsRemoteDispatch(sp.Role, meta) {
|
||||
continue
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(speaker *store.Speaker) {
|
||||
defer wg.Done()
|
||||
ch <- resWrap{
|
||||
sp: speaker,
|
||||
res: nodedispatch.FetchBirdProtocols(ctx, speaker, opts),
|
||||
}
|
||||
}(sp)
|
||||
}
|
||||
wg.Wait()
|
||||
close(ch)
|
||||
for rw := range ch {
|
||||
views = append(views, speakerBGPLive{
|
||||
SpeakerID: rw.sp.ID,
|
||||
Label: speakerDisplayLabel(rw.sp),
|
||||
Sessions: rw.res.Sessions,
|
||||
Error: rw.res.Error,
|
||||
})
|
||||
}
|
||||
|
||||
peerLiveCache.Store(tenantID, peerLiveCacheEntry{at: time.Now(), views: views})
|
||||
return views
|
||||
}
|
||||
|
||||
func liveSpeakerPollJSON(views []speakerBGPLive) []liveSpeakerPoll {
|
||||
out := make([]liveSpeakerPoll, 0, len(views))
|
||||
for _, v := range views {
|
||||
out = append(out, liveSpeakerPoll{
|
||||
SpeakerID: v.SpeakerID,
|
||||
Label: v.Label,
|
||||
OK: v.Error == "",
|
||||
SessionCount: len(v.Sessions),
|
||||
PollError: v.Error,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func findPeerSession(sessions []birdfmt.BGPSession, protoName string, neighbor netip.Addr, hasNeighbor bool) *birdfmt.BGPSession {
|
||||
for i := range sessions {
|
||||
if peerSessionMatches(sessions[i], protoName, neighbor, hasNeighbor) {
|
||||
return &sessions[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func matchPeerOnSpeakers(peer *store.BGPPeer, views []speakerBGPLive) (
|
||||
bestState string,
|
||||
connectedID string,
|
||||
connectedLabel string,
|
||||
establishedOn []peerSessionOnSpeaker,
|
||||
on []peerSessionOnSpeaker,
|
||||
mismatch bool,
|
||||
) {
|
||||
if peer == nil {
|
||||
return "", "", "", nil, nil, false
|
||||
}
|
||||
neighbor, hasNeighbor := store.ParsePeerNeighbor(peer.Neighbor)
|
||||
protoName := birdfmt.PeerProtocolName(peer.ID)
|
||||
|
||||
for _, v := range views {
|
||||
if v.Error != "" && len(v.Sessions) == 0 {
|
||||
on = append(on, peerSessionOnSpeaker{
|
||||
SpeakerID: v.SpeakerID,
|
||||
Label: v.Label,
|
||||
PollError: v.Error,
|
||||
})
|
||||
continue
|
||||
}
|
||||
sess := findPeerSession(v.Sessions, protoName, neighbor, hasNeighbor)
|
||||
if sess == nil {
|
||||
on = append(on, peerSessionOnSpeaker{
|
||||
SpeakerID: v.SpeakerID,
|
||||
Label: v.Label,
|
||||
State: "absent",
|
||||
})
|
||||
continue
|
||||
}
|
||||
hit := peerSessionOnSpeaker{
|
||||
SpeakerID: v.SpeakerID,
|
||||
Label: v.Label,
|
||||
State: sess.State,
|
||||
}
|
||||
on = append(on, hit)
|
||||
if strings.EqualFold(strings.TrimSpace(sess.State), "Established") {
|
||||
establishedOn = append(establishedOn, hit)
|
||||
}
|
||||
if bestState == "" || sessionStateRank(sess.State) > sessionStateRank(bestState) {
|
||||
bestState = sess.State
|
||||
}
|
||||
}
|
||||
|
||||
if len(establishedOn) > 0 {
|
||||
bestState = "Established"
|
||||
labels := make([]string, 0, len(establishedOn))
|
||||
for _, e := range establishedOn {
|
||||
labels = append(labels, e.Label)
|
||||
}
|
||||
connectedLabel = strings.Join(labels, ", ")
|
||||
if len(establishedOn) == 1 {
|
||||
connectedID = establishedOn[0].SpeakerID
|
||||
}
|
||||
} else if len(on) == 1 && on[0].PollError == "" && on[0].State != "" {
|
||||
connectedID = on[0].SpeakerID
|
||||
connectedLabel = on[0].Label
|
||||
}
|
||||
|
||||
if peer.SpeakerID != nil && strings.TrimSpace(*peer.SpeakerID) != "" && len(establishedOn) > 0 {
|
||||
want := strings.TrimSpace(*peer.SpeakerID)
|
||||
found := false
|
||||
for _, e := range establishedOn {
|
||||
if strings.EqualFold(strings.TrimSpace(e.SpeakerID), want) {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
mismatch = !found
|
||||
}
|
||||
return bestState, connectedID, connectedLabel, establishedOn, on, mismatch
|
||||
}
|
||||
|
||||
func peerSessionMatches(sess birdfmt.BGPSession, protoName string, neighbor netip.Addr, hasNeighbor bool) bool {
|
||||
if strings.EqualFold(strings.TrimSpace(sess.Name), protoName) {
|
||||
return true
|
||||
}
|
||||
if !hasNeighbor || strings.TrimSpace(sess.Neighbor) == "" {
|
||||
return false
|
||||
}
|
||||
peerAddr, ok := store.ParsePeerNeighbor(sess.Neighbor)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
return peerAddr == neighbor
|
||||
}
|
||||
|
||||
func sessionStateRank(state string) int {
|
||||
switch strings.ToLower(strings.TrimSpace(state)) {
|
||||
case "established":
|
||||
return 100
|
||||
case "openconfirm", "opensent":
|
||||
return 80
|
||||
case "active", "connect":
|
||||
return 60
|
||||
case "idle":
|
||||
return 20
|
||||
default:
|
||||
return 10
|
||||
}
|
||||
}
|
||||
|
||||
func applyPeerLiveFields(row map[string]any, peer *store.BGPPeer, views []speakerBGPLive) {
|
||||
state, connID, connLabel, establishedOn, on, mismatch := matchPeerOnSpeakers(peer, views)
|
||||
row["session_on_speakers"] = on
|
||||
row["established_on_speakers"] = establishedOn
|
||||
row["session_conflict"] = false
|
||||
row["session_mismatch"] = mismatch
|
||||
if state != "" {
|
||||
row["session_state"] = state
|
||||
}
|
||||
if connLabel != "" {
|
||||
row["connected_speaker_label"] = connLabel
|
||||
}
|
||||
row["connected_speaker_id"] = peerLiveSpeakerIDOrNull(connID)
|
||||
}
|
||||
|
||||
func peerLiveSpeakerIDOrNull(id string) any {
|
||||
if strings.TrimSpace(id) == "" {
|
||||
return nil
|
||||
}
|
||||
return id
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"evobgp/internal/birdfmt"
|
||||
"evobgp/internal/store"
|
||||
)
|
||||
|
||||
func TestMatchPeerOnSpeakers_establishedOnReplica(t *testing.T) {
|
||||
peer := &store.BGPPeer{
|
||||
ID: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
|
||||
Neighbor: "198.51.100.2",
|
||||
}
|
||||
views := []speakerBGPLive{
|
||||
{
|
||||
SpeakerID: "master-id",
|
||||
Label: "CP · bgp.shz.su",
|
||||
Sessions: []birdfmt.BGPSession{
|
||||
{Name: birdfmt.PeerProtocolName(peer.ID), Neighbor: "198.51.100.2", State: "Established"},
|
||||
},
|
||||
},
|
||||
{
|
||||
SpeakerID: "replica-id",
|
||||
Label: "bgp2.shz.su",
|
||||
Sessions: []birdfmt.BGPSession{
|
||||
{Name: birdfmt.PeerProtocolName(peer.ID), Neighbor: "198.51.100.2", State: "Established"},
|
||||
},
|
||||
},
|
||||
}
|
||||
state, connID, connLabel, established, on, mismatch := matchPeerOnSpeakers(peer, views)
|
||||
if state != "Established" || connID != "" || connLabel != "CP · bgp.shz.su, bgp2.shz.su" {
|
||||
t.Fatalf("got state=%q conn=%q label=%q", state, connID, connLabel)
|
||||
}
|
||||
if mismatch || len(on) != 2 || len(established) != 2 {
|
||||
t.Fatalf("on=%+v established=%+v mismatch=%v", on, established, mismatch)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchPeerOnSpeakers_multipleEstablished(t *testing.T) {
|
||||
peer := &store.BGPPeer{ID: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", Neighbor: "198.51.100.2/32"}
|
||||
views := []speakerBGPLive{
|
||||
{SpeakerID: "a", Label: "n1", Sessions: []birdfmt.BGPSession{{Name: birdfmt.PeerProtocolName(peer.ID), State: "Established"}}},
|
||||
{SpeakerID: "b", Label: "n2", Sessions: []birdfmt.BGPSession{{Name: birdfmt.PeerProtocolName(peer.ID), State: "Established"}}},
|
||||
}
|
||||
_, connID, label, established, on, mismatch := matchPeerOnSpeakers(peer, views)
|
||||
if mismatch || connID != "" || label != "n1, n2" || len(established) != 2 || len(on) != 2 {
|
||||
t.Fatalf("connID=%q label=%q established=%+v on=%+v mismatch=%v", connID, label, established, on, mismatch)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchPeerOnSpeakers_mismatchConfiguredSpeaker(t *testing.T) {
|
||||
replica := "replica-id"
|
||||
peer := &store.BGPPeer{
|
||||
ID: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
|
||||
Neighbor: "198.51.100.2",
|
||||
SpeakerID: &replica,
|
||||
}
|
||||
views := []speakerBGPLive{
|
||||
{SpeakerID: "master-id", Label: "CP", Sessions: []birdfmt.BGPSession{{Name: birdfmt.PeerProtocolName(peer.ID), State: "Established"}}},
|
||||
{SpeakerID: replica, Label: "bgp2", Sessions: []birdfmt.BGPSession{{Name: birdfmt.PeerProtocolName(peer.ID), State: "Idle"}}},
|
||||
}
|
||||
_, _, _, _, _, mismatch := matchPeerOnSpeakers(peer, views)
|
||||
if !mismatch {
|
||||
t.Fatal("expected mismatch when configured replica has no Established")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchPeerOnSpeakers_pollError(t *testing.T) {
|
||||
peer := &store.BGPPeer{ID: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", Neighbor: "198.51.100.2"}
|
||||
views := []speakerBGPLive{
|
||||
{Label: "CP (local BIRD)", Sessions: []birdfmt.BGPSession{{Name: birdfmt.PeerProtocolName(peer.ID), State: "Established"}}},
|
||||
{SpeakerID: "replica-id", Label: "bgp2.shz.su", Error: "HTTP 404: Not Found"},
|
||||
}
|
||||
_, _, _, established, on, _ := matchPeerOnSpeakers(peer, views)
|
||||
if len(established) != 1 || len(on) != 2 || on[1].PollError == "" {
|
||||
t.Fatalf("on=%+v established=%+v", on, established)
|
||||
}
|
||||
}
|
||||
@@ -2,16 +2,26 @@ package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
const (
|
||||
internalErrorDetail = "an internal error occurred"
|
||||
badGatewayDetail = "upstream request failed"
|
||||
notFoundDetail = "resource not found"
|
||||
invalidInputDetail = "invalid request data"
|
||||
cdnExtractDetail = "could not extract prefixes from source"
|
||||
csvInvalidRowDetail = "invalid row in csv file"
|
||||
)
|
||||
|
||||
// Problem is RFC 9457 application/problem+json.
|
||||
type Problem struct {
|
||||
Type string `json:"type,omitempty"`
|
||||
Title string `json:"title"`
|
||||
Status int `json:"status"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
Instance string `json:"instance,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Title string `json:"title"`
|
||||
Status int `json:"status"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
Instance string `json:"instance,omitempty"`
|
||||
}
|
||||
|
||||
func writeProblem(w http.ResponseWriter, status int, title, detail string) {
|
||||
@@ -34,3 +44,19 @@ func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
func writeNoContent(w http.ResponseWriter) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// writeInternalError logs err server-side and returns a generic 500 problem (ERR-01).
|
||||
func writeInternalError(w http.ResponseWriter, operation string, err error) {
|
||||
if err != nil {
|
||||
log.Printf("httpapi: %s: %v", operation, err)
|
||||
}
|
||||
writeProblem(w, http.StatusInternalServerError, "Internal Error", internalErrorDetail)
|
||||
}
|
||||
|
||||
// writeBadGateway logs err server-side and returns a generic 502 problem (ERR-01).
|
||||
func writeBadGateway(w http.ResponseWriter, operation string, err error) {
|
||||
if err != nil {
|
||||
log.Printf("httpapi: %s: %v", operation, err)
|
||||
}
|
||||
writeProblem(w, http.StatusBadGateway, "Bad Gateway", badGatewayDetail)
|
||||
}
|
||||
+385
-49
@@ -14,10 +14,14 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"evobgp/internal/birdfmt"
|
||||
"evobgp/internal/bundle"
|
||||
"evobgp/internal/jobs"
|
||||
"evobgp/internal/observability"
|
||||
"evobgp/internal/pipeline"
|
||||
"evobgp/internal/reports"
|
||||
"evobgp/internal/store"
|
||||
"evobgp/internal/version"
|
||||
)
|
||||
|
||||
// Handler returns the root HTTP handler (system routes public; rest under /v1/ authenticated).
|
||||
@@ -27,6 +31,7 @@ func (s *Server) Handler() http.Handler {
|
||||
wrappedV1 := http.StripPrefix("/v1", v1)
|
||||
|
||||
s.mux.Handle("GET /metrics", observability.MetricsHandler())
|
||||
s.mux.HandleFunc("GET /version", s.handleVersion)
|
||||
s.mux.HandleFunc("GET /v1/health", s.handleHealth)
|
||||
s.mux.HandleFunc("GET /v1/ready", s.handleReady)
|
||||
s.mux.HandleFunc("GET /v1/version", s.handleVersion)
|
||||
@@ -46,20 +51,26 @@ func (s *Server) registerRoutes() {
|
||||
|
||||
func (s *Server) registerV1(m *http.ServeMux) {
|
||||
m.HandleFunc("GET /modules", s.handleListModules)
|
||||
m.HandleFunc("GET /router-lists/catalog", s.handleRouterListsCatalog)
|
||||
m.HandleFunc("GET /modules/{module_id}", s.handleGetModule)
|
||||
m.HandleFunc("GET /peers", s.handleListPeers)
|
||||
m.HandleFunc("GET /speakers", s.handleListSpeakers)
|
||||
m.HandleFunc("GET /bundle/signing-public-key", s.handleBundleSigningPublicKey)
|
||||
m.HandleFunc("POST /modules/{module_id}/refresh", s.handleModuleRefresh)
|
||||
m.HandleFunc("POST /tenant/refresh", s.handleTenantRefresh)
|
||||
m.HandleFunc("GET /revisions", s.handleListRevisions)
|
||||
m.HandleFunc("GET /revisions/{revision_id}", s.handleGetRevision)
|
||||
m.HandleFunc("GET /revisions/{revision_id}/preview", s.handleRevisionPreview)
|
||||
m.HandleFunc("GET /revisions/{revision_id}/diagnostic-log", s.handleRevisionDiagnosticLog)
|
||||
m.HandleFunc("GET /revisions/{revision_a}/diff/{revision_b}", s.handleRevisionDiff)
|
||||
m.HandleFunc("POST /revisions/{revision_id}/rollback", s.handleRevisionRollback)
|
||||
m.HandleFunc("POST /apply", s.handleApply)
|
||||
m.HandleFunc("POST /speakers/{id}/apply", s.handleSpeakerApply)
|
||||
m.HandleFunc("POST /bird/reload", s.handleBirdReload)
|
||||
m.HandleFunc("GET /bird/status", s.handleBirdStatus)
|
||||
m.HandleFunc("GET /jobs", s.handleListJobs)
|
||||
m.HandleFunc("GET /jobs/{job_id}", s.handleGetJob)
|
||||
m.HandleFunc("GET /jobs/{job_id}/report", s.handleGetJobReport)
|
||||
m.HandleFunc("POST /jobs/{job_id}/cancel", s.handleCancelJob)
|
||||
m.HandleFunc("GET /speakers/{speaker_id}/revisions/latest", s.handleNodeLatestRevision)
|
||||
m.HandleFunc("GET /speakers/{speaker_id}/bundle/{revision_id}", s.handleNodeBundle)
|
||||
@@ -75,12 +86,15 @@ func (s *Server) handleReady(w http.ResponseWriter, r *http.Request) {
|
||||
checks := map[string]string{"store": "ok", "jobs": "memory"}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
if s.pgPool != nil {
|
||||
if err := s.pgPool.Ping(ctx); err != nil {
|
||||
checks["postgres"] = err.Error()
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"status": "not_ready", "checks": checks})
|
||||
return
|
||||
if err := s.store.Ping(ctx); err != nil {
|
||||
checks["store"] = "unavailable"
|
||||
if s.pgPool != nil {
|
||||
checks["postgres"] = "unavailable"
|
||||
}
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"status": "not_ready", "checks": checks})
|
||||
return
|
||||
}
|
||||
if s.pgPool != nil {
|
||||
checks["postgres"] = "ok"
|
||||
} else {
|
||||
checks["store_backend"] = "memory"
|
||||
@@ -89,11 +103,16 @@ func (s *Server) handleReady(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (s *Server) handleVersion(w http.ResponseWriter, r *http.Request) {
|
||||
sha := strings.TrimSpace(os.Getenv("EVOBGP_GIT_SHA"))
|
||||
if sha == "" {
|
||||
sha = "unknown"
|
||||
ver, sha, buildTime := version.Info()
|
||||
resp := map[string]string{
|
||||
"version": ver,
|
||||
"api_version": ver,
|
||||
"git_sha": sha,
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"api_version": "0.1.0", "git_sha": sha})
|
||||
if buildTime != "" {
|
||||
resp["build_time"] = buildTime
|
||||
}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func moduleJSON(mod *store.Module) map[string]any {
|
||||
@@ -106,11 +125,23 @@ func moduleJSON(mod *store.Module) map[string]any {
|
||||
"refresh_interval_sec": mod.RefreshIntervalSec,
|
||||
"cron_expr": mod.CronExpr,
|
||||
}
|
||||
if mod.LastRefreshedAt != nil {
|
||||
m["last_refreshed_at"] = mod.LastRefreshedAt.UTC().Format(time.RFC3339Nano)
|
||||
} else {
|
||||
m["last_refreshed_at"] = nil
|
||||
}
|
||||
if mod.DefaultCommunityID != nil {
|
||||
m["default_community_id"] = *mod.DefaultCommunityID
|
||||
} else {
|
||||
m["default_community_id"] = nil
|
||||
}
|
||||
ids := mod.EffectiveDohProfileIDs()
|
||||
if len(ids) > 0 {
|
||||
m["doh_profile_ids"] = ids
|
||||
} else {
|
||||
m["doh_profile_ids"] = []string{}
|
||||
}
|
||||
m["doh_resolver_policy"] = store.NormalizeDohResolverPolicy(mod.DohResolverPolicy)
|
||||
if mod.DohProfileID != nil {
|
||||
m["doh_profile_id"] = *mod.DohProfileID
|
||||
} else {
|
||||
@@ -137,17 +168,7 @@ func peerJSON(p *store.BGPPeer) map[string]any {
|
||||
}
|
||||
|
||||
func speakerJSON(sp *store.Speaker) map[string]any {
|
||||
m := map[string]any{
|
||||
"id": sp.ID,
|
||||
"role": sp.Role,
|
||||
"endpoint": sp.Endpoint,
|
||||
}
|
||||
if sp.LastAppliedRevisionID != nil {
|
||||
m["last_applied_revision_id"] = *sp.LastAppliedRevisionID
|
||||
} else {
|
||||
m["last_applied_revision_id"] = nil
|
||||
}
|
||||
return m
|
||||
return speakerJSONFromStore(nil, sp)
|
||||
}
|
||||
|
||||
func (s *Server) handleListModules(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -159,13 +180,74 @@ func (s *Server) handleListModules(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.requireAtLeast(w, a, "viewer") {
|
||||
return
|
||||
}
|
||||
mods := s.store.ListModules(a.TenantID)
|
||||
items := make([]map[string]any, 0, len(mods))
|
||||
for _, mod := range mods {
|
||||
typeFilter := strings.TrimSpace(r.URL.Query().Get("type"))
|
||||
enabledRaw := strings.TrimSpace(r.URL.Query().Get("enabled"))
|
||||
var enabledFilter *bool
|
||||
if enabledRaw != "" {
|
||||
v, err := strconv.ParseBool(enabledRaw)
|
||||
if err != nil {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "enabled must be boolean")
|
||||
return
|
||||
}
|
||||
enabledFilter = &v
|
||||
}
|
||||
|
||||
filtered := make([]*store.Module, 0)
|
||||
limit := parseListLimit(r)
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
if typeFilter == "" && enabledFilter == nil {
|
||||
page, next, more := s.store.ListModulesPage(a.TenantID, cursor, limit)
|
||||
for _, mod := range page {
|
||||
filtered = append(filtered, mod)
|
||||
}
|
||||
items := make([]map[string]any, 0, len(filtered))
|
||||
for _, mod := range filtered {
|
||||
items = append(items, moduleJSON(mod))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"items": items, "next_cursor": strPtrOrNull(next), "has_more": more,
|
||||
})
|
||||
return
|
||||
}
|
||||
for _, mod := range s.store.ListModules(a.TenantID) {
|
||||
if typeFilter != "" && mod.Type != typeFilter {
|
||||
continue
|
||||
}
|
||||
if enabledFilter != nil && mod.Enabled != *enabledFilter {
|
||||
continue
|
||||
}
|
||||
filtered = append(filtered, mod)
|
||||
}
|
||||
page, next, more := store.PaginateOffset(filtered, r.URL.Query().Get("cursor"), parseListLimit(r))
|
||||
items := make([]map[string]any, 0, len(page))
|
||||
for _, mod := range page {
|
||||
items = append(items, moduleJSON(mod))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"items": items, "next_cursor": nil, "has_more": false,
|
||||
"items": items, "next_cursor": strPtrOrNull(next), "has_more": more,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleRouterListsCatalog(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok {
|
||||
writeProblem(w, http.StatusUnauthorized, "Unauthorized", "missing auth")
|
||||
return
|
||||
}
|
||||
if !s.requireAtLeast(w, a, "viewer") {
|
||||
return
|
||||
}
|
||||
cat, err := reports.BuildRouterListsCatalog(s.store, a.TenantID)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"modules": map[string]any{"items": cat.Modules},
|
||||
"domains": map[string]any{"items": cat.Domains},
|
||||
"asns": map[string]any{"items": cat.ASNs},
|
||||
"ip_ranges": map[string]any{"items": cat.IPRanges},
|
||||
"communities": map[string]any{"items": cat.Communities},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -184,7 +266,7 @@ func (s *Server) handleGetModule(w http.ResponseWriter, r *http.Request) {
|
||||
writeProblem(w, http.StatusNotFound, "Not Found", "module not found")
|
||||
return
|
||||
}
|
||||
writeProblem(w, http.StatusInternalServerError, "Internal Error", err.Error())
|
||||
writeInternalError(w, "internal", err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, moduleJSON(mod))
|
||||
@@ -199,16 +281,100 @@ func (s *Server) handleListPeers(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.requireAtLeast(w, a, "viewer") {
|
||||
return
|
||||
}
|
||||
peers := s.store.ListPeers(a.TenantID)
|
||||
items := make([]map[string]any, 0, len(peers))
|
||||
for _, p := range peers {
|
||||
items = append(items, peerJSON(p))
|
||||
allPeers := s.store.ListPeers(a.TenantID)
|
||||
page, next, more := store.PaginateOffset(allPeers, r.URL.Query().Get("cursor"), parseListLimit(r))
|
||||
fresh := r != nil && strings.EqualFold(strings.TrimSpace(r.URL.Query().Get("live")), "1")
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second)
|
||||
defer cancel()
|
||||
liveViews := s.collectSpeakerBGPLive(ctx, a.TenantID, fresh)
|
||||
items := make([]map[string]any, 0, len(page))
|
||||
for _, p := range page {
|
||||
row := peerJSON(p)
|
||||
applyPeerLiveFields(row, p, liveViews)
|
||||
items = append(items, row)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"items": items, "next_cursor": nil, "has_more": false,
|
||||
"items": items,
|
||||
"next_cursor": strPtrOrNull(next),
|
||||
"has_more": more,
|
||||
"live_speaker_poll": liveSpeakerPollJSON(liveViews),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) liveBGPProtocolStates(r *http.Request) map[string]string {
|
||||
if r != nil && strings.EqualFold(strings.TrimSpace(r.URL.Query().Get("live")), "1") {
|
||||
return s.liveBGPProtocolStatesFresh(r.Context())
|
||||
}
|
||||
if cached, ok := observability.CachedBirdProtocolStates(90 * time.Second); ok {
|
||||
return cached
|
||||
}
|
||||
return s.liveBGPProtocolStatesFresh(r.Context())
|
||||
}
|
||||
|
||||
func (s *Server) liveBGPProtocolStatesFresh(ctx context.Context) map[string]string {
|
||||
sock := strings.TrimSpace(os.Getenv("EVOBGP_BIRDC_SOCKET"))
|
||||
if sock == "" {
|
||||
return map[string]string{}
|
||||
}
|
||||
out, err := birdfmt.ShowProtocols(ctx, sock, strings.TrimSpace(os.Getenv("EVOBGP_BIRDC_BIN")))
|
||||
if err != nil {
|
||||
return map[string]string{}
|
||||
}
|
||||
states := birdfmt.ParseBGPProtocolStates(out)
|
||||
observability.SetBirdProtocolStates(states)
|
||||
return states
|
||||
}
|
||||
|
||||
// parseBGPProtocolStates parses `birdc show protocols all` summary rows into protocol_name -> state.
|
||||
func parseBGPProtocolStates(output string) map[string]string {
|
||||
out := make(map[string]string)
|
||||
for _, raw := range strings.Split(output, "\n") {
|
||||
line := strings.TrimSpace(raw)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
low := strings.ToLower(line)
|
||||
if strings.HasPrefix(low, "bird ") || strings.HasPrefix(low, "name ") || strings.HasPrefix(low, "table ") {
|
||||
continue
|
||||
}
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) < 4 {
|
||||
continue
|
||||
}
|
||||
if !strings.EqualFold(fields[1], "BGP") {
|
||||
continue
|
||||
}
|
||||
state := extractBGPSessionState(line)
|
||||
if state == "" {
|
||||
state = fields[3]
|
||||
}
|
||||
out[fields[0]] = state
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func extractBGPSessionState(line string) string {
|
||||
known := []string{
|
||||
"Established",
|
||||
"Idle",
|
||||
"Connect",
|
||||
"Active",
|
||||
"OpenSent",
|
||||
"OpenConfirm",
|
||||
}
|
||||
for _, st := range known {
|
||||
if strings.Contains(line, st) {
|
||||
return st
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// peerProtocolNameForID forwards to birdfmt for tests and legacy callers.
|
||||
func peerProtocolNameForID(peerID string) string {
|
||||
return birdfmt.PeerProtocolName(peerID)
|
||||
}
|
||||
|
||||
func (s *Server) handleListSpeakers(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok {
|
||||
@@ -219,9 +385,22 @@ func (s *Server) handleListSpeakers(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
speakers := s.store.ListSpeakersForTenant(a.TenantID)
|
||||
fresh := r != nil && strings.EqualFold(strings.TrimSpace(r.URL.Query().Get("live")), "1")
|
||||
var liveByID map[string]map[string]any
|
||||
if fresh {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second)
|
||||
defer cancel()
|
||||
liveByID = s.collectSpeakerLiveStatus(ctx, a.TenantID, true, speakers)
|
||||
}
|
||||
items := make([]map[string]any, 0, len(speakers))
|
||||
for _, sp := range speakers {
|
||||
items = append(items, speakerJSON(sp))
|
||||
row := speakerJSONFromStore(s.store, sp)
|
||||
if liveByID != nil {
|
||||
if live, ok := liveByID[sp.ID]; ok {
|
||||
row["live"] = live
|
||||
}
|
||||
}
|
||||
items = append(items, row)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"items": items, "next_cursor": nil, "has_more": false,
|
||||
@@ -244,11 +423,7 @@ func (s *Server) handleModuleRefresh(w http.ResponseWriter, r *http.Request) {
|
||||
writeProblem(w, http.StatusNotFound, "Not Found", "module not found")
|
||||
return
|
||||
}
|
||||
writeProblem(w, http.StatusInternalServerError, "Internal Error", err.Error())
|
||||
return
|
||||
}
|
||||
if mod.Type == "IP_RANGES" {
|
||||
writeNoContent(w)
|
||||
writeInternalError(w, "internal", err)
|
||||
return
|
||||
}
|
||||
idem := r.Header.Get("Idempotency-Key")
|
||||
@@ -260,7 +435,7 @@ func (s *Server) handleModuleRefresh(w http.ResponseWriter, r *http.Request) {
|
||||
mid := mod.ID
|
||||
j, _, err := s.jobs.Enqueue(a.TenantID, jobs.KindModuleRefresh, idemPtr, &mid, map[string]any{"module_id": moduleID})
|
||||
if err != nil {
|
||||
writeProblem(w, http.StatusInternalServerError, "Internal Error", err.Error())
|
||||
writeInternalError(w, "internal", err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Location", "/v1/jobs/"+j.ID)
|
||||
@@ -268,6 +443,60 @@ func (s *Server) handleModuleRefresh(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"job_id": snap["job_id"], "status": snap["status"]})
|
||||
}
|
||||
|
||||
func (s *Server) handleTenantRefresh(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok {
|
||||
writeProblem(w, http.StatusUnauthorized, "Unauthorized", "missing auth")
|
||||
return
|
||||
}
|
||||
if !s.requireAtLeast(w, a, "editor") {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
ModuleIDs []string `json:"module_ids"`
|
||||
}
|
||||
if r.Body != nil && r.ContentLength != 0 {
|
||||
if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&body); err != nil && err != io.EOF {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid JSON body")
|
||||
return
|
||||
}
|
||||
}
|
||||
moduleIDs := body.ModuleIDs
|
||||
if len(moduleIDs) == 0 {
|
||||
now := time.Now().UTC()
|
||||
for _, mod := range s.store.ListModules(a.TenantID) {
|
||||
if pipeline.ModuleDueForScheduler(mod, now) {
|
||||
moduleIDs = append(moduleIDs, mod.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(moduleIDs) == 0 {
|
||||
writeJSON(w, http.StatusNoContent, map[string]any{"message": "no modules due for refresh"})
|
||||
return
|
||||
}
|
||||
idem := strings.TrimSpace(r.Header.Get("Idempotency-Key"))
|
||||
var idemPtr *string
|
||||
if idem != "" {
|
||||
idemPtr = &idem
|
||||
}
|
||||
j, _, err := s.jobs.Enqueue(a.TenantID, jobs.KindTenantRefresh, idemPtr, nil, map[string]any{
|
||||
"module_ids": moduleIDs,
|
||||
"trigger": "api",
|
||||
})
|
||||
if err != nil {
|
||||
writeInternalError(w, "internal", err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Location", "/v1/jobs/"+j.ID)
|
||||
snap := j.Snapshot()
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{
|
||||
"job_id": snap["job_id"],
|
||||
"status": snap["status"],
|
||||
"module_ids": moduleIDs,
|
||||
"modules_due": len(moduleIDs),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleListRevisions(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok {
|
||||
@@ -313,11 +542,32 @@ func revisionJSON(rev *store.Revision) map[string]any {
|
||||
return m
|
||||
}
|
||||
|
||||
func strPtrOrNull(s string) any {
|
||||
if s == "" {
|
||||
return nil
|
||||
// enqueueModuleRefreshIfEnabled queues module_refresh when the module exists and is enabled (best-effort, no HTTP error).
|
||||
func (s *Server) enqueueModuleRefreshIfEnabled(tenantID, moduleID, trigger string) {
|
||||
if s.jobs == nil {
|
||||
return
|
||||
}
|
||||
return s
|
||||
mod, err := s.store.GetModule(tenantID, moduleID)
|
||||
if err != nil || !mod.Enabled {
|
||||
return
|
||||
}
|
||||
mid := moduleID
|
||||
key := "module_refresh:" + moduleID
|
||||
_, _, _ = s.jobs.Enqueue(tenantID, jobs.KindModuleRefresh, &key, &mid, map[string]any{
|
||||
"module_id": moduleID,
|
||||
"trigger": trigger,
|
||||
})
|
||||
}
|
||||
|
||||
// enqueuePeerReconcile queues fast peer-only reconcile/render (best-effort, no HTTP error).
|
||||
func (s *Server) enqueuePeerReconcile(tenantID, trigger string) {
|
||||
if s.jobs == nil {
|
||||
return
|
||||
}
|
||||
_, _, _ = s.jobs.Enqueue(tenantID, jobs.KindPeerReconcile, nil, nil, map[string]any{
|
||||
"trigger": trigger,
|
||||
"job_title": "Обновление BGP пиров",
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleGetRevision(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -370,9 +620,38 @@ func (s *Server) handleRevisionPreview(w http.ResponseWriter, r *http.Request) {
|
||||
for k, v := range rev.PreviewFragments {
|
||||
obj[k] = v
|
||||
}
|
||||
if expanded := pipeline.BuildExpandedBirdPreview(rev.PreviewFragments); expanded != "" {
|
||||
obj[pipeline.AuxBirdFullExpandedKey()] = expanded
|
||||
}
|
||||
writeJSON(w, http.StatusOK, obj)
|
||||
}
|
||||
|
||||
func (s *Server) handleRevisionDiagnosticLog(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok {
|
||||
writeProblem(w, http.StatusUnauthorized, "Unauthorized", "missing auth")
|
||||
return
|
||||
}
|
||||
if !s.requireAtLeast(w, a, "viewer") {
|
||||
return
|
||||
}
|
||||
revID := r.PathValue("revision_id")
|
||||
rev, err := s.store.GetRevision(a.TenantID, revID)
|
||||
if err != nil {
|
||||
writeProblem(w, http.StatusNotFound, "Not Found", "revision not found")
|
||||
return
|
||||
}
|
||||
logOut, err := reports.BuildRevisionDiagnosticLog(s.store, a.TenantID, rev)
|
||||
if err != nil {
|
||||
writeInternalError(w, "revision diagnostic log", err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="`+logOut.Filename+`"`)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(logOut.Body)
|
||||
}
|
||||
|
||||
func (s *Server) handleRevisionDiff(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok {
|
||||
@@ -396,7 +675,7 @@ func (s *Server) handleRevisionRollback(w http.ResponseWriter, r *http.Request)
|
||||
writeProblem(w, http.StatusUnauthorized, "Unauthorized", "missing auth")
|
||||
return
|
||||
}
|
||||
if !s.requireAtLeast(w, a, "editor") {
|
||||
if !s.requireAtLeast(w, a, "operator") {
|
||||
return
|
||||
}
|
||||
revID := r.PathValue("revision_id")
|
||||
@@ -413,7 +692,7 @@ func (s *Server) handleRevisionRollback(w http.ResponseWriter, r *http.Request)
|
||||
"source_revision_id": revID,
|
||||
})
|
||||
if err != nil {
|
||||
writeProblem(w, http.StatusInternalServerError, "Internal Error", err.Error())
|
||||
writeInternalError(w, "internal", err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Location", "/v1/jobs/"+j.ID)
|
||||
@@ -460,7 +739,7 @@ func (s *Server) handleApply(w http.ResponseWriter, r *http.Request) {
|
||||
"strategy": body.Strategy,
|
||||
})
|
||||
if err != nil {
|
||||
writeProblem(w, http.StatusInternalServerError, "Internal Error", err.Error())
|
||||
writeInternalError(w, "internal", err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Location", "/v1/jobs/"+j.ID)
|
||||
@@ -511,7 +790,7 @@ func (s *Server) handleSpeakerApply(w http.ResponseWriter, r *http.Request) {
|
||||
"speaker_id": spkID,
|
||||
})
|
||||
if err != nil {
|
||||
writeProblem(w, http.StatusInternalServerError, "Internal Error", err.Error())
|
||||
writeInternalError(w, "internal", err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Location", "/v1/jobs/"+j.ID)
|
||||
@@ -536,13 +815,28 @@ func (s *Server) handleBirdReload(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
j, _, err := s.jobs.Enqueue(a.TenantID, jobs.KindBirdReload, idemPtr, nil, nil)
|
||||
if err != nil {
|
||||
writeProblem(w, http.StatusInternalServerError, "Internal Error", err.Error())
|
||||
writeInternalError(w, "internal", err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Location", "/v1/jobs/"+j.ID)
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"job_id": j.ID, "status": "queued"})
|
||||
}
|
||||
|
||||
func (s *Server) handleBirdStatus(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok {
|
||||
writeProblem(w, http.StatusUnauthorized, "Unauthorized", "missing auth")
|
||||
return
|
||||
}
|
||||
if !s.requireAtLeast(w, a, "viewer") {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second)
|
||||
defer cancel()
|
||||
st := birdfmt.InspectLocalBird(ctx)
|
||||
writeJSON(w, http.StatusOK, st)
|
||||
}
|
||||
|
||||
func (s *Server) handleListJobs(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok {
|
||||
@@ -583,6 +877,44 @@ func (s *Server) handleGetJob(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, j.Snapshot())
|
||||
}
|
||||
|
||||
func (s *Server) handleGetJobReport(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok {
|
||||
writeProblem(w, http.StatusUnauthorized, "Unauthorized", "missing auth")
|
||||
return
|
||||
}
|
||||
if !s.requireAtLeast(w, a, "viewer") {
|
||||
return
|
||||
}
|
||||
j, err := s.jobs.Get(a.TenantID, r.PathValue("job_id"))
|
||||
if err != nil {
|
||||
writeProblem(w, http.StatusNotFound, "Not Found", "job not found")
|
||||
return
|
||||
}
|
||||
snap := j.Snapshot()
|
||||
meta, _ := snap["meta"].(map[string]any)
|
||||
out := map[string]any{
|
||||
"job_id": snap["job_id"],
|
||||
"kind": snap["kind"],
|
||||
"status": snap["status"],
|
||||
"meta": meta,
|
||||
"error": snap["error"],
|
||||
"created_at": snap["created_at"],
|
||||
}
|
||||
if meta != nil {
|
||||
if v, ok := meta["log_entries"]; ok {
|
||||
out["log_entries"] = v
|
||||
}
|
||||
if v, ok := meta["log_total"]; ok {
|
||||
out["log_total"] = v
|
||||
}
|
||||
if v, ok := meta["revision_id"]; ok {
|
||||
out["revision_id"] = v
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (s *Server) handleCancelJob(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok {
|
||||
@@ -654,9 +986,13 @@ func (s *Server) handleNodeBundle(w http.ResponseWriter, r *http.Request) {
|
||||
writeProblem(w, http.StatusNotFound, "Not Found", "revision not found")
|
||||
return
|
||||
}
|
||||
tgz, err := bundle.BuildGzippedTar(rid, sid, rev.PreviewFragments, s.bundlePriv)
|
||||
frags := rev.PreviewFragments
|
||||
if overlaid, err := pipeline.OverlayFragmentsForSpeaker(s.store, a.TenantID, sid, rid, frags); err == nil {
|
||||
frags = overlaid
|
||||
}
|
||||
tgz, err := bundle.BuildGzippedTar(rid, sid, frags, s.bundlePriv)
|
||||
if err != nil {
|
||||
writeProblem(w, http.StatusInternalServerError, "Internal Error", err.Error())
|
||||
writeInternalError(w, "internal", err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/gzip")
|
||||
@@ -706,7 +1042,7 @@ func (s *Server) handleNodeEnroll(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
patch := &store.SpeakerPatch{MetaJSON: &meta}
|
||||
if _, err := s.store.UpdateSpeaker(a.TenantID, sid, patch); err != nil {
|
||||
writeProblem(w, http.StatusInternalServerError, "Internal Error", err.Error())
|
||||
writeInternalError(w, "internal", err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"evobgp/internal/store"
|
||||
)
|
||||
|
||||
func (s *Server) registerAPIKeyRoutes(m *http.ServeMux) {
|
||||
m.HandleFunc("GET /auth/session", s.handleAuthSession)
|
||||
m.HandleFunc("GET /api-keys", s.handleListAPIKeys)
|
||||
m.HandleFunc("POST /api-keys", s.handlePostAPIKey)
|
||||
m.HandleFunc("GET /api-keys/{id}", s.handleGetAPIKey)
|
||||
m.HandleFunc("PATCH /api-keys/{id}", s.handlePatchAPIKey)
|
||||
m.HandleFunc("DELETE /api-keys/{id}", s.handleDeleteAPIKey)
|
||||
m.HandleFunc("POST /api-keys/{id}/rotate", s.handleRotateAPIKey)
|
||||
}
|
||||
|
||||
func (s *Server) handleAuthSession(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "viewer") {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"tenant_id": a.TenantID,
|
||||
"role": a.Role,
|
||||
})
|
||||
}
|
||||
|
||||
func apiKeyJSON(k *store.APIKey) map[string]any {
|
||||
m := map[string]any{
|
||||
"id": k.ID,
|
||||
"name": k.Name,
|
||||
"role": k.Role,
|
||||
"prefix": k.Prefix,
|
||||
"created_at": k.CreatedAt.UTC().Format(time.RFC3339),
|
||||
"updated_at": k.UpdatedAt.UTC().Format(time.RFC3339),
|
||||
}
|
||||
if k.ExpiresAt != nil {
|
||||
m["expires_at"] = k.ExpiresAt.UTC().Format(time.RFC3339)
|
||||
} else {
|
||||
m["expires_at"] = nil
|
||||
}
|
||||
if k.RevokedAt != nil {
|
||||
m["revoked_at"] = k.RevokedAt.UTC().Format(time.RFC3339)
|
||||
} else {
|
||||
m["revoked_at"] = nil
|
||||
}
|
||||
if k.LastUsedAt != nil {
|
||||
m["last_used_at"] = k.LastUsedAt.UTC().Format(time.RFC3339)
|
||||
} else {
|
||||
m["last_used_at"] = nil
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (s *Server) handleListAPIKeys(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "operator") {
|
||||
return
|
||||
}
|
||||
list, err := s.store.ListAPIKeys(a.TenantID)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
writePaginatedListJSON(w, r, list, func(k *store.APIKey) map[string]any {
|
||||
return apiKeyJSON(k)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleGetAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "operator") {
|
||||
return
|
||||
}
|
||||
k, err := s.store.GetAPIKey(a.TenantID, r.PathValue("id"))
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, apiKeyJSON(k))
|
||||
}
|
||||
|
||||
func (s *Server) handlePostAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "operator") {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Name string `json:"name"`
|
||||
Role string `json:"role"`
|
||||
ExpiresAt *string `json:"expires_at"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid json")
|
||||
return
|
||||
}
|
||||
in := &store.APIKeyCreate{
|
||||
Name: strings.TrimSpace(body.Name),
|
||||
Role: strings.TrimSpace(body.Role),
|
||||
}
|
||||
if body.ExpiresAt != nil && strings.TrimSpace(*body.ExpiresAt) != "" {
|
||||
t, err := time.Parse(time.RFC3339, strings.TrimSpace(*body.ExpiresAt))
|
||||
if err != nil {
|
||||
writeProblem(w, http.StatusUnprocessableEntity, "Unprocessable Entity", "invalid expires_at")
|
||||
return
|
||||
}
|
||||
in.ExpiresAt = &t
|
||||
}
|
||||
created, err := s.store.CreateAPIKey(a.TenantID, in)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
if err := s.keyResolver.Reload(s.store); err != nil {
|
||||
writeProblem(w, http.StatusInternalServerError, "Internal Server Error", "failed to reload api keys")
|
||||
return
|
||||
}
|
||||
out := apiKeyJSON(&created.APIKey)
|
||||
out["token"] = created.Token
|
||||
writeJSON(w, http.StatusCreated, out)
|
||||
}
|
||||
|
||||
func (s *Server) handlePatchAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "operator") {
|
||||
return
|
||||
}
|
||||
var raw map[string]json.RawMessage
|
||||
if err := json.NewDecoder(r.Body).Decode(&raw); err != nil {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid json")
|
||||
return
|
||||
}
|
||||
patch := &store.APIKeyPatch{}
|
||||
if v, ok := raw["name"]; ok {
|
||||
var name string
|
||||
if err := json.Unmarshal(v, &name); err != nil {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid name")
|
||||
return
|
||||
}
|
||||
patch.Name = &name
|
||||
}
|
||||
if v, ok := raw["role"]; ok {
|
||||
var role string
|
||||
if err := json.Unmarshal(v, &role); err != nil {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid role")
|
||||
return
|
||||
}
|
||||
patch.Role = &role
|
||||
}
|
||||
if v, ok := raw["expires_at"]; ok {
|
||||
if string(v) == "null" {
|
||||
patch.ClearExpiresAt = true
|
||||
} else {
|
||||
var s string
|
||||
if err := json.Unmarshal(v, &s); err != nil {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid expires_at")
|
||||
return
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339, strings.TrimSpace(s))
|
||||
if err != nil {
|
||||
writeProblem(w, http.StatusUnprocessableEntity, "Unprocessable Entity", "invalid expires_at")
|
||||
return
|
||||
}
|
||||
patch.ExpiresAt = &t
|
||||
}
|
||||
}
|
||||
k, err := s.store.UpdateAPIKey(a.TenantID, r.PathValue("id"), patch)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
if err := s.keyResolver.Reload(s.store); err != nil {
|
||||
writeProblem(w, http.StatusInternalServerError, "Internal Server Error", "failed to reload api keys")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, apiKeyJSON(k))
|
||||
}
|
||||
|
||||
func (s *Server) handleDeleteAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "operator") {
|
||||
return
|
||||
}
|
||||
if err := s.store.RevokeAPIKey(a.TenantID, r.PathValue("id")); err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
if err := s.keyResolver.Reload(s.store); err != nil {
|
||||
writeProblem(w, http.StatusInternalServerError, "Internal Server Error", "failed to reload api keys")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) handleRotateAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "operator") {
|
||||
return
|
||||
}
|
||||
rotated, err := s.store.RotateAPIKey(a.TenantID, r.PathValue("id"))
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
if err := s.keyResolver.Reload(s.store); err != nil {
|
||||
writeProblem(w, http.StatusInternalServerError, "Internal Server Error", "failed to reload api keys")
|
||||
return
|
||||
}
|
||||
out := apiKeyJSON(&rotated.APIKey)
|
||||
out["token"] = rotated.Token
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBearerDevWithoutInsecureDev(t *testing.T) {
|
||||
srv, err := New(Options{SeedDemo: true, BundleSeedHex: testBundleSeed})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer srv.Close()
|
||||
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
defer ts.Close()
|
||||
|
||||
req, _ := http.NewRequest(http.MethodGet, ts.URL+"/v1/modules?limit=1", nil)
|
||||
req.Header.Set("Authorization", "Bearer dev")
|
||||
resp, err := ts.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("status=%d body=%s", resp.StatusCode, b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIKeysCRUDAndAuth(t *testing.T) {
|
||||
srv, err := New(Options{SeedDemo: true, BundleSeedHex: testBundleSeed})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer srv.Close()
|
||||
tenant, _, _, _, _ := srv.Store().DemoIDs()
|
||||
mustSetTestAPIKeys(t, srv, "opkey|"+tenant+"|operator")
|
||||
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
defer ts.Close()
|
||||
client := ts.Client()
|
||||
base := ts.URL
|
||||
|
||||
reqCreate, _ := http.NewRequest(http.MethodPost, base+"/v1/api-keys", strings.NewReader(`{"name":"ci","role":"editor"}`))
|
||||
reqCreate.Header.Set("Authorization", "Bearer opkey")
|
||||
reqCreate.Header.Set("Content-Type", "application/json")
|
||||
respCreate, err := client.Do(reqCreate)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = respCreate.Body.Close() }()
|
||||
if respCreate.StatusCode != http.StatusCreated {
|
||||
b, _ := io.ReadAll(respCreate.Body)
|
||||
t.Fatalf("create status=%d body=%s", respCreate.StatusCode, b)
|
||||
}
|
||||
var created map[string]any
|
||||
if err := json.NewDecoder(respCreate.Body).Decode(&created); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, _ := created["token"].(string)
|
||||
if token == "" {
|
||||
t.Fatal("missing token in create response")
|
||||
}
|
||||
id, _ := created["id"].(string)
|
||||
if id == "" {
|
||||
t.Fatal("missing id")
|
||||
}
|
||||
|
||||
reqMod, _ := http.NewRequest(http.MethodGet, base+"/v1/modules?limit=1", nil)
|
||||
reqMod.Header.Set("Authorization", "Bearer "+token)
|
||||
respMod, err := client.Do(reqMod)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = respMod.Body.Close() }()
|
||||
if respMod.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(respMod.Body)
|
||||
t.Fatalf("modules status=%d body=%s", respMod.StatusCode, b)
|
||||
}
|
||||
|
||||
reqDel, _ := http.NewRequest(http.MethodDelete, base+"/v1/api-keys/"+id, nil)
|
||||
reqDel.Header.Set("Authorization", "Bearer opkey")
|
||||
respDel, err := client.Do(reqDel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = respDel.Body.Close() }()
|
||||
if respDel.StatusCode != http.StatusNoContent {
|
||||
t.Fatalf("delete status=%d", respDel.StatusCode)
|
||||
}
|
||||
|
||||
reqAfter, _ := http.NewRequest(http.MethodGet, base+"/v1/modules?limit=1", nil)
|
||||
reqAfter.Header.Set("Authorization", "Bearer "+token)
|
||||
respAfter, err := client.Do(reqAfter)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = respAfter.Body.Close() }()
|
||||
if respAfter.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401 after revoke, got %d", respAfter.StatusCode)
|
||||
}
|
||||
|
||||
mustSetTestAPIKeys(t, srv, "nodekey|"+tenant+"|node,opkey|"+tenant+"|operator")
|
||||
reqNode2, _ := http.NewRequest(http.MethodGet, base+"/v1/api-keys", nil)
|
||||
reqNode2.Header.Set("Authorization", "Bearer nodekey")
|
||||
respNode, err := client.Do(reqNode2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = respNode.Body.Close() }()
|
||||
if respNode.StatusCode != http.StatusForbidden {
|
||||
t.Fatalf("node list api-keys status=%d want 403", respNode.StatusCode)
|
||||
}
|
||||
}
|
||||
+394
-60
@@ -1,10 +1,19 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"evobgp/internal/importer"
|
||||
"evobgp/internal/pipeline"
|
||||
"evobgp/internal/store"
|
||||
)
|
||||
|
||||
@@ -15,6 +24,7 @@ func (s *Server) registerCRUDRoutes(m *http.ServeMux) {
|
||||
|
||||
m.HandleFunc("GET /modules/{module_id}/cdn-sources", s.handleListCDNSources)
|
||||
m.HandleFunc("POST /modules/{module_id}/cdn-sources", s.handlePostCDNSource)
|
||||
m.HandleFunc("POST /modules/{module_id}/cdn-sources/preview", s.handlePreviewCDNSource)
|
||||
m.HandleFunc("PATCH /modules/{module_id}/cdn-sources/{source_id}", s.handlePatchCDNSource)
|
||||
m.HandleFunc("DELETE /modules/{module_id}/cdn-sources/{source_id}", s.handleDeleteCDNSource)
|
||||
|
||||
@@ -32,6 +42,8 @@ func (s *Server) registerCRUDRoutes(m *http.ServeMux) {
|
||||
m.HandleFunc("POST /modules/{module_id}/ip-range-entries", s.handlePostIPRange)
|
||||
m.HandleFunc("PATCH /modules/{module_id}/ip-range-entries/{entry_id}", s.handlePatchIPRange)
|
||||
m.HandleFunc("DELETE /modules/{module_id}/ip-range-entries/{entry_id}", s.handleDeleteIPRange)
|
||||
m.HandleFunc("GET /modules/{module_id}/entries.csv", s.handleExportModuleEntriesCSV)
|
||||
m.HandleFunc("POST /modules/{module_id}/entries.csv", s.handleImportModuleEntriesCSV)
|
||||
|
||||
m.HandleFunc("GET /doh-profiles", s.handleListDoh)
|
||||
m.HandleFunc("POST /doh-profiles", s.handlePostDoh)
|
||||
@@ -53,11 +65,14 @@ func (s *Server) registerCRUDRoutes(m *http.ServeMux) {
|
||||
m.HandleFunc("POST /speakers", s.handlePostSpeaker)
|
||||
m.HandleFunc("GET /speakers/{speaker_id}", s.handleGetSpeakerByID)
|
||||
m.HandleFunc("PATCH /speakers/{speaker_id}", s.handlePatchSpeaker)
|
||||
m.HandleFunc("DELETE /speakers/{speaker_id}", s.handleDeleteSpeaker)
|
||||
|
||||
m.HandleFunc("GET /revisions/{revision_id}/prefixes", s.handleRevisionPrefixes)
|
||||
|
||||
m.HandleFunc("GET /settings", s.handleGetSettings)
|
||||
m.HandleFunc("PATCH /settings", s.handlePatchSettings)
|
||||
|
||||
s.registerAPIKeyRoutes(m)
|
||||
}
|
||||
|
||||
func (s *Server) handlePostModule(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -66,14 +81,16 @@ func (s *Server) handlePostModule(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Priority int `json:"priority"`
|
||||
RefreshIntervalSec int `json:"refresh_interval_sec"`
|
||||
CronExpr string `json:"cron_expr"`
|
||||
DefaultCommunityID *string `json:"default_community_id"`
|
||||
DohProfileID *string `json:"doh_profile_id"`
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Priority int `json:"priority"`
|
||||
RefreshIntervalSec int `json:"refresh_interval_sec"`
|
||||
CronExpr string `json:"cron_expr"`
|
||||
DefaultCommunityID *string `json:"default_community_id"`
|
||||
DohProfileID *string `json:"doh_profile_id"`
|
||||
DohProfileIDs []string `json:"doh_profile_ids"`
|
||||
DohResolverPolicy string `json:"doh_resolver_policy"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid json")
|
||||
@@ -83,6 +100,7 @@ func (s *Server) handlePostModule(w http.ResponseWriter, r *http.Request) {
|
||||
Type: body.Type, Name: body.Name, Enabled: body.Enabled, Priority: body.Priority,
|
||||
RefreshIntervalSec: body.RefreshIntervalSec, CronExpr: body.CronExpr,
|
||||
DefaultCommunityID: body.DefaultCommunityID, DohProfileID: body.DohProfileID,
|
||||
DohProfileIDs: body.DohProfileIDs, DohResolverPolicy: body.DohResolverPolicy,
|
||||
})
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
@@ -96,11 +114,47 @@ func (s *Server) handlePatchModule(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok || !s.requireAtLeast(w, a, "editor") {
|
||||
return
|
||||
}
|
||||
rawBody, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid body")
|
||||
return
|
||||
}
|
||||
var body store.ModulePatch
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
if err := json.Unmarshal(rawBody, &body); err != nil {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid json")
|
||||
return
|
||||
}
|
||||
// NOTE:
|
||||
// In Go, unmarshalling JSON `null` into pointer fields results in nil,
|
||||
// which is indistinguishable from "field omitted". For PATCH we need to
|
||||
// distinguish these cases so clients can explicitly clear nullable fields.
|
||||
var raw map[string]json.RawMessage
|
||||
if err := json.Unmarshal(rawBody, &raw); err == nil {
|
||||
if v, ok := raw["default_community_id"]; ok && string(v) == "null" {
|
||||
empty := ""
|
||||
body.DefaultCommunityID = &empty
|
||||
}
|
||||
if v, ok := raw["doh_profile_id"]; ok && string(v) == "null" {
|
||||
empty := ""
|
||||
body.DohProfileID = &empty
|
||||
}
|
||||
if v, ok := raw["doh_profile_ids"]; ok && string(v) == "null" {
|
||||
empty := []string{}
|
||||
body.DohProfileIDs = &empty
|
||||
}
|
||||
if v, ok := raw["doh_resolver_policy"]; ok && string(v) == "null" {
|
||||
p := store.DohPolicyPrimaryOnly
|
||||
body.DohResolverPolicy = &p
|
||||
}
|
||||
if v, ok := raw["cron_expr"]; ok && string(v) == "null" {
|
||||
empty := ""
|
||||
body.CronExpr = &empty
|
||||
}
|
||||
if v, ok := raw["refresh_interval_sec"]; ok && string(v) == "null" {
|
||||
zero := 0
|
||||
body.RefreshIntervalSec = &zero
|
||||
}
|
||||
}
|
||||
mod, err := s.store.UpdateModule(a.TenantID, r.PathValue("module_id"), &body)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
@@ -122,15 +176,18 @@ func (s *Server) handleDeleteModule(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func writeStoreErr(w http.ResponseWriter, err error) {
|
||||
if err != nil {
|
||||
log.Printf("httpapi: store: %v", err)
|
||||
}
|
||||
if err == store.ErrNotFound || err == store.ErrTenantScope {
|
||||
writeProblem(w, http.StatusNotFound, "Not Found", err.Error())
|
||||
writeProblem(w, http.StatusNotFound, "Not Found", notFoundDetail)
|
||||
return
|
||||
}
|
||||
if err == store.ErrInvalidInput {
|
||||
writeProblem(w, http.StatusUnprocessableEntity, "Unprocessable Entity", err.Error())
|
||||
writeProblem(w, http.StatusUnprocessableEntity, "Unprocessable Entity", invalidInputDetail)
|
||||
return
|
||||
}
|
||||
writeProblem(w, http.StatusInternalServerError, "Internal Error", err.Error())
|
||||
writeInternalError(w, "store", err)
|
||||
}
|
||||
|
||||
func (s *Server) handleListCDNSources(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -143,15 +200,11 @@ func (s *Server) handleListCDNSources(w http.ResponseWriter, r *http.Request) {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
items := make([]map[string]any, 0, len(list))
|
||||
for _, x := range list {
|
||||
items = append(items, cdnSourceJSON(x))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": items, "next_cursor": nil, "has_more": false})
|
||||
writePaginatedListJSON(w, r, list, cdnSourceJSON)
|
||||
}
|
||||
|
||||
func cdnSourceJSON(x *store.CDNSource) map[string]any {
|
||||
m := map[string]any{"id": x.ID, "source_kind": x.SourceKind, "url": x.URL, "etag": x.Etag}
|
||||
m := map[string]any{"id": x.ID, "source_kind": x.SourceKind, "url": x.URL, "prefix_path": x.PrefixPath, "etag": x.Etag}
|
||||
if x.RefreshIntervalSec != nil {
|
||||
m["refresh_interval_sec"] = *x.RefreshIntervalSec
|
||||
} else {
|
||||
@@ -162,9 +215,85 @@ func cdnSourceJSON(x *store.CDNSource) map[string]any {
|
||||
} else {
|
||||
m["community_id"] = nil
|
||||
}
|
||||
if x.LastRefreshedAt != nil {
|
||||
m["last_refreshed_at"] = x.LastRefreshedAt.UTC().Format(time.RFC3339Nano)
|
||||
} else {
|
||||
m["last_refreshed_at"] = nil
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (s *Server) handlePreviewCDNSource(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "editor") {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
URL string `json:"url"`
|
||||
SourceKind string `json:"source_kind"`
|
||||
PrefixPath string `json:"prefix_path"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid json")
|
||||
return
|
||||
}
|
||||
u := strings.TrimSpace(body.URL)
|
||||
if u == "" {
|
||||
writeProblem(w, http.StatusUnprocessableEntity, "Unprocessable Entity", "url is required")
|
||||
return
|
||||
}
|
||||
mod, err := s.store.GetModule(a.TenantID, r.PathValue("module_id"))
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
if mod.Type != "CDN_CIDRS" {
|
||||
writeProblem(w, http.StatusUnprocessableEntity, "Unprocessable Entity", "module type must be CDN_CIDRS")
|
||||
return
|
||||
}
|
||||
req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
writeProblem(w, http.StatusUnprocessableEntity, "Unprocessable Entity", "invalid url")
|
||||
return
|
||||
}
|
||||
resp, err := s.cdnHTTP.Do(req)
|
||||
if err != nil {
|
||||
writeBadGateway(w, "cdn preview fetch", err)
|
||||
return
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
writeBadGateway(w, "cdn preview fetch", fmt.Errorf("upstream status: %s", resp.Status))
|
||||
return
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
|
||||
if err != nil {
|
||||
writeBadGateway(w, "cdn preview read body", err)
|
||||
return
|
||||
}
|
||||
pfxs, err := pipeline.ExtractCIDRs(string(raw), body.SourceKind, body.PrefixPath)
|
||||
if err != nil {
|
||||
log.Printf("httpapi: cdn preview extract: %v", err)
|
||||
writeProblem(w, http.StatusUnprocessableEntity, "Unprocessable Entity", cdnExtractDetail)
|
||||
return
|
||||
}
|
||||
items := make([]string, 0, len(pfxs))
|
||||
const previewLimit = 100
|
||||
for i, p := range pfxs {
|
||||
if i >= previewLimit {
|
||||
break
|
||||
}
|
||||
items = append(items, p.String())
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"items": items,
|
||||
"total": len(pfxs),
|
||||
"truncated": len(pfxs) > previewLimit,
|
||||
"source_url": u,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handlePostCDNSource(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "editor") {
|
||||
@@ -175,11 +304,13 @@ func (s *Server) handlePostCDNSource(w http.ResponseWriter, r *http.Request) {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid json")
|
||||
return
|
||||
}
|
||||
x, err := s.store.CreateCDNSource(a.TenantID, r.PathValue("module_id"), &body)
|
||||
mid := r.PathValue("module_id")
|
||||
x, err := s.store.CreateCDNSource(a.TenantID, mid, &body)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
s.enqueueModuleRefreshIfEnabled(a.TenantID, mid, "cdn_source_create")
|
||||
writeJSON(w, http.StatusCreated, cdnSourceJSON(x))
|
||||
}
|
||||
|
||||
@@ -193,11 +324,13 @@ func (s *Server) handlePatchCDNSource(w http.ResponseWriter, r *http.Request) {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid json")
|
||||
return
|
||||
}
|
||||
x, err := s.store.UpdateCDNSource(a.TenantID, r.PathValue("module_id"), r.PathValue("source_id"), &body)
|
||||
mid := r.PathValue("module_id")
|
||||
x, err := s.store.UpdateCDNSource(a.TenantID, mid, r.PathValue("source_id"), &body)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
s.enqueueModuleRefreshIfEnabled(a.TenantID, mid, "cdn_source_patch")
|
||||
writeJSON(w, http.StatusOK, cdnSourceJSON(x))
|
||||
}
|
||||
|
||||
@@ -206,10 +339,12 @@ func (s *Server) handleDeleteCDNSource(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok || !s.requireAtLeast(w, a, "editor") {
|
||||
return
|
||||
}
|
||||
if err := s.store.DeleteCDNSource(a.TenantID, r.PathValue("module_id"), r.PathValue("source_id")); err != nil {
|
||||
mid := r.PathValue("module_id")
|
||||
if err := s.store.DeleteCDNSource(a.TenantID, mid, r.PathValue("source_id")); err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
s.enqueueModuleRefreshIfEnabled(a.TenantID, mid, "cdn_source_delete")
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
@@ -223,30 +358,31 @@ func (s *Server) handleListAS(w http.ResponseWriter, r *http.Request) {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
items := make([]map[string]any, 0, len(list))
|
||||
for _, x := range list {
|
||||
items = append(items, asEntryJSON(x))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
||||
writePaginatedListJSON(w, r, list, asEntryJSON)
|
||||
}
|
||||
|
||||
func asEntryJSON(x *store.ASEntry) map[string]any {
|
||||
m := map[string]any{"id": x.ID}
|
||||
if x.ASN != nil {
|
||||
m["asn"] = *x.ASN
|
||||
} else {
|
||||
m["asn"] = nil
|
||||
}
|
||||
if x.Prefix != nil {
|
||||
m["prefix"] = *x.Prefix
|
||||
} else {
|
||||
m["prefix"] = nil
|
||||
}
|
||||
m := map[string]any{"id": x.ID, "asn": x.ASN}
|
||||
if x.CommunityID != nil {
|
||||
m["community_id"] = *x.CommunityID
|
||||
} else {
|
||||
m["community_id"] = nil
|
||||
}
|
||||
if strings.TrimSpace(x.ASNName) != "" {
|
||||
m["asn_name"] = strings.TrimSpace(x.ASNName)
|
||||
} else {
|
||||
m["asn_name"] = nil
|
||||
}
|
||||
if x.PrefixCount != nil {
|
||||
m["prefix_count"] = *x.PrefixCount
|
||||
} else {
|
||||
m["prefix_count"] = nil
|
||||
}
|
||||
if x.ASNResolvedAt != nil {
|
||||
m["asn_resolved_at"] = x.ASNResolvedAt.UTC().Format(time.RFC3339Nano)
|
||||
} else {
|
||||
m["asn_resolved_at"] = nil
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
@@ -260,11 +396,13 @@ func (s *Server) handlePostAS(w http.ResponseWriter, r *http.Request) {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid json")
|
||||
return
|
||||
}
|
||||
x, err := s.store.CreateASEntry(a.TenantID, r.PathValue("module_id"), &body)
|
||||
mid := r.PathValue("module_id")
|
||||
x, err := s.store.CreateASEntry(a.TenantID, mid, &body)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
s.enqueueModuleRefreshIfEnabled(a.TenantID, mid, "as_entry_create")
|
||||
writeJSON(w, http.StatusCreated, asEntryJSON(x))
|
||||
}
|
||||
|
||||
@@ -278,11 +416,13 @@ func (s *Server) handlePatchAS(w http.ResponseWriter, r *http.Request) {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid json")
|
||||
return
|
||||
}
|
||||
x, err := s.store.UpdateASEntry(a.TenantID, r.PathValue("module_id"), r.PathValue("entry_id"), &body)
|
||||
mid := r.PathValue("module_id")
|
||||
x, err := s.store.UpdateASEntry(a.TenantID, mid, r.PathValue("entry_id"), &body)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
s.enqueueModuleRefreshIfEnabled(a.TenantID, mid, "as_entry_patch")
|
||||
writeJSON(w, http.StatusOK, asEntryJSON(x))
|
||||
}
|
||||
|
||||
@@ -291,10 +431,12 @@ func (s *Server) handleDeleteAS(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok || !s.requireAtLeast(w, a, "editor") {
|
||||
return
|
||||
}
|
||||
if err := s.store.DeleteASEntry(a.TenantID, r.PathValue("module_id"), r.PathValue("entry_id")); err != nil {
|
||||
mid := r.PathValue("module_id")
|
||||
if err := s.store.DeleteASEntry(a.TenantID, mid, r.PathValue("entry_id")); err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
s.enqueueModuleRefreshIfEnabled(a.TenantID, mid, "as_entry_delete")
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
@@ -308,11 +450,7 @@ func (s *Server) handleListDomain(w http.ResponseWriter, r *http.Request) {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
items := make([]map[string]any, 0, len(list))
|
||||
for _, x := range list {
|
||||
items = append(items, domainEntryJSON(x))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
||||
writePaginatedListJSON(w, r, list, domainEntryJSON)
|
||||
}
|
||||
|
||||
func domainEntryJSON(x *store.DomainEntry) map[string]any {
|
||||
@@ -335,11 +473,13 @@ func (s *Server) handlePostDomain(w http.ResponseWriter, r *http.Request) {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid json")
|
||||
return
|
||||
}
|
||||
x, err := s.store.CreateDomainEntry(a.TenantID, r.PathValue("module_id"), &body)
|
||||
mid := r.PathValue("module_id")
|
||||
x, err := s.store.CreateDomainEntry(a.TenantID, mid, &body)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
s.enqueueModuleRefreshIfEnabled(a.TenantID, mid, "domain_entry_create")
|
||||
writeJSON(w, http.StatusCreated, domainEntryJSON(x))
|
||||
}
|
||||
|
||||
@@ -353,11 +493,13 @@ func (s *Server) handlePatchDomain(w http.ResponseWriter, r *http.Request) {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid json")
|
||||
return
|
||||
}
|
||||
x, err := s.store.UpdateDomainEntry(a.TenantID, r.PathValue("module_id"), r.PathValue("entry_id"), &body)
|
||||
mid := r.PathValue("module_id")
|
||||
x, err := s.store.UpdateDomainEntry(a.TenantID, mid, r.PathValue("entry_id"), &body)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
s.enqueueModuleRefreshIfEnabled(a.TenantID, mid, "domain_entry_patch")
|
||||
writeJSON(w, http.StatusOK, domainEntryJSON(x))
|
||||
}
|
||||
|
||||
@@ -366,10 +508,12 @@ func (s *Server) handleDeleteDomain(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok || !s.requireAtLeast(w, a, "editor") {
|
||||
return
|
||||
}
|
||||
if err := s.store.DeleteDomainEntry(a.TenantID, r.PathValue("module_id"), r.PathValue("entry_id")); err != nil {
|
||||
mid := r.PathValue("module_id")
|
||||
if err := s.store.DeleteDomainEntry(a.TenantID, mid, r.PathValue("entry_id")); err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
s.enqueueModuleRefreshIfEnabled(a.TenantID, mid, "domain_entry_delete")
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
@@ -383,11 +527,7 @@ func (s *Server) handleListIPRange(w http.ResponseWriter, r *http.Request) {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
items := make([]map[string]any, 0, len(list))
|
||||
for _, x := range list {
|
||||
items = append(items, ipRangeJSON(x))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
||||
writePaginatedListJSON(w, r, list, ipRangeJSON)
|
||||
}
|
||||
|
||||
func ipRangeJSON(x *store.IPRangeEntry) map[string]any {
|
||||
@@ -410,11 +550,13 @@ func (s *Server) handlePostIPRange(w http.ResponseWriter, r *http.Request) {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid json")
|
||||
return
|
||||
}
|
||||
x, err := s.store.CreateIPRangeEntry(a.TenantID, r.PathValue("module_id"), &body)
|
||||
mid := r.PathValue("module_id")
|
||||
x, err := s.store.CreateIPRangeEntry(a.TenantID, mid, &body)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
s.enqueueModuleRefreshIfEnabled(a.TenantID, mid, "ip_range_create")
|
||||
writeJSON(w, http.StatusCreated, ipRangeJSON(x))
|
||||
}
|
||||
|
||||
@@ -428,11 +570,13 @@ func (s *Server) handlePatchIPRange(w http.ResponseWriter, r *http.Request) {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid json")
|
||||
return
|
||||
}
|
||||
x, err := s.store.UpdateIPRangeEntry(a.TenantID, r.PathValue("module_id"), r.PathValue("entry_id"), &body)
|
||||
mid := r.PathValue("module_id")
|
||||
x, err := s.store.UpdateIPRangeEntry(a.TenantID, mid, r.PathValue("entry_id"), &body)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
s.enqueueModuleRefreshIfEnabled(a.TenantID, mid, "ip_range_patch")
|
||||
writeJSON(w, http.StatusOK, ipRangeJSON(x))
|
||||
}
|
||||
|
||||
@@ -441,13 +585,142 @@ func (s *Server) handleDeleteIPRange(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok || !s.requireAtLeast(w, a, "editor") {
|
||||
return
|
||||
}
|
||||
if err := s.store.DeleteIPRangeEntry(a.TenantID, r.PathValue("module_id"), r.PathValue("entry_id")); err != nil {
|
||||
mid := r.PathValue("module_id")
|
||||
if err := s.store.DeleteIPRangeEntry(a.TenantID, mid, r.PathValue("entry_id")); err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
s.enqueueModuleRefreshIfEnabled(a.TenantID, mid, "ip_range_delete")
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) handleExportModuleEntriesCSV(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "viewer") {
|
||||
return
|
||||
}
|
||||
moduleID := r.PathValue("module_id")
|
||||
mod, err := s.store.GetModule(a.TenantID, moduleID)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
communities, err := s.store.ListCommunities(a.TenantID)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
communityByID := make(map[string]string, len(communities))
|
||||
for _, c := range communities {
|
||||
communityByID[c.ID] = strings.TrimSpace(c.Community)
|
||||
}
|
||||
|
||||
records := make([][]string, 0, 64)
|
||||
|
||||
switch mod.Type {
|
||||
case "AS_PREFIXES":
|
||||
records = append(records, []string{"asn", "community"})
|
||||
list, err := s.store.ListASEntries(a.TenantID, moduleID)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
for _, x := range list {
|
||||
community := ""
|
||||
if x.CommunityID != nil {
|
||||
community = communityByID[*x.CommunityID]
|
||||
}
|
||||
records = append(records, []string{strconv.FormatInt(x.ASN, 10), community})
|
||||
}
|
||||
case "DOMAINS":
|
||||
records = append(records, []string{"domain", "community"})
|
||||
list, err := s.store.ListDomainEntries(a.TenantID, moduleID)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
for _, x := range list {
|
||||
community := ""
|
||||
if x.CommunityID != nil {
|
||||
community = communityByID[*x.CommunityID]
|
||||
}
|
||||
records = append(records, []string{x.FQDN, community})
|
||||
}
|
||||
case "IP_RANGES":
|
||||
records = append(records, []string{"ipRange", "community"})
|
||||
list, err := s.store.ListIPRangeEntries(a.TenantID, moduleID)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
for _, x := range list {
|
||||
community := ""
|
||||
if x.CommunityID != nil {
|
||||
community = communityByID[*x.CommunityID]
|
||||
}
|
||||
records = append(records, []string{x.Prefix, community})
|
||||
}
|
||||
default:
|
||||
writeProblem(w, http.StatusUnprocessableEntity, "Unprocessable Entity", "csv import/export is supported only for AS_PREFIXES, DOMAINS, IP_RANGES")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="module-entries.csv"`)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
cw := csv.NewWriter(w)
|
||||
for _, rec := range records {
|
||||
if err := cw.Write(rec); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
cw.Flush()
|
||||
}
|
||||
|
||||
func (s *Server) handleImportModuleEntriesCSV(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "editor") {
|
||||
return
|
||||
}
|
||||
moduleID := r.PathValue("module_id")
|
||||
res, err := importer.ImportModuleEntriesCSV(s.store, a.TenantID, moduleID, r.Body)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrInvalidInput) {
|
||||
writeProblem(w, http.StatusUnprocessableEntity, "Unprocessable Entity", "csv is empty")
|
||||
return
|
||||
}
|
||||
if strings.Contains(err.Error(), "importer: invalid csv") {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid csv")
|
||||
return
|
||||
}
|
||||
if strings.Contains(err.Error(), "importer: line") {
|
||||
log.Printf("httpapi: csv import: %v", err)
|
||||
writeProblem(w, http.StatusUnprocessableEntity, "Unprocessable Entity", csvInvalidRowDetail)
|
||||
return
|
||||
}
|
||||
if strings.Contains(err.Error(), "importer: csv import/export") {
|
||||
writeProblem(w, http.StatusUnprocessableEntity, "Unprocessable Entity", "csv import/export is supported only for AS_PREFIXES, DOMAINS, IP_RANGES")
|
||||
return
|
||||
}
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
if res.Imported > 0 {
|
||||
switch res.ModuleType {
|
||||
case "AS_PREFIXES":
|
||||
s.enqueueModuleRefreshIfEnabled(a.TenantID, moduleID, "as_entry_import_csv")
|
||||
case "DOMAINS":
|
||||
s.enqueueModuleRefreshIfEnabled(a.TenantID, moduleID, "domain_entry_import_csv")
|
||||
case "IP_RANGES":
|
||||
s.enqueueModuleRefreshIfEnabled(a.TenantID, moduleID, "ip_range_import_csv")
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"imported": res.Imported,
|
||||
"module_type": res.ModuleType,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleListDoh(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "viewer") {
|
||||
@@ -563,7 +836,7 @@ func commJSON(x *store.Community) map[string]any {
|
||||
if err := json.Unmarshal([]byte(x.ValueJSON), &v); err != nil {
|
||||
v = x.ValueJSON
|
||||
}
|
||||
return map[string]any{"id": x.ID, "name": x.Name, "kind": x.Kind, "value_json": v}
|
||||
return map[string]any{"id": x.ID, "community": x.Community, "title": x.Title, "value_json": v}
|
||||
}
|
||||
|
||||
func (s *Server) handleGetComm(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -643,6 +916,7 @@ func (s *Server) handlePostPeer(w http.ResponseWriter, r *http.Request) {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
s.enqueuePeerReconcile(a.TenantID, "peer_create")
|
||||
writeJSON(w, http.StatusCreated, peerJSON(x))
|
||||
}
|
||||
|
||||
@@ -674,6 +948,7 @@ func (s *Server) handlePatchPeer(w http.ResponseWriter, r *http.Request) {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
s.enqueuePeerReconcile(a.TenantID, "peer_patch")
|
||||
writeJSON(w, http.StatusOK, peerJSON(x))
|
||||
}
|
||||
|
||||
@@ -686,6 +961,7 @@ func (s *Server) handleDeletePeer(w http.ResponseWriter, r *http.Request) {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
s.enqueuePeerReconcile(a.TenantID, "peer_delete")
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
@@ -699,12 +975,20 @@ func (s *Server) handlePostSpeaker(w http.ResponseWriter, r *http.Request) {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid json")
|
||||
return
|
||||
}
|
||||
if err := normalizeSpeakerCreate(&body); err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
x, err := s.store.CreateSpeaker(a.TenantID, &body)
|
||||
if err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, speakerJSON(x))
|
||||
resp := speakerJSONFromStore(s.store, x)
|
||||
if meta := store.ParseSpeakerMeta(x.MetaJSON); meta.AgentSecret != "" {
|
||||
resp["agent_secret"] = meta.AgentSecret
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, resp)
|
||||
}
|
||||
|
||||
func (s *Server) handleGetSpeakerByID(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -717,7 +1001,7 @@ func (s *Server) handleGetSpeakerByID(w http.ResponseWriter, r *http.Request) {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, speakerJSON(x))
|
||||
writeJSON(w, http.StatusOK, speakerJSONFromStore(s.store, x))
|
||||
}
|
||||
|
||||
func (s *Server) handlePatchSpeaker(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -735,7 +1019,19 @@ func (s *Server) handlePatchSpeaker(w http.ResponseWriter, r *http.Request) {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, speakerJSON(x))
|
||||
writeJSON(w, http.StatusOK, speakerJSONFromStore(s.store, x))
|
||||
}
|
||||
|
||||
func (s *Server) handleDeleteSpeaker(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "editor") {
|
||||
return
|
||||
}
|
||||
if err := s.store.DeleteSpeaker(a.TenantID, r.PathValue("speaker_id")); err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) handleRevisionPrefixes(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -785,9 +1081,47 @@ func (s *Server) handlePatchSettings(w http.ResponseWriter, r *http.Request) {
|
||||
writeProblem(w, http.StatusBadRequest, "Bad Request", "invalid json")
|
||||
return
|
||||
}
|
||||
if raw, ok := body["revision_retention_minutes"]; ok && raw != nil {
|
||||
v, ok := parseRevisionRetentionMinutes(raw)
|
||||
if !ok {
|
||||
writeProblem(w, http.StatusUnprocessableEntity, "Unprocessable Entity", "revision_retention_minutes must be an integer in range 15..43200")
|
||||
return
|
||||
}
|
||||
body["revision_retention_minutes"] = v
|
||||
}
|
||||
if err := s.store.PatchGlobalSettings(a.TenantID, body); err != nil {
|
||||
writeStoreErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func parseRevisionRetentionMinutes(v any) (int, bool) {
|
||||
const minMinutes = 15
|
||||
const maxMinutes = 30 * 24 * 60
|
||||
|
||||
var out int
|
||||
switch x := v.(type) {
|
||||
case float64:
|
||||
if x != float64(int(x)) {
|
||||
return 0, false
|
||||
}
|
||||
out = int(x)
|
||||
case int:
|
||||
out = x
|
||||
case int64:
|
||||
out = int(x)
|
||||
case string:
|
||||
n, err := strconv.Atoi(strings.TrimSpace(x))
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
out = n
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
if out < minMinutes || out > maxMinutes {
|
||||
return 0, false
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestModuleEntriesCSVImportExportIPRanges(t *testing.T) {
|
||||
srv, err := New(Options{
|
||||
InsecureDev: true,
|
||||
SeedDemo: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer srv.Close()
|
||||
|
||||
tenant, _, modIP, _, _ := srv.Store().DemoIDs()
|
||||
mustSetTestAPIKeys(t, srv, "opkey|"+tenant+"|operator")
|
||||
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
defer ts.Close()
|
||||
client := ts.Client()
|
||||
base := ts.URL
|
||||
|
||||
reqList, _ := http.NewRequest(http.MethodGet, base+"/v1/communities?limit=10", nil)
|
||||
reqList.Header.Set("Authorization", "Bearer opkey")
|
||||
respList, err := client.Do(reqList)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = respList.Body.Close() }()
|
||||
if respList.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(respList.Body)
|
||||
t.Fatalf("communities status %d: %s", respList.StatusCode, b)
|
||||
}
|
||||
var listBody struct {
|
||||
Items []struct {
|
||||
Community string `json:"community"`
|
||||
} `json:"items"`
|
||||
}
|
||||
if err := json.NewDecoder(respList.Body).Decode(&listBody); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(listBody.Items) == 0 {
|
||||
t.Fatal("expected seeded community")
|
||||
}
|
||||
|
||||
csvBody := "\"ipRange\",\"community\"\n\"10.254.1.254/32\",\"" + listBody.Items[0].Community + "\"\n\"160.79.104.0/23\",\"" + listBody.Items[0].Community + "\"\n"
|
||||
reqImport, _ := http.NewRequest(http.MethodPost, base+"/v1/modules/"+modIP+"/entries.csv", strings.NewReader(csvBody))
|
||||
reqImport.Header.Set("Authorization", "Bearer opkey")
|
||||
reqImport.Header.Set("Content-Type", "text/csv")
|
||||
respImport, err := client.Do(reqImport)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = respImport.Body.Close() }()
|
||||
if respImport.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(respImport.Body)
|
||||
t.Fatalf("import status %d: %s", respImport.StatusCode, b)
|
||||
}
|
||||
var importBody struct {
|
||||
Imported int `json:"imported"`
|
||||
}
|
||||
if err := json.NewDecoder(respImport.Body).Decode(&importBody); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if importBody.Imported != 2 {
|
||||
t.Fatalf("expected imported=2, got %d", importBody.Imported)
|
||||
}
|
||||
|
||||
reqExport, _ := http.NewRequest(http.MethodGet, base+"/v1/modules/"+modIP+"/entries.csv", nil)
|
||||
reqExport.Header.Set("Authorization", "Bearer opkey")
|
||||
respExport, err := client.Do(reqExport)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = respExport.Body.Close() }()
|
||||
if respExport.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(respExport.Body)
|
||||
t.Fatalf("export status %d: %s", respExport.StatusCode, b)
|
||||
}
|
||||
if got := respExport.Header.Get("Content-Type"); !strings.Contains(got, "text/csv") {
|
||||
t.Fatalf("unexpected content-type: %q", got)
|
||||
}
|
||||
raw, err := io.ReadAll(respExport.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
records, err := csv.NewReader(strings.NewReader(string(raw))).ReadAll()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(records) < 3 {
|
||||
t.Fatalf("expected at least 3 csv rows, got %d", len(records))
|
||||
}
|
||||
if records[0][0] != "ipRange" || records[0][1] != "community" {
|
||||
t.Fatalf("unexpected header: %#v", records[0])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNestedModuleListPagination(t *testing.T) {
|
||||
srv, err := New(Options{InsecureDev: true, SeedDemo: true, BundleSeedHex: testBundleSeed})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer srv.Close()
|
||||
tenant, _, modIP, _, _ := srv.Store().DemoIDs()
|
||||
mustSetTestAPIKeys(t, srv, "edkey|"+tenant+"|editor")
|
||||
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
defer ts.Close()
|
||||
client := ts.Client()
|
||||
base := ts.URL
|
||||
mid := modIP
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
body := strings.NewReader(fmt.Sprintf(`{"prefix":"10.%d.0.0/24"}`, 200+i))
|
||||
req, _ := http.NewRequest(http.MethodPost, base+"/v1/modules/"+mid+"/ip-range-entries", body)
|
||||
req.Header.Set("Authorization", "Bearer edkey")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("create entry %d: status %d", i, resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
req, _ := http.NewRequest(http.MethodGet, base+"/v1/modules/"+mid+"/ip-range-entries?limit=2", nil)
|
||||
req.Header.Set("Authorization", "Bearer edkey")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("list status %d: %s", resp.StatusCode, b)
|
||||
}
|
||||
var page1 struct {
|
||||
Items []map[string]any `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&page1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page1.Items) != 2 {
|
||||
t.Fatalf("page1 items: got %d want 2", len(page1.Items))
|
||||
}
|
||||
if !page1.HasMore || page1.NextCursor == nil || *page1.NextCursor == "" {
|
||||
t.Fatalf("page1: has_more=%v next_cursor=%v", page1.HasMore, page1.NextCursor)
|
||||
}
|
||||
|
||||
req2, _ := http.NewRequest(http.MethodGet, base+"/v1/modules/"+mid+"/ip-range-entries?limit=2&cursor="+*page1.NextCursor, nil)
|
||||
req2.Header.Set("Authorization", "Bearer edkey")
|
||||
resp2, err := client.Do(req2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp2.Body.Close() }()
|
||||
var page2 struct {
|
||||
Items []map[string]any `json:"items"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
if err := json.NewDecoder(resp2.Body).Decode(&page2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page1.Items)+len(page2.Items) < 3 {
|
||||
t.Fatalf("expected at least 3 entries across pages, got %d+%d", len(page1.Items), len(page2.Items))
|
||||
}
|
||||
}
|
||||
@@ -21,9 +21,9 @@ type Server struct {
|
||||
pgPool *pgxpool.Pool
|
||||
jobs *jobs.Registry
|
||||
bundlePriv ed25519.PrivateKey
|
||||
apiKeys []apiKeyRecord
|
||||
insecureDev bool
|
||||
keyResolver *apiKeyResolver
|
||||
corsOrigins []string
|
||||
cdnHTTP *http.Client
|
||||
mux *http.ServeMux
|
||||
}
|
||||
|
||||
@@ -31,10 +31,10 @@ type Server struct {
|
||||
type Options struct {
|
||||
APIKeys string
|
||||
// DatabaseURL enables PostgreSQL-backed store (migrations applied on connect).
|
||||
DatabaseURL string
|
||||
InsecureDev bool
|
||||
SeedDemo bool
|
||||
BundleSeedHex string
|
||||
DatabaseURL string
|
||||
InsecureDev bool
|
||||
SeedDemo bool
|
||||
BundleSeedHex string
|
||||
CORSAllowedOrigins string
|
||||
}
|
||||
|
||||
@@ -59,14 +59,18 @@ func New(opts Options) (*Server, error) {
|
||||
_, priv, _ = ed25519.GenerateKey(rand.Reader)
|
||||
}
|
||||
|
||||
resolver, err := newAPIKeyResolver(opts.APIKeys, backend)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s := &Server{
|
||||
store: backend,
|
||||
pgPool: pool,
|
||||
jobs: reg,
|
||||
bundlePriv: priv,
|
||||
apiKeys: parseAPIKeysSpec(opts.APIKeys),
|
||||
insecureDev: opts.InsecureDev && opts.SeedDemo,
|
||||
keyResolver: resolver,
|
||||
corsOrigins: parseCORSOrigins(opts.CORSAllowedOrigins),
|
||||
cdnHTTP: NewCDNHTTPClient(),
|
||||
}
|
||||
s.mux = http.NewServeMux()
|
||||
s.registerRoutes()
|
||||
|
||||
+205
-12
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"evobgp/internal/jobs"
|
||||
"evobgp/internal/signing"
|
||||
"evobgp/internal/version"
|
||||
)
|
||||
|
||||
const testBundleSeed = "0101010101010101010101010101010101010101010101010101010101010101"
|
||||
@@ -28,7 +29,7 @@ func TestAPIRefreshApplyJobsBundle(t *testing.T) {
|
||||
}
|
||||
defer srv.Close()
|
||||
tenant, modCDN, modIP, rev, speaker := srv.Store().DemoIDs()
|
||||
srv.apiKeys = parseAPIKeysSpec("nodekey|" + tenant + "|node,opkey|" + tenant + "|operator")
|
||||
mustSetTestAPIKeys(t, srv, "nodekey|"+tenant+"|node,opkey|"+tenant+"|operator,edkey|"+tenant+"|editor")
|
||||
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
defer ts.Close()
|
||||
@@ -50,7 +51,7 @@ func TestAPIRefreshApplyJobsBundle(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("status %d: %s", resp.StatusCode, b)
|
||||
@@ -68,18 +69,25 @@ func TestAPIRefreshApplyJobsBundle(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("refresh IP_RANGES no op", func(t *testing.T) {
|
||||
t.Run("refresh IP_RANGES queues render job", func(t *testing.T) {
|
||||
req, _ := http.NewRequest(http.MethodPost, base+"/v1/modules/"+modIP+"/refresh", nil)
|
||||
req.Header.Set("Authorization", "Bearer opkey")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusNoContent {
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusAccepted {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("status %d: %s", resp.StatusCode, b)
|
||||
}
|
||||
var body struct {
|
||||
JobID string `json:"job_id"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitJob(t, client, base, "opkey", body.JobID)
|
||||
})
|
||||
|
||||
t.Run("refresh CDN queues job", func(t *testing.T) {
|
||||
@@ -89,7 +97,7 @@ func TestAPIRefreshApplyJobsBundle(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusAccepted {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("status %d: %s", resp.StatusCode, b)
|
||||
@@ -110,13 +118,41 @@ func TestAPIRefreshApplyJobsBundle(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("status %d: %s", resp.StatusCode, b)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("diagnostic log for revision", func(t *testing.T) {
|
||||
req, _ := http.NewRequest(http.MethodGet, base+"/v1/revisions/"+rev+"/diagnostic-log", nil)
|
||||
req.Header.Set("Authorization", "Bearer opkey")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("status %d: %s", resp.StatusCode, b)
|
||||
}
|
||||
if got := resp.Header.Get("Content-Type"); !strings.Contains(got, "text/plain") {
|
||||
t.Fatalf("unexpected content-type: %q", got)
|
||||
}
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
body := string(raw)
|
||||
for _, needle := range []string{
|
||||
"EvoBGP revision diagnostic log",
|
||||
"revision_id=" + rev,
|
||||
"## Raw rows",
|
||||
} {
|
||||
if !strings.Contains(body, needle) {
|
||||
t.Fatalf("diagnostic log missing %q", needle)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("list modules peers speakers", func(t *testing.T) {
|
||||
for _, path := range []string{"/v1/modules", "/v1/peers", "/v1/speakers"} {
|
||||
req, _ := http.NewRequest(http.MethodGet, base+path, nil)
|
||||
@@ -126,7 +162,7 @@ func TestAPIRefreshApplyJobsBundle(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
_ = resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("%s status %d: %s", path, resp.StatusCode, b)
|
||||
}
|
||||
@@ -142,6 +178,90 @@ func TestAPIRefreshApplyJobsBundle(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("modules filter by type", func(t *testing.T) {
|
||||
req, _ := http.NewRequest(http.MethodGet, base+"/v1/modules?type=IP_RANGES", nil)
|
||||
req.Header.Set("Authorization", "Bearer opkey")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("status %d: %s", resp.StatusCode, b)
|
||||
}
|
||||
var body struct {
|
||||
Items []struct {
|
||||
Type string `json:"type"`
|
||||
} `json:"items"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(body.Items) == 0 {
|
||||
t.Fatalf("expected at least one IP_RANGES module")
|
||||
}
|
||||
for _, item := range body.Items {
|
||||
if item.Type != "IP_RANGES" {
|
||||
t.Fatalf("unexpected module type %q", item.Type)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("router lists catalog endpoint", func(t *testing.T) {
|
||||
req, _ := http.NewRequest(http.MethodGet, base+"/v1/router-lists/catalog", nil)
|
||||
req.Header.Set("Authorization", "Bearer opkey")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("status %d: %s", resp.StatusCode, b)
|
||||
}
|
||||
var body struct {
|
||||
Modules struct {
|
||||
Items []map[string]any `json:"items"`
|
||||
} `json:"modules"`
|
||||
Domains struct {
|
||||
Items []map[string]any `json:"items"`
|
||||
} `json:"domains"`
|
||||
ASNs struct {
|
||||
Items []map[string]any `json:"items"`
|
||||
} `json:"asns"`
|
||||
IPRanges struct {
|
||||
Items []map[string]any `json:"items"`
|
||||
} `json:"ip_ranges"`
|
||||
Communities struct {
|
||||
Items []map[string]any `json:"items"`
|
||||
} `json:"communities"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(body.Modules.Items) == 0 {
|
||||
t.Fatalf("expected modules in catalog")
|
||||
}
|
||||
if body.Communities.Items == nil {
|
||||
t.Fatalf("expected communities.items field in catalog")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("rollback forbidden for editor", func(t *testing.T) {
|
||||
req, _ := http.NewRequest(http.MethodPost, base+"/v1/revisions/"+rev+"/rollback", nil)
|
||||
req.Header.Set("Authorization", "Bearer edkey")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusForbidden {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("status %d want 403: %s", resp.StatusCode, b)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("rollback queues job", func(t *testing.T) {
|
||||
req, _ := http.NewRequest(http.MethodPost, base+"/v1/revisions/"+rev+"/rollback", nil)
|
||||
req.Header.Set("Authorization", "Bearer opkey")
|
||||
@@ -149,7 +269,7 @@ func TestAPIRefreshApplyJobsBundle(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusAccepted {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("status %d: %s", resp.StatusCode, b)
|
||||
@@ -169,7 +289,7 @@ func TestAPIRefreshApplyJobsBundle(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusAccepted {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("status %d: %s", resp.StatusCode, b)
|
||||
@@ -194,7 +314,7 @@ func TestAPIRefreshApplyJobsBundle(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("status %d: %s", resp.StatusCode, b)
|
||||
@@ -221,7 +341,7 @@ func waitJob(t *testing.T, client *http.Client, base, token, jobID string) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
_ = resp.Body.Close()
|
||||
var body struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
@@ -236,3 +356,76 @@ func waitJob(t *testing.T, client *http.Client, base, token, jobID string) {
|
||||
}
|
||||
t.Fatalf("job %s did not complete", jobID)
|
||||
}
|
||||
|
||||
func TestParseBGPProtocolStates(t *testing.T) {
|
||||
raw := `BIRD 2.16.2 ready.
|
||||
name proto table state since info
|
||||
device1 Device --- up 2026-04-09
|
||||
evobgp_p_abcdef01 BGP master up 2026-04-09 Established
|
||||
evobgp_p_01234567 BGP master start 2026-04-09 Connect
|
||||
`
|
||||
got := parseBGPProtocolStates(raw)
|
||||
if got["evobgp_p_abcdef01"] != "Established" {
|
||||
t.Fatalf("expected protocol state Established, got %q", got["evobgp_p_abcdef01"])
|
||||
}
|
||||
if got["evobgp_p_01234567"] != "Connect" {
|
||||
t.Fatalf("expected protocol state Connect, got %q", got["evobgp_p_01234567"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestVersionEndpoints(t *testing.T) {
|
||||
srv, err := New(Options{
|
||||
InsecureDev: true,
|
||||
SeedDemo: true,
|
||||
BundleSeedHex: testBundleSeed,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer srv.Close()
|
||||
|
||||
oldVer := version.Version
|
||||
oldSHA := version.GitSHA
|
||||
oldTime := version.BuildTime
|
||||
version.Version = "1.2.3"
|
||||
version.GitSHA = "abc123def456"
|
||||
version.BuildTime = "2026-05-20T12:00:00Z"
|
||||
t.Cleanup(func() {
|
||||
version.Version = oldVer
|
||||
version.GitSHA = oldSHA
|
||||
version.BuildTime = oldTime
|
||||
})
|
||||
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
defer ts.Close()
|
||||
|
||||
for _, path := range []string{"/version", "/v1/version"} {
|
||||
t.Run(path, func(t *testing.T) {
|
||||
resp, err := http.Get(ts.URL + path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("status %d: %s", resp.StatusCode, b)
|
||||
}
|
||||
var body map[string]string
|
||||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body["version"] != "1.2.3" {
|
||||
t.Fatalf("version=%q want 1.2.3", body["version"])
|
||||
}
|
||||
if body["api_version"] != "1.2.3" {
|
||||
t.Fatalf("api_version=%q want 1.2.3", body["api_version"])
|
||||
}
|
||||
if body["git_sha"] != "abc123def456" {
|
||||
t.Fatalf("git_sha=%q", body["git_sha"])
|
||||
}
|
||||
if body["build_time"] != "2026-05-20T12:00:00Z" {
|
||||
t.Fatalf("build_time=%q", body["build_time"])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"evobgp/internal/nodedispatch"
|
||||
"evobgp/internal/store"
|
||||
)
|
||||
|
||||
func speakerJSONFromStore(st store.Backend, sp *store.Speaker) map[string]any {
|
||||
if sp == nil {
|
||||
return map[string]any{}
|
||||
}
|
||||
meta := store.ParseSpeakerMeta(sp.MetaJSON)
|
||||
m := map[string]any{
|
||||
"id": sp.ID,
|
||||
"role": sp.Role,
|
||||
"endpoint": sp.Endpoint,
|
||||
}
|
||||
if sp.LastAppliedRevisionID != nil {
|
||||
m["last_applied_revision_id"] = *sp.LastAppliedRevisionID
|
||||
} else {
|
||||
m["last_applied_revision_id"] = nil
|
||||
}
|
||||
if st != nil {
|
||||
if rid, at, err := st.LatestPublishedRevision(sp.ID); err == nil && rid != "" {
|
||||
m["published_revision_id"] = rid
|
||||
m["published_at"] = at.UTC().Format(time.RFC3339Nano)
|
||||
} else {
|
||||
m["published_revision_id"] = nil
|
||||
m["published_at"] = nil
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(sp.MetaJSON) != "" && sp.MetaJSON != "{}" {
|
||||
var raw map[string]any
|
||||
if json.Unmarshal([]byte(sp.MetaJSON), &raw) == nil {
|
||||
m["meta_json"] = raw
|
||||
}
|
||||
}
|
||||
if meta.AgentDomain != "" {
|
||||
m["agent_domain"] = meta.AgentDomain
|
||||
}
|
||||
if meta.NodeIPv4 != "" {
|
||||
m["node_ipv4"] = meta.NodeIPv4
|
||||
}
|
||||
if meta.BirdBgpSourceIPv4 != "" {
|
||||
m["bird_bgp_source_ipv4"] = meta.BirdBgpSourceIPv4
|
||||
}
|
||||
if meta.LastDispatchAt != "" {
|
||||
m["last_dispatch_at"] = meta.LastDispatchAt
|
||||
}
|
||||
if meta.LastDispatchError != "" {
|
||||
m["last_dispatch_error"] = meta.LastDispatchError
|
||||
}
|
||||
if meta.LastDispatchStatus != "" {
|
||||
m["dispatch_status"] = meta.LastDispatchStatus
|
||||
}
|
||||
if meta.SyncStatus != "" {
|
||||
m["sync_status"] = meta.SyncStatus
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (s *Server) handleBundleSigningPublicKey(w http.ResponseWriter, r *http.Request) {
|
||||
a, ok := authFromContext(r.Context())
|
||||
if !ok || !s.requireAtLeast(w, a, "viewer") {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"public_key_base64": s.BundlePublicKeyBase64(),
|
||||
})
|
||||
}
|
||||
|
||||
// normalizeSpeakerCreate fills meta defaults and validates replica fields.
|
||||
func normalizeSpeakerCreate(in *store.Speaker) error {
|
||||
if in == nil {
|
||||
return store.ErrInvalidInput
|
||||
}
|
||||
meta := store.ParseSpeakerMeta(in.MetaJSON)
|
||||
if meta.AgentSecret == "" {
|
||||
b := make([]byte, 24)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return err
|
||||
}
|
||||
meta.AgentSecret = hex.EncodeToString(b)
|
||||
}
|
||||
if meta.AgentPort == 0 {
|
||||
meta.AgentPort = 8443
|
||||
}
|
||||
if meta.NodeIPv4 == "" {
|
||||
meta.NodeIPv4 = store.IPv4FromEndpoint(in.Endpoint)
|
||||
}
|
||||
if meta.BirdBgpSourceIPv4 == "" && meta.NodeIPv4 != "" {
|
||||
meta.BirdBgpSourceIPv4 = meta.NodeIPv4
|
||||
}
|
||||
if meta.BirdBgpSourceIPv4 != "" && !store.ValidIPv4(meta.BirdBgpSourceIPv4) {
|
||||
return store.ErrInvalidInput
|
||||
}
|
||||
if meta.AgentDomain == "" && in.Endpoint != "" {
|
||||
ep := strings.TrimSpace(in.Endpoint)
|
||||
if strings.HasPrefix(ep, "https://") {
|
||||
u := strings.TrimPrefix(ep, "https://")
|
||||
if idx := strings.Index(u, "/"); idx >= 0 {
|
||||
u = u[:idx]
|
||||
}
|
||||
if idx := strings.Index(u, ":"); idx >= 0 {
|
||||
u = u[:idx]
|
||||
}
|
||||
if u != "" && !store.ValidIPv4(u) {
|
||||
meta.AgentDomain = u
|
||||
}
|
||||
}
|
||||
}
|
||||
in.MetaJSON = store.SpeakerMetaJSON(meta)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) recordSpeakerDispatch(tenantID string, sp *store.Speaker, res nodedispatch.Result) {
|
||||
if s == nil || s.store == nil || sp == nil {
|
||||
return
|
||||
}
|
||||
patch := store.SpeakerMeta{
|
||||
LastDispatchAt: time.Now().UTC().Format(time.RFC3339Nano),
|
||||
LastDispatchStatus: res.Status,
|
||||
}
|
||||
if res.Error != "" {
|
||||
patch.LastDispatchError = res.Error
|
||||
patch.SyncStatus = "error"
|
||||
} else if res.Status == "ok" {
|
||||
patch.LastDispatchError = ""
|
||||
patch.SyncStatus = "synced"
|
||||
}
|
||||
meta := store.MergeSpeakerMetaJSON(sp.MetaJSON, patch)
|
||||
_, _ = s.store.UpdateSpeaker(tenantID, sp.ID, &store.SpeakerPatch{MetaJSON: &meta})
|
||||
}
|
||||
Loaded 100 of 511 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user