docs: simplify project guides and add GPLv3

This commit is contained in:
TakuyaYagam1 committed 2026-10-11 22:25:10 +03:00
1 parent e4de6d0f9a
commit 76d32bb79f
59 files changed
+2267 -8843

No files matched your search

+17 -43
View File
@@ -1,55 +1,29 @@
# Lab provisioner (labd)
# Lab provisioner
[Русский](README.md) | English
A separate Go service that creates practical labs (MikroTik CHR and small Ubuntu VMs) as LXD virtual machines on the app host and deletes them. labd is the only component that talks to the LXD API: the `lxd` group is equivalent to root on the host, so the backend gets neither the LXD socket nor node addresses. The backend calls labd through the internal `api/labd/` contract over TLS with a bearer token; the backend has the `LabProvisioner` port, the generated client, and a disabled adapter (`backend/internal/adapter/secondary/lab_provisioner/`), but neither bootstrap nor a use case wires them yet.
labd is a Go service that creates and deletes LXD VMs for practical labs. Only labd receives the LXD socket; the backend uses the `api/labd/` contract with TLS and a bearer token. Membership in the `lxd` group grants root-equivalent access to the host.
- `cmd/labd/` is the entry point.
- `internal/lab/` holds the lab record and the names of its LXD objects (`lcxl-<id>-<node>` for instances, `lxl<id><nn>` for bridges) with the `user.lincodex.lab` marker.
- `internal/template/` is the template model: nodes (`mikrotik` or `ubuntu`, profile, source snapshot, memory), L2 links, the variant plan from the seed (management addresses, NICs, and MACs), and the hooks that render cloud-init user-data and network-config or a RouterOS script and check a variant. Real templates and images are not part of this build yet: the registry is empty and CreateLab answers `validation_failed`.
- `internal/lxd/` is a small client of the LXD REST API over its unix socket. The official `github.com/canonical/lxd/client` is not used: since LXD 5.20 it is AGPL-3.0 and pulls in most of the LXD tree. `internal/lxd/lxdfake/` is an in-memory LXD for unit tests.
- `internal/pool/` holds admission by the host memory budget, cloning nodes from snapshots, readiness by the management TCP port, console tokens, checks, expiry, and guaranteed deletion.
- `internal/reaper/` runs the periodic sweep (timers, deletion retries) and the reconciliation with LXD (orphans).
- `internal/store/` keeps the state in one JSON file.
- `internal/server/` is the HTTP API on the generated ogen server (`internal/api/`, from `codegen/ogen.yml`).
The built-in template registry is currently empty: lab creation returns `validation_failed`. The backend contains a port and client but does not connect them in bootstrap yet. Console token issuance is implemented; WebSocket attach returns 501. A usable workflow needs prepared images, templates, and integration.
## How a lab works
- `internal/template/` - nodes, links, variant parameters, and lab checkers.
- `internal/lxd/` - LXD REST client through a Unix socket and a test fake.
- `internal/pool/` - memory budget, creation, readiness, checking, and deletion.
- `internal/store/`, `internal/reaper/` - JSON state, lifetimes, and orphan cleanup.
- `internal/server/`, `internal/api/` - API and ogen code from `api/labd/`.
1. CreateLab (`PUT /v1/labs/{lab_id}`) checks the template and the lifetime, reserves memory and management addresses, writes the lab to the state file, and only then starts working with LXD. It answers 202 `provisioning`; a repeat with the same ID and body returns the same lab.
2. Every link gets its own bridge without an address on the host (`ipv4.address=none`, `ipv6.address=none`): lab traffic is not routed and reaches neither the host, the application, another lab, nor the internet. Every node is copied from a prepared snapshot (a subvolume snapshot on the btrfs pool `lincodex`, seconds) and gets a management NIC on `lxdbr-labmgmt` with a fixed MAC, `security.mac_filtering`, and `security.port_isolation`, NICs on the bridges of its own lab, and the cloud-init of its variant; `security.devlxd=false`.
3. labd starts the nodes and waits until the management port of each (22 for Ubuntu, 8728 for RouterOS) accepts a TCP connection from the host side of the bridge. The lab becomes `ready`; on an LXD error or a timeout it becomes `failed` and is deleted.
4. A lab is deleted at `expires_at` (creation time plus `ttl_seconds`) or earlier by DeleteLab. Deletion is retried until LXD confirms that the instances and bridges are gone; only then are the memory and addresses released, and the record becomes `deleted` and stays for `LABD_DELETED_RETENTION`.
A lab record is persisted before any LXD object is created. Deletion retries until every object is gone, then releases capacity. A corrupt state file blocks startup; `/readyz` requires successful reconciliation with LXD. The file contains variant seeds; keep it at mode 0600.
Deletion after a crash: a record exists in the file before the first LXD object and disappears after the last one. At startup a lab in `provisioning` becomes `failed` (`interrupted`) and is deleted; the timers of the others live in the file and fire at the first sweep. Reconciliation deletes instances and bridges with the labd prefix and marker that no record owns; an object with the prefix but without the marker is only logged. labd is not ready (`/readyz` 503) until the first reconciliation succeeds.
## Running and checking
Capacity: a lab is admitted only when the memory of all its nodes fits `LABD_MEMORY_BUDGET_MIB` together with the current labs (and, when set, `LABD_MAX_LABS`). Otherwise the answer is 503 `lab_pool_busy` with Retry-After and nothing is stored. A template that does not fit the budget even alone stops labd from starting. There are no pre-started nodes: a snapshot clone is cheap, and every node must boot with its own variant.
```sh
make -C labd check
```
Storage: a JSON file that every change rewrites completely through a temporary file, fsync, rename, and a directory fsync. labd holds a few dozen labs, so this needs no SQLite, cgo, or new dependency, and the file can be read during an incident. The file holds variant seeds, so it is `0600` in the directory of the labd user. A corrupt file stops the start: labd must not forget labs whose objects may still exist.
This check uses the LXD fake. `make -C labd test-live` creates and deletes a real lab on a separate test LXD; set `LABD_LIVE_SOCKET` and `LABD_LIVE_SOURCE=instance/snapshot`. Never run it against production.
A console token (`POST /v1/labs/{lab_id}/console-tokens`) is single-use and lives at most 120 seconds; labd keeps only its SHA-256 in memory. The WebSocket attach itself is not implemented yet and answers 501. A check (`POST /v1/labs/{lab_id}/check`) calls the template checker over the management addresses; when the checker cannot reach a node, the answer is 503 `lab_unavailable`, never a failed check.
On the app host, use the [systemd unit](../deploy/labs/lincodex-labd.service) and [example settings](../deploy/labs/labd.env.example). TLS, a token file, and restricted clients are required. `LABD_MEMORY_BUDGET_MIB`, `LABD_MAX_LABS`, and `LABD_MAX_LIFETIME` control capacity and lifetime; `internal/config/` reads all `LABD_*` settings.
## Settings
Before enabling labs, test L2 isolation, MAC/port filtering, cloud-init application, and node authentication during checks. LXD group access remains privileged regardless of systemd restrictions.
`internal/config/` reads the `LABD_*` variables and reports the errors of all of them together. TLS (`LABD_TLS_CERT_FILE`, `LABD_TLS_KEY_FILE`) and a token (`LABD_API_TOKEN_FILE`, at least 32 characters) are required; `LABD_DEV_ALLOW_PLAINTEXT_HTTP=true` is for development only. Main defaults:
| Variable | Default | Meaning |
| --- | --- | --- |
| `LABD_LISTEN_ADDRESS` | `127.0.0.1:8445` | API address; in production the gateway address of the application Docker network |
| `LABD_ALLOWED_CLIENTS` | `127.0.0.0/8,::1/128` | networks requests are accepted from; others get 401 |
| `LABD_LXD_SOCKET`, `LABD_LXD_PROJECT` | `/var/snap/lxd/common/lxd/unix.socket`, `default` | LXD |
| `LABD_STATE_FILE` | `/var/lib/lincodex-labd/labs.json` | state file |
| `LABD_MEMORY_BUDGET_MIB`, `LABD_MAX_LABS` | `3072`, `0` (no separate cap) | capacity |
| `LABD_MAX_LIFETIME`, `LABD_PROVISION_TIMEOUT` | `2h`, `5m` | lifetime and provisioning |
| `LABD_SWEEP_INTERVAL`, `LABD_RECONCILE_INTERVAL`, `LABD_DELETED_RETENTION` | `15s`, `5m`, `1h` | deletion |
| `LABD_CONSOLE_TOKEN_TTL`, `LABD_CHECK_TIMEOUT`, `LABD_RETRY_AFTER` | `1m`, `1m`, `30s` | tokens, checks, Retry-After |
| `LABD_MGMT_NETWORK`, `LABD_MGMT_SUBNET`, `LABD_MGMT_HOST_ADDRESS`, `LABD_MGMT_FIRST_ADDRESS` | `lxdbr-labmgmt`, `10.81.0.0/24`, `10.81.0.1`, `10.81.0.16` | management plane from `deploy/labs/lxd-preseed.yaml` |
## Running on the host
labd runs as a systemd service on the app host, not in Docker: `deploy/labs/lincodex-labd.service` and the example settings `deploy/labs/labd.env.example` (no secrets). The service runs as the dedicated user `lincodex-labd` with the supplementary group `lxd`, without capabilities, with `ProtectSystem=strict`, `StateDirectory=lincodex-labd`, and write access only to the LXD socket. The certificate, key, and token live in `/etc/lincodex-labd/`, readable only by that user. The host firewall opens the API port only to the application network. A compromise of labd is still a compromise of the host: the `lxd` group gives root through the LXD API, so labd accepts nothing but the described contract and never executes request data.
Before the rollout, check on the host what this build did not verify: that a bridge without an address gets no IPv6 link-local address (LXD disables IPv6 on such a bridge), that L2 traffic between nodes is not dropped by the Docker FORWARD chain when `br_netfilter` is loaded, that the LXD version supports `security.port_isolation` and `cloud-init:config`, and how the CHR image applies the script from cloud-init user-data. A template checker must authenticate the node (a pinned SSH host key or credentials of this lab), because a node of another lab can answer ARP for a foreign management address.
## Checks
From the repository root, `make -C labd check` runs formatting, the Linux build, unit tests with the race detector, the generated code check, and lint. The tests use the in-memory LXD: creating and deleting a lab (nodes on isolated bridges that disappear completely), restarting labd in the middle of a lab's life and the timer deletion after it, a restart during provisioning, orphans, a failing and retried deletion, and the capacity limit with 503 for the extra lab. `make -C labd test-live` creates and deletes one bridge and one instance on a real LXD; it does not run without `LABD_LIVE_SOCKET` and `LABD_LIVE_SOURCE` and must not target the production host.
Networks and host preparation: [DEPLOYMENT.md](../docs/en/DEPLOYMENT.md#labs-and-labd).
+17 -43
View File
@@ -1,55 +1,29 @@
# Провиженер лабораторий (labd)
# Провиженер лабораторий
Русский | [English](README.en.md)
Отдельный Go-сервис, который создает практические лаборатории (MikroTik CHR и небольшие Ubuntu VM) как LXD-машины на app-хосте и удаляет их. labd - единственный компонент, который обращается к LXD API: группа `lxd` равна root на хосте, поэтому backend не получает ни сокет LXD, ни адреса узлов. Backend вызывает labd по внутреннему контракту `api/labd/` с TLS и bearer-токеном; в backend есть порт `LabProvisioner`, сгенерированный клиент и отключенный адаптер (`backend/internal/adapter/secondary/lab_provisioner/`), но ни bootstrap, ни usecase их пока не подключают.
labd - Go-сервис, который создает и удаляет LXD VM для практических лабораторий. Только он получает сокет LXD; backend обращается по контракту `api/labd/` с TLS и bearer-токеном. Группа `lxd` дает права, эквивалентные root на хосте.
- `cmd/labd/` - точка входа.
- `internal/lab/` - запись лаборатории и имена LXD-объектов (`lcxl-<id>-<узел>` для машин, `lxl<id><nn>` для мостов) с меткой `user.lincodex.lab`.
- `internal/template/` - модель шаблона: узлы (`mikrotik` или `ubuntu`, профиль, снимок-источник, память), L2-связи, план варианта по seed (адреса управления, NIC и MAC) и хуки рендера (cloud-init user-data и network-config, скрипт RouterOS) и проверки. Реальные шаблоны и образы в этой сборке еще не входят: реестр пуст, и CreateLab отвечает `validation_failed`.
- `internal/lxd/` - небольшой клиент LXD REST API через unix-сокет. Официальный `github.com/canonical/lxd/client` не используется: с LXD 5.20 он под AGPL-3.0 и тянет большую часть дерева LXD. `internal/lxd/lxdfake/` - LXD в памяти для unit-тестов.
- `internal/pool/` - допуск по бюджету памяти хоста, клонирование узлов из снимков, готовность по TCP-порту управления, console-токены, проверка, истечение и гарантированное удаление.
- `internal/reaper/` - периодический sweep (таймеры, повтор удаления) и сверка с LXD (сироты).
- `internal/store/` - состояние в одном JSON-файле.
- `internal/server/` - HTTP API на сгенерированном ogen-сервере (`internal/api/`, из `codegen/ogen.yml`).
Сейчас встроенный реестр шаблонов пуст: создание лаборатории отвечает `validation_failed`. Backend содержит порт и клиент, но bootstrap их пока не подключает. Выдача console-токенов реализована, WebSocket attach отвечает 501. Рабочий сценарий требует подготовленных образов, шаблонов и интеграции.
## Как работает лаборатория
- `internal/template/` - узлы, связи, параметры варианта и checker лаборатории.
- `internal/lxd/` - LXD REST-клиент через unix socket и fake для тестов.
- `internal/pool/` - бюджет памяти, создание, готовность, проверка и удаление.
- `internal/store/`, `internal/reaper/` - состояние в JSON, сроки жизни и уборка сирот.
- `internal/server/`, `internal/api/` - API и ogen-код из `api/labd/`.
1. CreateLab (`PUT /v1/labs/{lab_id}`) проверяет шаблон и время жизни, резервирует память и адреса управления, записывает лабораторию в файл состояния и только после этого начинает работу с LXD. Ответ 202 `provisioning`; повтор с тем же ID и телом возвращает ту же лабораторию.
2. Для каждой связи создается свой мост без адреса на хосте (`ipv4.address=none`, `ipv6.address=none`): трафик лаборатории не маршрутизируется и не доходит до хоста, приложения, другой лаборатории или интернета. Каждый узел копируется из подготовленного снимка (на btrfs-пуле `lincodex` это snapshot подтома, секунды), получает NIC управления на `lxdbr-labmgmt` с фиксированным MAC, `security.mac_filtering` и `security.port_isolation`, NIC на мостах своей лаборатории и cloud-init своего варианта; `security.devlxd=false`.
3. labd запускает узлы и ждет, пока порт управления каждого (22 для Ubuntu, 8728 для RouterOS) примет TCP-соединение с хостовой стороны моста. Лаборатория становится `ready`; при ошибке LXD или по таймауту - `failed` и удаляется.
4. Лаборатория удаляется в `expires_at` (время создания плюс `ttl_seconds`) или раньше по DeleteLab. Удаление повторяется, пока LXD не подтвердит, что машин и мостов нет; только тогда освобождаются память и адреса, а запись становится `deleted` и хранится `LABD_DELETED_RETENTION`.
Запись лаборатории сохраняется до создания LXD-объектов. Удаление повторяется до исчезновения всех объектов, после чего освобождается емкость. Поврежденный файл состояния останавливает запуск; `/readyz` требует успешной сверки с LXD. Файл содержит seed вариантов, храните его с правами 0600.
Гарантия удаления после сбоя: запись появляется в файле до первого LXD-объекта и исчезает после последнего. При старте лаборатория в `provisioning` становится `failed` (`interrupted`) и удаляется; таймеры остальных живут в файле и срабатывают при первом sweep. Сверка удаляет машины и мосты с префиксом и меткой labd, которых нет ни в одной записи; объект с префиксом, но без метки, только попадает в лог. labd не готов (`/readyz` 503), пока первая сверка не прошла.
## Запуск и проверки
Емкость: лаборатория допускается, только если память всех ее узлов помещается в `LABD_MEMORY_BUDGET_MIB` вместе с текущими лабораториями (и, если задан, в `LABD_MAX_LABS`). Иначе ответ 503 `lab_pool_busy` с Retry-After, ничего не сохраняется. Шаблон, который не помещается в бюджет даже один, не дает labd запуститься. Готовых заранее запущенных узлов нет: клон снимка дешев, а каждый узел должен загрузиться со своим вариантом.
```sh
make -C labd check
```
Хранилище: JSON-файл, который при каждом изменении целиком пишется во временный файл, fsync, rename и fsync каталога. Лабораторий десятки, поэтому этого хватает без SQLite, cgo и новых зависимостей, а файл читается при разборе инцидента. В файле есть seed вариантов, поэтому он `0600` в каталоге пользователя labd. Поврежденный файл останавливает старт: labd не должен забыть лаборатории, объекты которых еще могут существовать.
Проверка использует LXD fake. `make -C labd test-live` создает и удаляет настоящую лабораторию на отдельном тестовом LXD; нужны `LABD_LIVE_SOCKET` и `LABD_LIVE_SOURCE=instance/snapshot`. Не запускайте ее против production.
Console-токен (`POST /v1/labs/{lab_id}/console-tokens`) одноразовый, до 120 секунд, labd хранит только его SHA-256 в памяти. Сам WebSocket attach пока не реализован и отвечает 501. Проверка (`POST /v1/labs/{lab_id}/check`) вызывает checker шаблона по адресам управления; если checker не может дойти до узла, ответ 503 `lab_unavailable`, а не проваленная проверка.
На app-хосте используйте [systemd unit](../deploy/labs/lincodex-labd.service) и [пример настроек](../deploy/labs/labd.env.example). Обязательны TLS, файл токена и ограниченный список клиентов. `LABD_MEMORY_BUDGET_MIB`, `LABD_MAX_LABS` и `LABD_MAX_LIFETIME` задают емкость и срок; все `LABD_*` читает `internal/config/`.
## Настройки
Перед включением проверьте L2-изоляцию, MAC/port filtering, применение cloud-init и подлинность узлов при проверке. Доступ к группе `lxd` остается привилегированным независимо от ограничений systemd.
Переменные `LABD_*` читает `internal/config/`; ошибки всех переменных выводятся вместе. Обязательны TLS (`LABD_TLS_CERT_FILE`, `LABD_TLS_KEY_FILE`) и токен (`LABD_API_TOKEN_FILE`, не короче 32 символов); `LABD_DEV_ALLOW_PLAINTEXT_HTTP=true` только для разработки. Основные значения по умолчанию:
| Переменная | По умолчанию | Смысл |
| --- | --- | --- |
| `LABD_LISTEN_ADDRESS` | `127.0.0.1:8445` | адрес API; в production - адрес шлюза Docker-сети приложения |
| `LABD_ALLOWED_CLIENTS` | `127.0.0.0/8,::1/128` | сети, из которых принимаются запросы; остальные получают 401 |
| `LABD_LXD_SOCKET`, `LABD_LXD_PROJECT` | `/var/snap/lxd/common/lxd/unix.socket`, `default` | LXD |
| `LABD_STATE_FILE` | `/var/lib/lincodex-labd/labs.json` | файл состояния |
| `LABD_MEMORY_BUDGET_MIB`, `LABD_MAX_LABS` | `3072`, `0` (без отдельного лимита) | емкость |
| `LABD_MAX_LIFETIME`, `LABD_PROVISION_TIMEOUT` | `2h`, `5m` | время жизни и подготовки |
| `LABD_SWEEP_INTERVAL`, `LABD_RECONCILE_INTERVAL`, `LABD_DELETED_RETENTION` | `15s`, `5m`, `1h` | удаление |
| `LABD_CONSOLE_TOKEN_TTL`, `LABD_CHECK_TIMEOUT`, `LABD_RETRY_AFTER` | `1m`, `1m`, `30s` | токены, проверка, Retry-After |
| `LABD_MGMT_NETWORK`, `LABD_MGMT_SUBNET`, `LABD_MGMT_HOST_ADDRESS`, `LABD_MGMT_FIRST_ADDRESS` | `lxdbr-labmgmt`, `10.81.0.0/24`, `10.81.0.1`, `10.81.0.16` | план управления из `deploy/labs/lxd-preseed.yaml` |
## Запуск на хосте
labd работает как systemd-сервис на app-хосте, не в Docker: `deploy/labs/lincodex-labd.service` и пример настроек `deploy/labs/labd.env.example` (без секретов). Сервис запускается от отдельного пользователя `lincodex-labd` с дополнительной группой `lxd`, без capabilities, с `ProtectSystem=strict`, `StateDirectory=lincodex-labd` и правом записи только на сокет LXD. Сертификат, ключ и токен лежат в `/etc/lincodex-labd/` с правами только для этого пользователя. Порт API открывается в межсетевом экране хоста только для сети приложения. Компрометация labd остается компрометацией хоста: группа `lxd` дает root через LXD API, поэтому labd не принимает ничего, кроме описанного контракта, и не исполняет данные запроса.
Перед выкаткой на хосте нужно проверить то, что в этой сборке не проверялось: что мост без адреса не получает IPv6 link-local (LXD отключает IPv6 на таком мосту), что пересылаемый между узлами L2-трафик не режется цепочкой FORWARD Docker при включенном `br_netfilter`, что `security.port_isolation` и `cloud-init:config` поддерживаются версией LXD, и как образ CHR применяет скрипт из cloud-init user-data. Checker шаблона должен проверять подлинность узла (закрепленный ключ хоста SSH или учетные данные этой лаборатории), потому что узел другой лаборатории может ответить ARP на чужой адрес управления.
## Проверки
Из корня: `make -C labd check` запускает форматирование, сборку для Linux, unit-тесты с race detector, проверку generated-кода и lint. Тесты используют LXD в памяти: создание и удаление лаборатории (узлы на изолированных мостах и их полное исчезновение), перезапуск labd посреди жизни лаборатории и удаление по таймеру после него, перезапуск во время подготовки, сироты, отказ удаления и повтор, лимит емкости и 503 для лишней лаборатории. `make -C labd test-live` создает и удаляет один мост и одну машину на настоящем LXD; без `LABD_LIVE_SOCKET` и `LABD_LIVE_SOURCE` он не запускается, и его нельзя направлять на production-хост.
Сети и подготовка хоста: [DEPLOYMENT.md](../docs/ru/DEPLOYMENT.md#лаборатории-и-labd).