feat(labs): add the labd provisioner with clone pool, time to live and limits
This commit is contained in:
1 parent
9fdaa62b9b
commit
9385b2ddd4
53 files changed
+14675
-6
No files matched your search
@@ -13,7 +13,7 @@ install: ## Install project dependencies
|
|||||||
printf '\n==> %s install\n' "$$part"; \
|
printf '\n==> %s install\n' "$$part"; \
|
||||||
$(MAKE) -C "$$part" install || status=1; \
|
$(MAKE) -C "$$part" install || status=1; \
|
||||||
done; \
|
done; \
|
||||||
for part in backend runner; do \
|
for part in backend runner labd; do \
|
||||||
printf '\n==> %s deps\n' "$$part"; \
|
printf '\n==> %s deps\n' "$$part"; \
|
||||||
$(MAKE) -C "$$part" deps || status=1; \
|
$(MAKE) -C "$$part" deps || status=1; \
|
||||||
done; \
|
done; \
|
||||||
@@ -23,37 +23,38 @@ generate: ## Generate shared contracts, Go and TypeScript code, and Python model
|
|||||||
$(MAKE) -C api bundle
|
$(MAKE) -C api bundle
|
||||||
API_PREPARED=1 $(MAKE) -C backend generate
|
API_PREPARED=1 $(MAKE) -C backend generate
|
||||||
API_PREPARED=1 $(MAKE) -C runner generate
|
API_PREPARED=1 $(MAKE) -C runner generate
|
||||||
|
API_PREPARED=1 $(MAKE) -C labd generate
|
||||||
API_PREPARED=1 $(MAKE) -C frontend generate
|
API_PREPARED=1 $(MAKE) -C frontend generate
|
||||||
API_PREPARED=1 $(MAKE) -C ml generate
|
API_PREPARED=1 $(MAKE) -C ml generate
|
||||||
|
|
||||||
gen: generate ## Alias for generate
|
gen: generate ## Alias for generate
|
||||||
|
|
||||||
fmt: ## Format all project parts
|
fmt: ## Format all project parts
|
||||||
@status=0; for part in api backend runner frontend ml; do \
|
@status=0; for part in api backend runner labd frontend ml; do \
|
||||||
printf '\n==> %s fmt\n' "$$part"; \
|
printf '\n==> %s fmt\n' "$$part"; \
|
||||||
$(MAKE) -C "$$part" fmt || status=1; \
|
$(MAKE) -C "$$part" fmt || status=1; \
|
||||||
done; exit "$$status"
|
done; exit "$$status"
|
||||||
|
|
||||||
fmt-check: ## Check formatting without changing files
|
fmt-check: ## Check formatting without changing files
|
||||||
@status=0; for part in api backend runner frontend ml; do \
|
@status=0; for part in api backend runner labd frontend ml; do \
|
||||||
printf '\n==> %s fmt-check\n' "$$part"; \
|
printf '\n==> %s fmt-check\n' "$$part"; \
|
||||||
$(MAKE) -C "$$part" fmt-check || status=1; \
|
$(MAKE) -C "$$part" fmt-check || status=1; \
|
||||||
done; exit "$$status"
|
done; exit "$$status"
|
||||||
|
|
||||||
lint: ## Run configured linters
|
lint: ## Run configured linters
|
||||||
@status=0; for part in api backend runner frontend ml; do \
|
@status=0; for part in api backend runner labd frontend ml; do \
|
||||||
printf '\n==> %s lint\n' "$$part"; \
|
printf '\n==> %s lint\n' "$$part"; \
|
||||||
$(MAKE) -C "$$part" lint || status=1; \
|
$(MAKE) -C "$$part" lint || status=1; \
|
||||||
done; exit "$$status"
|
done; exit "$$status"
|
||||||
|
|
||||||
test: ## Run unit and component tests
|
test: ## Run unit and component tests
|
||||||
@status=0; for part in backend runner frontend ml; do \
|
@status=0; for part in backend runner labd frontend ml; do \
|
||||||
printf '\n==> %s test\n' "$$part"; \
|
printf '\n==> %s test\n' "$$part"; \
|
||||||
$(MAKE) -C "$$part" test || status=1; \
|
$(MAKE) -C "$$part" test || status=1; \
|
||||||
done; exit "$$status"
|
done; exit "$$status"
|
||||||
|
|
||||||
check: ## Run local checks for code, docs, deployment, and observability
|
check: ## Run local checks for code, docs, deployment, and observability
|
||||||
@status=0; for part in api backend runner frontend ml deploy observability; do \
|
@status=0; for part in api backend runner labd frontend ml deploy observability; do \
|
||||||
printf '\n==> %s check\n' "$$part"; \
|
printf '\n==> %s check\n' "$$part"; \
|
||||||
$(MAKE) -C "$$part" check || status=1; \
|
$(MAKE) -C "$$part" check || status=1; \
|
||||||
done; \
|
done; \
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Example settings of labd for /etc/lincodex-labd/labd.env on the app host.
|
||||||
|
# The file holds no secret: the token, certificate, and key are separate files
|
||||||
|
# that only the lincodex-labd user can read. See labd/README.en.md.
|
||||||
|
|
||||||
|
# Listen on the gateway of the application Docker network, so that only the
|
||||||
|
# backend reaches the API; the host firewall opens the port to that network.
|
||||||
|
LABD_LISTEN_ADDRESS=172.29.79.1:8445
|
||||||
|
LABD_ALLOWED_CLIENTS=172.29.79.0/24
|
||||||
|
LABD_TLS_CERT_FILE=/etc/lincodex-labd/tls.crt
|
||||||
|
LABD_TLS_KEY_FILE=/etc/lincodex-labd/tls.key
|
||||||
|
LABD_API_TOKEN_FILE=/etc/lincodex-labd/api-token
|
||||||
|
|
||||||
|
LABD_LXD_SOCKET=/var/snap/lxd/common/lxd/unix.socket
|
||||||
|
LABD_LXD_PROJECT=default
|
||||||
|
LABD_STATE_FILE=/var/lib/lincodex-labd/labs.json
|
||||||
|
|
||||||
|
# Guest memory of all labs together. One lincodex-lab-small node is 768 MiB;
|
||||||
|
# leave room for the core stack and the runner VM.
|
||||||
|
LABD_MEMORY_BUDGET_MIB=3072
|
||||||
|
LABD_MAX_LABS=0
|
||||||
|
LABD_MAX_LIFETIME=2h
|
||||||
|
|
||||||
|
LABD_MGMT_NETWORK=lxdbr-labmgmt
|
||||||
|
LABD_MGMT_SUBNET=10.81.0.0/24
|
||||||
|
LABD_MGMT_HOST_ADDRESS=10.81.0.1
|
||||||
|
LABD_MGMT_FIRST_ADDRESS=10.81.0.16
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# systemd unit of the lab provisioner labd on the app host.
|
||||||
|
#
|
||||||
|
# labd is the only process that talks to the LXD API. The lxd group is
|
||||||
|
# equivalent to root on the host, so the unit gives the process nothing else:
|
||||||
|
# no capabilities, a read-only file system except its state directory and the
|
||||||
|
# LXD socket, and no other secrets than its own TLS pair and API token in
|
||||||
|
# /etc/lincodex-labd/ (owner lincodex-labd, mode 0600). The settings come from
|
||||||
|
# /etc/lincodex-labd/labd.env; see deploy/labs/labd.env.example.
|
||||||
|
[Unit]
|
||||||
|
Description=Lincodex lab provisioner (labd)
|
||||||
|
Wants=network-online.target
|
||||||
|
After=network-online.target snap.lxd.daemon.service docker.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=lincodex-labd
|
||||||
|
Group=lincodex-labd
|
||||||
|
SupplementaryGroups=lxd
|
||||||
|
EnvironmentFile=/etc/lincodex-labd/labd.env
|
||||||
|
ExecStart=/usr/local/bin/lincodex-labd
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=5s
|
||||||
|
# Longer than LABD_SHUTDOWN_TIMEOUT, so a drain finishes before SIGKILL. A
|
||||||
|
# kill is still safe: the next start finishes every lab from the state file.
|
||||||
|
TimeoutStopSec=45s
|
||||||
|
StateDirectory=lincodex-labd
|
||||||
|
StateDirectoryMode=0700
|
||||||
|
UMask=0077
|
||||||
|
ReadWritePaths=/var/snap/lxd/common/lxd/unix.socket
|
||||||
|
NoNewPrivileges=yes
|
||||||
|
CapabilityBoundingSet=
|
||||||
|
AmbientCapabilities=
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=yes
|
||||||
|
PrivateTmp=yes
|
||||||
|
PrivateDevices=yes
|
||||||
|
ProtectKernelTunables=yes
|
||||||
|
ProtectKernelModules=yes
|
||||||
|
ProtectKernelLogs=yes
|
||||||
|
ProtectControlGroups=yes
|
||||||
|
ProtectClock=yes
|
||||||
|
ProtectHostname=yes
|
||||||
|
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
|
||||||
|
RestrictNamespaces=yes
|
||||||
|
RestrictRealtime=yes
|
||||||
|
RestrictSUIDSGID=yes
|
||||||
|
LockPersonality=yes
|
||||||
|
MemoryDenyWriteExecute=yes
|
||||||
|
SystemCallArchitectures=native
|
||||||
|
SystemCallFilter=@system-service
|
||||||
|
# A refused system call fails with EPERM instead of killing the process.
|
||||||
|
SystemCallErrorNumber=EPERM
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
/bin/
|
||||||
|
|
||||||
|
# Go build and test output
|
||||||
|
*.exe
|
||||||
|
*.test
|
||||||
|
*.out
|
||||||
|
*.prof
|
||||||
|
*.cover
|
||||||
|
*.pprof
|
||||||
|
coverage.*
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
version: "2"
|
||||||
|
|
||||||
|
run:
|
||||||
|
timeout: 5m
|
||||||
|
tests: true
|
||||||
|
|
||||||
|
linters:
|
||||||
|
default: standard
|
||||||
|
enable:
|
||||||
|
- asasalint
|
||||||
|
- asciicheck
|
||||||
|
- bidichk
|
||||||
|
- bodyclose
|
||||||
|
- contextcheck
|
||||||
|
- copyloopvar
|
||||||
|
- durationcheck
|
||||||
|
- embeddedstructfieldcheck
|
||||||
|
- errname
|
||||||
|
- errorlint
|
||||||
|
- exhaustive
|
||||||
|
- exptostd
|
||||||
|
- fatcontext
|
||||||
|
- gocheckcompilerdirectives
|
||||||
|
- gochecknoinits
|
||||||
|
- gochecksumtype
|
||||||
|
- gocritic
|
||||||
|
- gocyclo
|
||||||
|
- gosec
|
||||||
|
- goprintffuncname
|
||||||
|
- inamedparam
|
||||||
|
- iotamixing
|
||||||
|
- loggercheck
|
||||||
|
- makezero
|
||||||
|
- mirror
|
||||||
|
- misspell
|
||||||
|
- musttag
|
||||||
|
- nakedret
|
||||||
|
- nilerr
|
||||||
|
- nilnesserr
|
||||||
|
- noctx
|
||||||
|
- nolintlint
|
||||||
|
- prealloc
|
||||||
|
- predeclared
|
||||||
|
- reassign
|
||||||
|
- revive
|
||||||
|
- sloglint
|
||||||
|
- tagalign
|
||||||
|
- testableexamples
|
||||||
|
- testifylint
|
||||||
|
- thelper
|
||||||
|
- unconvert
|
||||||
|
- unparam
|
||||||
|
- wastedassign
|
||||||
|
- whitespace
|
||||||
|
|
||||||
|
settings:
|
||||||
|
gocyclo:
|
||||||
|
min-complexity: 15
|
||||||
|
govet:
|
||||||
|
enable-all: true
|
||||||
|
disable:
|
||||||
|
- fieldalignment
|
||||||
|
- shadow
|
||||||
|
revive:
|
||||||
|
rules:
|
||||||
|
- name: blank-imports
|
||||||
|
- name: context-as-argument
|
||||||
|
- name: context-keys-type
|
||||||
|
- name: error-return
|
||||||
|
- name: error-strings
|
||||||
|
- name: error-naming
|
||||||
|
- name: var-declaration
|
||||||
|
- name: range
|
||||||
|
- name: receiver-naming
|
||||||
|
- name: time-naming
|
||||||
|
- name: indent-error-flow
|
||||||
|
- name: errorf
|
||||||
|
- name: empty-block
|
||||||
|
- name: superfluous-else
|
||||||
|
- name: unused-parameter
|
||||||
|
- name: unreachable-code
|
||||||
|
- name: redefines-builtin-id
|
||||||
|
nolintlint:
|
||||||
|
allow-unused: false
|
||||||
|
require-explanation: true
|
||||||
|
require-specific: true
|
||||||
|
gosec:
|
||||||
|
excludes:
|
||||||
|
- G104
|
||||||
|
staticcheck:
|
||||||
|
checks:
|
||||||
|
- all
|
||||||
|
testifylint:
|
||||||
|
enable-all: true
|
||||||
|
disable:
|
||||||
|
- go-require
|
||||||
|
|
||||||
|
exclusions:
|
||||||
|
generated: strict
|
||||||
|
paths:
|
||||||
|
- internal/api/
|
||||||
|
presets:
|
||||||
|
- comments
|
||||||
|
- common-false-positives
|
||||||
|
rules:
|
||||||
|
# Error locations use actual Go identifiers, including exported type names.
|
||||||
|
- linters:
|
||||||
|
- staticcheck
|
||||||
|
text: 'ST1005: error strings should not be capitalized'
|
||||||
|
source: '(fmt\.Errorf|errors\.New)\("[A-Z][A-Za-z0-9]*\.[A-Za-z0-9]+ - '
|
||||||
|
- path: _test\.go
|
||||||
|
linters:
|
||||||
|
- gocyclo
|
||||||
|
- gosec
|
||||||
|
- errcheck
|
||||||
|
- dupl
|
||||||
|
# Lab workers outlive the request that starts them and run on the
|
||||||
|
# lifetime context of the manager, which Close cancels.
|
||||||
|
- path: internal/pool/
|
||||||
|
linters:
|
||||||
|
- contextcheck
|
||||||
|
- path: _test\.go
|
||||||
|
text: net/http/httptest\.NewRequest must not be called
|
||||||
|
linters:
|
||||||
|
- noctx
|
||||||
|
|
||||||
|
formatters:
|
||||||
|
enable:
|
||||||
|
- gofmt
|
||||||
|
- goimports
|
||||||
|
exclusions:
|
||||||
|
generated: strict
|
||||||
|
paths:
|
||||||
|
- internal/api/
|
||||||
|
|
||||||
|
issues:
|
||||||
|
max-issues-per-linter: 0
|
||||||
|
max-same-issues: 0
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
SHELL := /usr/bin/env bash
|
||||||
|
.DEFAULT_GOAL := help
|
||||||
|
|
||||||
|
GO ?= go
|
||||||
|
GO_TOOL := $(GO) tool
|
||||||
|
API_DIR := $(abspath ../api)
|
||||||
|
API_PREPARED ?= 0
|
||||||
|
# labd runs only on the Linux app host, so lint analyzes Linux code. The
|
||||||
|
# linter binary is built for the host first; GOOS then selects only the
|
||||||
|
# analyzed packages.
|
||||||
|
LINT_GOOS ?= linux
|
||||||
|
GOLANGCI_LINT := bin/golangci-lint
|
||||||
|
# Architecture of the labd binary for the app host.
|
||||||
|
LABD_GOARCH ?= amd64
|
||||||
|
OGEN_ARGS := -config codegen/ogen.yml --package api --clean ../api/labd/openapi.bundle.yml
|
||||||
|
|
||||||
|
##@ Build
|
||||||
|
|
||||||
|
.PHONY: build
|
||||||
|
build: ## Build the labd binary for the Linux app host (LABD_GOARCH, default amd64)
|
||||||
|
@mkdir -p bin
|
||||||
|
CGO_ENABLED=0 GOOS=linux GOARCH=$(LABD_GOARCH) $(GO) build -buildvcs=false -trimpath -o bin/lincodex-labd ./cmd/labd
|
||||||
|
|
||||||
|
.PHONY: deps install
|
||||||
|
deps: ## Download pinned Go module dependencies
|
||||||
|
$(GO) mod download
|
||||||
|
|
||||||
|
install: deps ## Install module-pinned Go tools without global changes
|
||||||
|
@$(GO) version
|
||||||
|
@$(GO_TOOL) ogen --version
|
||||||
|
@$(GO_TOOL) golangci-lint version
|
||||||
|
|
||||||
|
.PHONY: tidy
|
||||||
|
tidy: ## Tidy application and tool dependencies
|
||||||
|
$(GO) mod tidy
|
||||||
|
|
||||||
|
.PHONY: clean
|
||||||
|
clean: ## Remove local build and test artifacts
|
||||||
|
rm -rf bin coverage.out
|
||||||
|
|
||||||
|
##@ Code generation
|
||||||
|
|
||||||
|
.PHONY: generate gen
|
||||||
|
generate gen: ## Generate the ogen server from the lab provisioner contract
|
||||||
|
@if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi
|
||||||
|
$(GO_TOOL) ogen --target internal/api $(OGEN_ARGS)
|
||||||
|
|
||||||
|
.PHONY: check-generated
|
||||||
|
check-generated: ## Check the generated server against the bundled contract without rewriting it
|
||||||
|
@set -euo pipefail; mkdir -p bin; temporary_dir=$$(mktemp -d "$(CURDIR)/bin/ogen-check.XXXXXX"); trap 'rm -rf "$$temporary_dir"' EXIT; \
|
||||||
|
$(GO_TOOL) ogen --target "$$temporary_dir" $(OGEN_ARGS) >/dev/null 2>&1; \
|
||||||
|
diff -r internal/api "$$temporary_dir"
|
||||||
|
|
||||||
|
##@ Format, lint, and test
|
||||||
|
|
||||||
|
.PHONY: $(GOLANGCI_LINT)
|
||||||
|
$(GOLANGCI_LINT):
|
||||||
|
@mkdir -p bin
|
||||||
|
$(GO) build -o $(GOLANGCI_LINT) github.com/golangci/golangci-lint/v2/cmd/golangci-lint
|
||||||
|
|
||||||
|
.PHONY: fmt
|
||||||
|
fmt: $(GOLANGCI_LINT) ## Format Go sources
|
||||||
|
GOOS=$(LINT_GOOS) $(GOLANGCI_LINT) fmt ./...
|
||||||
|
|
||||||
|
.PHONY: fmt-check
|
||||||
|
fmt-check: $(GOLANGCI_LINT) ## Check Go formatting without modifying files
|
||||||
|
@unformatted=$$(gofmt -l $$(find . -name '*.go' -type f -not -path './bin/*')); \
|
||||||
|
if [ -n "$$unformatted" ]; then printf '%s\n' "$$unformatted"; exit 1; fi
|
||||||
|
@formatter_diff=$$(GOOS=$(LINT_GOOS) $(GOLANGCI_LINT) fmt --diff ./...); \
|
||||||
|
if [ -n "$$formatter_diff" ]; then printf '%s\n' "$$formatter_diff"; exit 1; fi
|
||||||
|
|
||||||
|
.PHONY: lint
|
||||||
|
lint: $(GOLANGCI_LINT) ## Run golangci-lint for Linux
|
||||||
|
GOOS=$(LINT_GOOS) $(GOLANGCI_LINT) run ./...
|
||||||
|
|
||||||
|
.PHONY: test
|
||||||
|
test: ## Run unit tests with the race detector against the in-memory LXD fake
|
||||||
|
$(GO) test -race -count=1 ./...
|
||||||
|
|
||||||
|
.PHONY: test-live
|
||||||
|
test-live: ## Create and delete one lab on a real LXD (set LABD_LIVE_SOCKET and LABD_LIVE_SOURCE; never the production host)
|
||||||
|
@if [ -z "$$LABD_LIVE_SOCKET" ] || [ -z "$$LABD_LIVE_SOURCE" ]; then \
|
||||||
|
echo 'set LABD_LIVE_SOCKET and LABD_LIVE_SOURCE (instance/snapshot), optionally LABD_LIVE_PROFILE and LABD_LIVE_PROJECT' >&2; exit 2; \
|
||||||
|
fi
|
||||||
|
$(GO) test -count=1 -v -run '^TestLiveLXD' ./internal/lxd/
|
||||||
|
|
||||||
|
.PHONY: check
|
||||||
|
check: ## Run formatting, build, unit, generated drift, and lint checks
|
||||||
|
$(MAKE) --no-print-directory fmt-check
|
||||||
|
$(MAKE) --no-print-directory build
|
||||||
|
$(MAKE) --no-print-directory test
|
||||||
|
$(MAKE) --no-print-directory check-generated
|
||||||
|
$(MAKE) --no-print-directory lint
|
||||||
|
|
||||||
|
##@ Help
|
||||||
|
|
||||||
|
.PHONY: help
|
||||||
|
help: ## Show available targets
|
||||||
|
@awk 'BEGIN{FS=":.*##"; printf "\nUsage:\n make -C labd <target>\n"} /^[a-zA-Z0-9_-]+:.*##/ {printf " %-16s %s\n", $$1, $$2} /^##@/ {printf "\n%s\n", substr($$0, 5)}' $(MAKEFILE_LIST)
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# Lab provisioner (labd)
|
||||||
|
|
||||||
|
[Русский](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.
|
||||||
|
|
||||||
|
- `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`).
|
||||||
|
|
||||||
|
## How a lab works
|
||||||
|
|
||||||
|
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`.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
## Settings
|
||||||
|
|
||||||
|
`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.
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# Провиженер лабораторий (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 их пока не подключают.
|
||||||
|
|
||||||
|
- `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`).
|
||||||
|
|
||||||
|
## Как работает лаборатория
|
||||||
|
|
||||||
|
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-объекта и исчезает после последнего. При старте лаборатория в `provisioning` становится `failed` (`interrupted`) и удаляется; таймеры остальных живут в файле и срабатывают при первом sweep. Сверка удаляет машины и мосты с префиксом и меткой labd, которых нет ни в одной записи; объект с префиксом, но без метки, только попадает в лог. labd не готов (`/readyz` 503), пока первая сверка не прошла.
|
||||||
|
|
||||||
|
Емкость: лаборатория допускается, только если память всех ее узлов помещается в `LABD_MEMORY_BUDGET_MIB` вместе с текущими лабораториями (и, если задан, в `LABD_MAX_LABS`). Иначе ответ 503 `lab_pool_busy` с Retry-After, ничего не сохраняется. Шаблон, который не помещается в бюджет даже один, не дает labd запуститься. Готовых заранее запущенных узлов нет: клон снимка дешев, а каждый узел должен загрузиться со своим вариантом.
|
||||||
|
|
||||||
|
Хранилище: JSON-файл, который при каждом изменении целиком пишется во временный файл, fsync, rename и fsync каталога. Лабораторий десятки, поэтому этого хватает без SQLite, cgo и новых зависимостей, а файл читается при разборе инцидента. В файле есть seed вариантов, поэтому он `0600` в каталоге пользователя labd. Поврежденный файл останавливает старт: labd не должен забыть лаборатории, объекты которых еще могут существовать.
|
||||||
|
|
||||||
|
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`, а не проваленная проверка.
|
||||||
|
|
||||||
|
## Настройки
|
||||||
|
|
||||||
|
Переменные `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-хост.
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
// Command labd is the lab provisioner: the only component of Lincodex that
|
||||||
|
// talks to the LXD API. It serves the internal api/labd contract.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"lincodex/labd/internal/app"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
if err := app.Run(); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "labd:", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
generator:
|
||||||
|
features:
|
||||||
|
disable:
|
||||||
|
- paths/client
|
||||||
|
- webhooks/client
|
||||||
+243
@@ -0,0 +1,243 @@
|
|||||||
|
module lincodex/labd
|
||||||
|
|
||||||
|
go 1.26.9
|
||||||
|
|
||||||
|
tool (
|
||||||
|
github.com/golangci/golangci-lint/v2/cmd/golangci-lint
|
||||||
|
github.com/ogen-go/ogen/cmd/ogen
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/go-faster/errors v0.8.0
|
||||||
|
github.com/go-faster/jx v1.2.0
|
||||||
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/ogen-go/ogen v1.24.0
|
||||||
|
go.opentelemetry.io/otel v1.45.0
|
||||||
|
go.opentelemetry.io/otel/metric v1.45.0
|
||||||
|
go.opentelemetry.io/otel/trace v1.45.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
4d63.com/gocheckcompilerdirectives v1.4.0 // indirect
|
||||||
|
4d63.com/gochecknoglobals v0.2.2 // indirect
|
||||||
|
charm.land/lipgloss/v2 v2.0.6 // indirect
|
||||||
|
codeberg.org/chavacava/garif v0.2.1 // indirect
|
||||||
|
codeberg.org/polyfloyd/go-errorlint v1.9.0 // indirect
|
||||||
|
dev.gaijin.team/go/exhaustruct/v4 v4.0.0 // indirect
|
||||||
|
dev.gaijin.team/go/exhaustruct/v5 v5.2.0 // indirect
|
||||||
|
dev.gaijin.team/go/golib v0.8.1 // indirect
|
||||||
|
github.com/4meepo/tagalign v1.4.4 // indirect
|
||||||
|
github.com/Abirdcfly/dupword v0.1.8 // indirect
|
||||||
|
github.com/AdminBenni/iota-mixing v1.0.0 // indirect
|
||||||
|
github.com/AlwxSin/noinlineerr v1.0.6 // indirect
|
||||||
|
github.com/Antonboom/errname v1.1.2 // indirect
|
||||||
|
github.com/Antonboom/nilnil v1.1.2 // indirect
|
||||||
|
github.com/Antonboom/testifylint v1.6.4 // indirect
|
||||||
|
github.com/BurntSushi/toml v1.6.0 // indirect
|
||||||
|
github.com/ClickHouse/clickhouse-go-linter v1.2.1 // indirect
|
||||||
|
github.com/Djarvur/go-err113 v0.1.1 // indirect
|
||||||
|
github.com/Masterminds/semver/v3 v3.5.0 // indirect
|
||||||
|
github.com/MirrexOne/unqueryvet v1.5.4 // indirect
|
||||||
|
github.com/OpenPeeDeeP/depguard/v2 v2.2.1 // indirect
|
||||||
|
github.com/alecthomas/chroma/v2 v2.27.0 // indirect
|
||||||
|
github.com/alecthomas/go-check-sumtype v0.5.1-0.20260828200218-ae6904d28606 // indirect
|
||||||
|
github.com/alexkohler/nakedret/v2 v2.0.6 // indirect
|
||||||
|
github.com/alexkohler/prealloc v1.1.0 // indirect
|
||||||
|
github.com/alfatraining/structtag v1.0.0 // indirect
|
||||||
|
github.com/alingse/asasalint v0.0.11 // indirect
|
||||||
|
github.com/alingse/nilnesserr v0.2.0 // indirect
|
||||||
|
github.com/ashanbrown/forbidigo/v2 v2.3.1 // indirect
|
||||||
|
github.com/ashanbrown/makezero/v2 v2.2.1 // indirect
|
||||||
|
github.com/beorn7/perks v1.0.1 // indirect
|
||||||
|
github.com/bkielbasa/cyclop v1.2.3 // indirect
|
||||||
|
github.com/blizzy78/varnamelen v0.8.0 // indirect
|
||||||
|
github.com/bombsimon/wsl/v4 v4.7.0 // indirect
|
||||||
|
github.com/bombsimon/wsl/v5 v5.9.0 // indirect
|
||||||
|
github.com/breml/bidichk v0.3.3 // indirect
|
||||||
|
github.com/breml/errchkjson v0.4.1 // indirect
|
||||||
|
github.com/butuzov/ireturn v0.4.1 // indirect
|
||||||
|
github.com/butuzov/mirror v1.3.3 // indirect
|
||||||
|
github.com/catenacyber/perfsprint v0.10.1 // indirect
|
||||||
|
github.com/ccojocar/zxcvbn-go v1.0.4 // indirect
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||||
|
github.com/charithe/durationcheck v0.0.11 // indirect
|
||||||
|
github.com/charmbracelet/colorprofile v0.4.3 // indirect
|
||||||
|
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 // indirect
|
||||||
|
github.com/charmbracelet/x/ansi v0.11.8 // indirect
|
||||||
|
github.com/charmbracelet/x/term v0.2.2 // indirect
|
||||||
|
github.com/charmbracelet/x/termios v0.1.1 // indirect
|
||||||
|
github.com/charmbracelet/x/windows v0.2.2 // indirect
|
||||||
|
github.com/ckaznocha/intrange v0.3.1 // indirect
|
||||||
|
github.com/clipperhouse/displaywidth v0.11.0 // indirect
|
||||||
|
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
|
||||||
|
github.com/curioswitch/go-reassign v0.3.0 // indirect
|
||||||
|
github.com/daixiang0/gci v0.13.7 // indirect
|
||||||
|
github.com/dave/dst v0.27.3 // indirect
|
||||||
|
github.com/denis-tingaikin/go-header v0.5.0 // indirect
|
||||||
|
github.com/dlclark/regexp2 v1.12.0 // indirect
|
||||||
|
github.com/dlclark/regexp2/v2 v2.2.1 // indirect
|
||||||
|
github.com/ettle/strcase v0.2.0 // indirect
|
||||||
|
github.com/fatih/color v1.19.0 // indirect
|
||||||
|
github.com/fatih/structtag v1.2.0 // indirect
|
||||||
|
github.com/firefart/nonamedreturns v1.0.8 // indirect
|
||||||
|
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||||
|
github.com/fzipp/gocyclo v0.6.0 // indirect
|
||||||
|
github.com/ghodss/yaml v1.0.0 // indirect
|
||||||
|
github.com/ghostiam/protogetter v1.0.1 // indirect
|
||||||
|
github.com/go-critic/go-critic v0.15.0 // indirect
|
||||||
|
github.com/go-faster/yaml v0.4.6 // indirect
|
||||||
|
github.com/go-logr/logr v1.4.4 // indirect
|
||||||
|
github.com/go-logr/stdr v1.2.2 // indirect
|
||||||
|
github.com/go-toolsmith/astcast v1.1.0 // indirect
|
||||||
|
github.com/go-toolsmith/astcopy v1.1.0 // indirect
|
||||||
|
github.com/go-toolsmith/astequal v1.2.0 // indirect
|
||||||
|
github.com/go-toolsmith/astfmt v1.1.0 // indirect
|
||||||
|
github.com/go-toolsmith/astp v1.1.0 // indirect
|
||||||
|
github.com/go-toolsmith/strparse v1.1.0 // indirect
|
||||||
|
github.com/go-toolsmith/typep v1.1.0 // indirect
|
||||||
|
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
|
||||||
|
github.com/go-xmlfmt/xmlfmt v1.1.3 // indirect
|
||||||
|
github.com/gobwas/glob v0.2.3 // indirect
|
||||||
|
github.com/godoc-lint/godoc-lint v0.11.4 // indirect
|
||||||
|
github.com/gofrs/flock v0.13.1 // indirect
|
||||||
|
github.com/golang/protobuf v1.5.3 // indirect
|
||||||
|
github.com/golangci/asciicheck v0.5.0 // indirect
|
||||||
|
github.com/golangci/canonicalheader v0.0.0-20260827115959-a25c71c521f6 // indirect
|
||||||
|
github.com/golangci/dupl v0.0.0-20260401084720-c99c5cf5c202 // indirect
|
||||||
|
github.com/golangci/go-printf-func-name v0.1.1 // indirect
|
||||||
|
github.com/golangci/gofmt v0.0.0-20260820135601-e84e05053792 // indirect
|
||||||
|
github.com/golangci/golangci-lint/v2 v2.14.0 // indirect
|
||||||
|
github.com/golangci/golines v0.15.0 // indirect
|
||||||
|
github.com/golangci/misspell v0.8.0 // indirect
|
||||||
|
github.com/golangci/plugin-module-register v0.1.2 // indirect
|
||||||
|
github.com/golangci/revgrep v0.8.0 // indirect
|
||||||
|
github.com/golangci/rowserrcheck v0.0.0-20260419091836-c5f79b8a11ba // indirect
|
||||||
|
github.com/golangci/swaggoswag v0.0.0-20250504205917-77f2aca3143e // indirect
|
||||||
|
github.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e // indirect
|
||||||
|
github.com/google/go-cmp v0.7.0 // indirect
|
||||||
|
github.com/gordonklaus/ineffassign v0.2.0 // indirect
|
||||||
|
github.com/gostaticanalysis/analysisutil v0.7.1 // indirect
|
||||||
|
github.com/gostaticanalysis/comment v1.5.0 // indirect
|
||||||
|
github.com/gostaticanalysis/forcetypeassert v0.2.0 // indirect
|
||||||
|
github.com/gostaticanalysis/nilerr v0.1.2 // indirect
|
||||||
|
github.com/hashicorp/go-immutable-radix/v2 v2.1.0 // indirect
|
||||||
|
github.com/hashicorp/go-version v1.9.0 // indirect
|
||||||
|
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
||||||
|
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||||
|
github.com/hexops/gotextdiff v1.0.3 // indirect
|
||||||
|
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||||
|
github.com/jgautheron/goconst v1.11.0 // indirect
|
||||||
|
github.com/jjti/go-spancheck v0.6.5 // indirect
|
||||||
|
github.com/julz/importas v0.2.0 // indirect
|
||||||
|
github.com/karamaru-alpha/copyloopvar v1.2.2 // indirect
|
||||||
|
github.com/kisielk/errcheck v1.20.0 // indirect
|
||||||
|
github.com/kkHAIKE/contextcheck v1.1.6 // indirect
|
||||||
|
github.com/kulti/thelper v0.7.1 // indirect
|
||||||
|
github.com/kunwardeep/paralleltest v1.0.15 // indirect
|
||||||
|
github.com/ldez/exptostd v0.4.5 // indirect
|
||||||
|
github.com/ldez/gomoddirectives v0.10.0 // indirect
|
||||||
|
github.com/ldez/grignotin v0.10.1 // indirect
|
||||||
|
github.com/ldez/structtags v0.6.1 // indirect
|
||||||
|
github.com/ldez/tagliatelle v0.8.0 // indirect
|
||||||
|
github.com/ldez/usetesting v0.5.0 // indirect
|
||||||
|
github.com/leonklingele/grouper v1.1.2 // indirect
|
||||||
|
github.com/lucasb-eyer/go-colorful v1.4.1 // indirect
|
||||||
|
github.com/macabu/inamedparam v0.2.0 // indirect
|
||||||
|
github.com/magiconair/properties v1.8.6 // indirect
|
||||||
|
github.com/manuelarte/embeddedstructfieldcheck v0.4.0 // indirect
|
||||||
|
github.com/manuelarte/funcorder v0.6.0 // indirect
|
||||||
|
github.com/maratori/testableexamples v1.0.1 // indirect
|
||||||
|
github.com/maratori/testpackage v1.1.2 // indirect
|
||||||
|
github.com/matoous/godox v1.1.0 // indirect
|
||||||
|
github.com/mattn/go-colorable v0.1.15 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||||
|
github.com/mattn/go-runewidth v0.0.24 // indirect
|
||||||
|
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
|
||||||
|
github.com/mgechev/revive v1.17.0 // indirect
|
||||||
|
github.com/mitchellh/go-homedir v1.1.0 // indirect
|
||||||
|
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||||
|
github.com/moricho/tparallel v0.3.2 // indirect
|
||||||
|
github.com/muesli/cancelreader v0.2.2 // indirect
|
||||||
|
github.com/nakabonne/nestif v0.3.1 // indirect
|
||||||
|
github.com/nishanths/exhaustive v0.13.0 // indirect
|
||||||
|
github.com/nishanths/predeclared v0.2.2 // indirect
|
||||||
|
github.com/nunnatsa/ginkgolinter v0.24.0 // indirect
|
||||||
|
github.com/pelletier/go-toml v1.9.5 // indirect
|
||||||
|
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
|
||||||
|
github.com/prometheus/client_golang v1.12.1 // indirect
|
||||||
|
github.com/prometheus/client_model v0.2.0 // indirect
|
||||||
|
github.com/prometheus/common v0.32.1 // indirect
|
||||||
|
github.com/prometheus/procfs v0.7.3 // indirect
|
||||||
|
github.com/quasilyte/go-ruleguard v0.4.5 // indirect
|
||||||
|
github.com/quasilyte/go-ruleguard/dsl v0.3.23 // indirect
|
||||||
|
github.com/quasilyte/gogrep v0.5.0 // indirect
|
||||||
|
github.com/quasilyte/regex/syntax v0.0.0-20210819130434-b3f0c404a727 // indirect
|
||||||
|
github.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567 // indirect
|
||||||
|
github.com/raeperd/recvcheck v0.3.1 // indirect
|
||||||
|
github.com/rivo/uniseg v0.4.7 // indirect
|
||||||
|
github.com/rogpeppe/go-internal v1.16.0 // indirect
|
||||||
|
github.com/ryancurrah/gomodguard v1.4.1 // indirect
|
||||||
|
github.com/ryancurrah/gomodguard/v2 v2.1.3 // indirect
|
||||||
|
github.com/ryanrolds/sqlclosecheck v0.6.0 // indirect
|
||||||
|
github.com/sanposhiho/wastedassign/v2 v2.1.0 // indirect
|
||||||
|
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect
|
||||||
|
github.com/sashamelentyev/interfacebloat v1.1.0 // indirect
|
||||||
|
github.com/sashamelentyev/usestdlibvars v1.29.0 // indirect
|
||||||
|
github.com/securego/gosec/v2 v2.29.0 // indirect
|
||||||
|
github.com/segmentio/asm v1.2.1 // indirect
|
||||||
|
github.com/shopspring/decimal v1.4.0 // indirect
|
||||||
|
github.com/sirupsen/logrus v1.10.2 // indirect
|
||||||
|
github.com/sivchari/containedctx v1.0.3 // indirect
|
||||||
|
github.com/sonatard/noctx v0.5.1 // indirect
|
||||||
|
github.com/sourcegraph/go-diff v0.9.0 // indirect
|
||||||
|
github.com/spf13/afero v1.15.0 // indirect
|
||||||
|
github.com/spf13/cast v1.5.0 // indirect
|
||||||
|
github.com/spf13/cobra v1.10.2 // indirect
|
||||||
|
github.com/spf13/jwalterweatherman v1.1.0 // indirect
|
||||||
|
github.com/spf13/pflag v1.0.10 // indirect
|
||||||
|
github.com/spf13/viper v1.12.0 // indirect
|
||||||
|
github.com/ssgreg/nlreturn/v2 v2.2.1 // indirect
|
||||||
|
github.com/stbenjam/no-sprintf-host-port v0.3.1 // indirect
|
||||||
|
github.com/stretchr/objx v0.5.3 // indirect
|
||||||
|
github.com/stretchr/testify v1.12.1 // indirect
|
||||||
|
github.com/subosito/gotenv v1.4.1 // indirect
|
||||||
|
github.com/tetafro/godot v1.5.6 // indirect
|
||||||
|
github.com/timakin/bodyclose v0.0.0-20260723120731-857993a2939c // indirect
|
||||||
|
github.com/timonwong/loggercheck v0.12.0 // indirect
|
||||||
|
github.com/tomarrell/wrapcheck/v2 v2.12.0 // indirect
|
||||||
|
github.com/tommy-muehle/go-mnd/v2 v2.5.1 // indirect
|
||||||
|
github.com/ultraware/funlen v0.2.0 // indirect
|
||||||
|
github.com/ultraware/whitespace v0.2.0 // indirect
|
||||||
|
github.com/uudashr/gocognit v1.2.1 // indirect
|
||||||
|
github.com/uudashr/iface v1.5.1 // indirect
|
||||||
|
github.com/xen0n/gosmopolitan v1.3.0 // indirect
|
||||||
|
github.com/xo/terminfo v1.0.0 // indirect
|
||||||
|
github.com/yagipy/maintidx v1.0.0 // indirect
|
||||||
|
github.com/yeya24/promlinter v0.3.0 // indirect
|
||||||
|
github.com/ykadowak/zerologlint v0.1.5 // indirect
|
||||||
|
github.com/yuin/goldmark v1.8.2 // indirect
|
||||||
|
gitlab.com/bosi/decorder v0.4.2 // indirect
|
||||||
|
go-simpler.org/musttag v0.14.0 // indirect
|
||||||
|
go-simpler.org/sloglint v0.12.0 // indirect
|
||||||
|
go.augendre.info/arangolint v0.4.0 // indirect
|
||||||
|
go.augendre.info/fatcontext v0.10.1 // indirect
|
||||||
|
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||||
|
go.uber.org/multierr v1.11.0 // indirect
|
||||||
|
go.uber.org/zap v1.28.0 // indirect
|
||||||
|
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||||
|
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect
|
||||||
|
golang.org/x/exp/typeparams v0.0.0-20260811152304-ee035b5b010f // indirect
|
||||||
|
golang.org/x/mod v0.41.0 // indirect
|
||||||
|
golang.org/x/net v0.59.0 // indirect
|
||||||
|
golang.org/x/sync v0.23.0 // indirect
|
||||||
|
golang.org/x/sys v0.48.0 // indirect
|
||||||
|
golang.org/x/text v0.42.0 // indirect
|
||||||
|
golang.org/x/tools v0.50.0 // indirect
|
||||||
|
google.golang.org/protobuf v1.36.12 // indirect
|
||||||
|
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||||
|
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
|
honnef.co/go/tools v0.8.1 // indirect
|
||||||
|
mvdan.cc/gofumpt v0.12.0 // indirect
|
||||||
|
mvdan.cc/unparam v0.0.0-20260823230713-2fa3d841b0c8 // indirect
|
||||||
|
)
|
||||||
+1007
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,263 @@
|
|||||||
|
// Code generated by ogen, DO NOT EDIT.
|
||||||
|
|
||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/ogen-go/ogen/middleware"
|
||||||
|
"github.com/ogen-go/ogen/ogenerrors"
|
||||||
|
"github.com/ogen-go/ogen/ogenregex"
|
||||||
|
"github.com/ogen-go/ogen/otelogen"
|
||||||
|
"go.opentelemetry.io/otel"
|
||||||
|
"go.opentelemetry.io/otel/attribute"
|
||||||
|
"go.opentelemetry.io/otel/metric"
|
||||||
|
"go.opentelemetry.io/otel/trace"
|
||||||
|
)
|
||||||
|
|
||||||
|
var regexMap = map[string]ogenregex.Regexp{
|
||||||
|
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
|
||||||
|
"^/v1/labs/[0-9a-f-]{36}/console$": ogenregex.MustCompile("^/v1/labs/[0-9a-f-]{36}/console$"),
|
||||||
|
"^[0-9a-f]{64}$": ogenregex.MustCompile("^[0-9a-f]{64}$"),
|
||||||
|
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
|
||||||
|
"^[A-Za-z0-9_-]{43}$": ogenregex.MustCompile("^[A-Za-z0-9_-]{43}$"),
|
||||||
|
"^[a-z0-9][a-z0-9-]{0,47}$": ogenregex.MustCompile("^[a-z0-9][a-z0-9-]{0,47}$"),
|
||||||
|
"^[a-z0-9][a-z0-9_-]{0,31}$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_-]{0,31}$"),
|
||||||
|
"^[a-z][a-z0-9-]{0,14}$": ogenregex.MustCompile("^[a-z][a-z0-9-]{0,14}$"),
|
||||||
|
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
|
||||||
|
}
|
||||||
|
var (
|
||||||
|
// Allocate option closure once.
|
||||||
|
serverSpanKind = trace.WithSpanKind(trace.SpanKindServer)
|
||||||
|
)
|
||||||
|
|
||||||
|
type (
|
||||||
|
optionFunc[C any] func(*C)
|
||||||
|
otelOptionFunc func(*otelConfig)
|
||||||
|
)
|
||||||
|
|
||||||
|
type otelConfig struct {
|
||||||
|
TracerProvider trace.TracerProvider
|
||||||
|
Tracer trace.Tracer
|
||||||
|
MeterProvider metric.MeterProvider
|
||||||
|
Meter metric.Meter
|
||||||
|
Attributes []attribute.KeyValue
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cfg *otelConfig) initOTEL() {
|
||||||
|
if cfg.TracerProvider == nil {
|
||||||
|
cfg.TracerProvider = otel.GetTracerProvider()
|
||||||
|
}
|
||||||
|
if cfg.MeterProvider == nil {
|
||||||
|
cfg.MeterProvider = otel.GetMeterProvider()
|
||||||
|
}
|
||||||
|
cfg.Tracer = cfg.TracerProvider.Tracer(otelogen.Name,
|
||||||
|
trace.WithInstrumentationVersion(otelogen.SemVersion()),
|
||||||
|
)
|
||||||
|
cfg.Meter = cfg.MeterProvider.Meter(otelogen.Name,
|
||||||
|
metric.WithInstrumentationVersion(otelogen.SemVersion()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrorHandler is error handler.
|
||||||
|
type ErrorHandler = ogenerrors.ErrorHandler
|
||||||
|
|
||||||
|
type serverConfig struct {
|
||||||
|
otelConfig
|
||||||
|
NotFound http.HandlerFunc
|
||||||
|
MethodNotAllowed func(w http.ResponseWriter, r *http.Request, allowed string)
|
||||||
|
ErrorHandler ErrorHandler
|
||||||
|
Prefix string
|
||||||
|
Middleware Middleware
|
||||||
|
MaxMultipartMemory int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// ServerOption is server config option.
|
||||||
|
type ServerOption interface {
|
||||||
|
applyServer(*serverConfig)
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ ServerOption = (optionFunc[serverConfig])(nil)
|
||||||
|
|
||||||
|
func (o optionFunc[C]) applyServer(c *C) {
|
||||||
|
o(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ ServerOption = (otelOptionFunc)(nil)
|
||||||
|
|
||||||
|
func (o otelOptionFunc) applyServer(c *serverConfig) {
|
||||||
|
o(&c.otelConfig)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newServerConfig(opts ...ServerOption) serverConfig {
|
||||||
|
cfg := serverConfig{
|
||||||
|
NotFound: http.NotFound,
|
||||||
|
MethodNotAllowed: nil,
|
||||||
|
ErrorHandler: ogenerrors.DefaultErrorHandler,
|
||||||
|
Middleware: nil,
|
||||||
|
MaxMultipartMemory: 32 << 20, // 32 MB
|
||||||
|
}
|
||||||
|
for _, opt := range opts {
|
||||||
|
opt.applyServer(&cfg)
|
||||||
|
}
|
||||||
|
cfg.initOTEL()
|
||||||
|
return cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
type baseServer struct {
|
||||||
|
cfg serverConfig
|
||||||
|
requests metric.Int64Counter
|
||||||
|
errors metric.Int64Counter
|
||||||
|
duration metric.Float64Histogram
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s baseServer) notFound(w http.ResponseWriter, r *http.Request) {
|
||||||
|
s.cfg.NotFound(w, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
type notAllowedParams struct {
|
||||||
|
allowedMethods string
|
||||||
|
allowedHeaders map[string]string
|
||||||
|
acceptPost string
|
||||||
|
acceptPatch string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s baseServer) notAllowed(w http.ResponseWriter, r *http.Request, params notAllowedParams) {
|
||||||
|
h := w.Header()
|
||||||
|
isOptions := r.Method == "OPTIONS"
|
||||||
|
if isOptions {
|
||||||
|
h.Set("Access-Control-Allow-Methods", params.allowedMethods)
|
||||||
|
if params.allowedHeaders != nil {
|
||||||
|
m := r.Header.Get("Access-Control-Request-Method")
|
||||||
|
if m != "" {
|
||||||
|
allowedHeaders, ok := params.allowedHeaders[strings.ToUpper(m)]
|
||||||
|
if ok {
|
||||||
|
h.Set("Access-Control-Allow-Headers", allowedHeaders)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if params.acceptPost != "" {
|
||||||
|
h.Set("Accept-Post", params.acceptPost)
|
||||||
|
}
|
||||||
|
if params.acceptPatch != "" {
|
||||||
|
h.Set("Accept-Patch", params.acceptPatch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s.cfg.MethodNotAllowed != nil {
|
||||||
|
s.cfg.MethodNotAllowed(w, r, params.allowedMethods)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
status := http.StatusNoContent
|
||||||
|
if !isOptions {
|
||||||
|
h.Set("Allow", params.allowedMethods)
|
||||||
|
status = http.StatusMethodNotAllowed
|
||||||
|
}
|
||||||
|
w.WriteHeader(status)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cfg serverConfig) baseServer() (s baseServer, err error) {
|
||||||
|
s = baseServer{cfg: cfg}
|
||||||
|
if s.requests, err = otelogen.ServerRequestCountCounter(s.cfg.Meter); err != nil {
|
||||||
|
return s, err
|
||||||
|
}
|
||||||
|
if s.errors, err = otelogen.ServerErrorsCountCounter(s.cfg.Meter); err != nil {
|
||||||
|
return s, err
|
||||||
|
}
|
||||||
|
if s.duration, err = otelogen.ServerDurationHistogram(s.cfg.Meter); err != nil {
|
||||||
|
return s, err
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Option is config option.
|
||||||
|
type Option interface {
|
||||||
|
ServerOption
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithTracerProvider specifies a tracer provider to use for creating a tracer.
|
||||||
|
//
|
||||||
|
// If none is specified, the global provider is used.
|
||||||
|
func WithTracerProvider(provider trace.TracerProvider) Option {
|
||||||
|
return otelOptionFunc(func(cfg *otelConfig) {
|
||||||
|
if provider != nil {
|
||||||
|
cfg.TracerProvider = provider
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithMeterProvider specifies a meter provider to use for creating a meter.
|
||||||
|
//
|
||||||
|
// If none is specified, the otel.GetMeterProvider() is used.
|
||||||
|
func WithMeterProvider(provider metric.MeterProvider) Option {
|
||||||
|
return otelOptionFunc(func(cfg *otelConfig) {
|
||||||
|
if provider != nil {
|
||||||
|
cfg.MeterProvider = provider
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithAttributes specifies default otel attributes.
|
||||||
|
func WithAttributes(attributes ...attribute.KeyValue) Option {
|
||||||
|
return otelOptionFunc(func(cfg *otelConfig) {
|
||||||
|
cfg.Attributes = attributes
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithNotFound specifies Not Found handler to use.
|
||||||
|
func WithNotFound(notFound http.HandlerFunc) ServerOption {
|
||||||
|
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||||
|
if notFound != nil {
|
||||||
|
cfg.NotFound = notFound
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithMethodNotAllowed specifies Method Not Allowed handler to use.
|
||||||
|
func WithMethodNotAllowed(methodNotAllowed func(w http.ResponseWriter, r *http.Request, allowed string)) ServerOption {
|
||||||
|
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||||
|
if methodNotAllowed != nil {
|
||||||
|
cfg.MethodNotAllowed = methodNotAllowed
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithErrorHandler specifies error handler to use.
|
||||||
|
func WithErrorHandler(h ErrorHandler) ServerOption {
|
||||||
|
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||||
|
if h != nil {
|
||||||
|
cfg.ErrorHandler = h
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithPathPrefix specifies server path prefix.
|
||||||
|
func WithPathPrefix(prefix string) ServerOption {
|
||||||
|
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||||
|
cfg.Prefix = prefix
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithMiddleware specifies middlewares to use.
|
||||||
|
func WithMiddleware(m ...Middleware) ServerOption {
|
||||||
|
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||||
|
switch len(m) {
|
||||||
|
case 0:
|
||||||
|
cfg.Middleware = nil
|
||||||
|
case 1:
|
||||||
|
cfg.Middleware = m[0]
|
||||||
|
default:
|
||||||
|
cfg.Middleware = middleware.ChainMiddlewares(m...)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithMaxMultipartMemory specifies limit of memory for storing file parts.
|
||||||
|
// File parts which can't be stored in memory will be stored on disk in temporary files.
|
||||||
|
func WithMaxMultipartMemory(max int64) ServerOption {
|
||||||
|
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||||
|
if max > 0 {
|
||||||
|
cfg.MaxMultipartMemory = max
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,14 @@
|
|||||||
|
// Code generated by ogen, DO NOT EDIT.
|
||||||
|
package api
|
||||||
|
|
||||||
|
type CreateLabRes interface {
|
||||||
|
createLabRes()
|
||||||
|
}
|
||||||
|
|
||||||
|
type DeleteLabRes interface {
|
||||||
|
deleteLabRes()
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetLabdReadyzRes interface {
|
||||||
|
getLabdReadyzRes()
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,42 @@
|
|||||||
|
// Code generated by ogen, DO NOT EDIT.
|
||||||
|
|
||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"go.opentelemetry.io/otel/attribute"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Labeler is used to allow adding custom attributes to the server request metrics.
|
||||||
|
type Labeler struct {
|
||||||
|
attrs []attribute.KeyValue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add attributes to the Labeler.
|
||||||
|
func (l *Labeler) Add(attrs ...attribute.KeyValue) {
|
||||||
|
l.attrs = append(l.attrs, attrs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AttributeSet returns the attributes added to the Labeler as an attribute.Set.
|
||||||
|
func (l *Labeler) AttributeSet() attribute.Set {
|
||||||
|
return attribute.NewSet(l.attrs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
type labelerContextKey struct{}
|
||||||
|
|
||||||
|
// LabelerFromContext retrieves the Labeler from the provided context, if present.
|
||||||
|
//
|
||||||
|
// If no Labeler was found in the provided context a new, empty Labeler is returned and the second
|
||||||
|
// return value is false. In this case it is safe to use the Labeler but any attributes added to
|
||||||
|
// it will not be used.
|
||||||
|
func LabelerFromContext(ctx context.Context) (*Labeler, bool) {
|
||||||
|
if l, ok := ctx.Value(labelerContextKey{}).(*Labeler); ok {
|
||||||
|
return l, true
|
||||||
|
}
|
||||||
|
return &Labeler{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
func contextWithLabeler(ctx context.Context, l *Labeler) context.Context {
|
||||||
|
return context.WithValue(ctx, labelerContextKey{}, l)
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
// Code generated by ogen, DO NOT EDIT.
|
||||||
|
|
||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/ogen-go/ogen/middleware"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Middleware is middleware type.
|
||||||
|
type Middleware = middleware.Middleware
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
// Code generated by ogen, DO NOT EDIT.
|
||||||
|
|
||||||
|
package api
|
||||||
|
|
||||||
|
// OperationName is the ogen operation name
|
||||||
|
type OperationName = string
|
||||||
|
|
||||||
|
const (
|
||||||
|
CheckLabOperation OperationName = "CheckLab"
|
||||||
|
CreateLabOperation OperationName = "CreateLab"
|
||||||
|
CreateLabConsoleTokenOperation OperationName = "CreateLabConsoleToken"
|
||||||
|
DeleteLabOperation OperationName = "DeleteLab"
|
||||||
|
GetLabOperation OperationName = "GetLab"
|
||||||
|
GetLabdHealthzOperation OperationName = "GetLabdHealthz"
|
||||||
|
GetLabdReadyzOperation OperationName = "GetLabdReadyz"
|
||||||
|
)
|
||||||
@@ -0,0 +1,351 @@
|
|||||||
|
// Code generated by ogen, DO NOT EDIT.
|
||||||
|
|
||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
|
||||||
|
"github.com/go-faster/errors"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/ogen-go/ogen/conv"
|
||||||
|
"github.com/ogen-go/ogen/middleware"
|
||||||
|
"github.com/ogen-go/ogen/ogenerrors"
|
||||||
|
"github.com/ogen-go/ogen/uri"
|
||||||
|
"github.com/ogen-go/ogen/validate"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CheckLabParams is parameters of CheckLab operation.
|
||||||
|
type CheckLabParams struct {
|
||||||
|
// Random UUID chosen by the backend for one lab. It is the idempotency key of CreateLab and must not
|
||||||
|
// encode a candidate, attempt, or task identifier.
|
||||||
|
LabID uuid.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
func unpackCheckLabParams(packed middleware.Parameters) (params CheckLabParams) {
|
||||||
|
{
|
||||||
|
key := middleware.ParameterKey{
|
||||||
|
Name: "lab_id",
|
||||||
|
In: "path",
|
||||||
|
}
|
||||||
|
params.LabID = packed[key].(uuid.UUID)
|
||||||
|
}
|
||||||
|
return params
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeCheckLabParams(args [1]string, argsEscaped bool, r *http.Request) (params CheckLabParams, _ error) {
|
||||||
|
// Decode path: lab_id.
|
||||||
|
if err := func() error {
|
||||||
|
param := args[0]
|
||||||
|
if argsEscaped {
|
||||||
|
unescaped, err := url.PathUnescape(args[0])
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "unescape path")
|
||||||
|
}
|
||||||
|
param = unescaped
|
||||||
|
}
|
||||||
|
if len(param) > 0 {
|
||||||
|
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||||
|
Param: "lab_id",
|
||||||
|
Value: param,
|
||||||
|
Style: uri.PathStyleSimple,
|
||||||
|
Explode: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
if err := func() error {
|
||||||
|
val, err := d.DecodeValue()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err := conv.ToUUID(val)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
params.LabID = c
|
||||||
|
return nil
|
||||||
|
}(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return validate.ErrFieldRequired
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}(); err != nil {
|
||||||
|
return params, &ogenerrors.DecodeParamError{
|
||||||
|
Name: "lab_id",
|
||||||
|
In: "path",
|
||||||
|
Err: err,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return params, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateLabParams is parameters of CreateLab operation.
|
||||||
|
type CreateLabParams struct {
|
||||||
|
// Random UUID chosen by the backend for one lab. It is the idempotency key of CreateLab and must not
|
||||||
|
// encode a candidate, attempt, or task identifier.
|
||||||
|
LabID uuid.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
func unpackCreateLabParams(packed middleware.Parameters) (params CreateLabParams) {
|
||||||
|
{
|
||||||
|
key := middleware.ParameterKey{
|
||||||
|
Name: "lab_id",
|
||||||
|
In: "path",
|
||||||
|
}
|
||||||
|
params.LabID = packed[key].(uuid.UUID)
|
||||||
|
}
|
||||||
|
return params
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeCreateLabParams(args [1]string, argsEscaped bool, r *http.Request) (params CreateLabParams, _ error) {
|
||||||
|
// Decode path: lab_id.
|
||||||
|
if err := func() error {
|
||||||
|
param := args[0]
|
||||||
|
if argsEscaped {
|
||||||
|
unescaped, err := url.PathUnescape(args[0])
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "unescape path")
|
||||||
|
}
|
||||||
|
param = unescaped
|
||||||
|
}
|
||||||
|
if len(param) > 0 {
|
||||||
|
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||||
|
Param: "lab_id",
|
||||||
|
Value: param,
|
||||||
|
Style: uri.PathStyleSimple,
|
||||||
|
Explode: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
if err := func() error {
|
||||||
|
val, err := d.DecodeValue()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err := conv.ToUUID(val)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
params.LabID = c
|
||||||
|
return nil
|
||||||
|
}(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return validate.ErrFieldRequired
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}(); err != nil {
|
||||||
|
return params, &ogenerrors.DecodeParamError{
|
||||||
|
Name: "lab_id",
|
||||||
|
In: "path",
|
||||||
|
Err: err,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return params, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateLabConsoleTokenParams is parameters of CreateLabConsoleToken operation.
|
||||||
|
type CreateLabConsoleTokenParams struct {
|
||||||
|
// Random UUID chosen by the backend for one lab. It is the idempotency key of CreateLab and must not
|
||||||
|
// encode a candidate, attempt, or task identifier.
|
||||||
|
LabID uuid.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
func unpackCreateLabConsoleTokenParams(packed middleware.Parameters) (params CreateLabConsoleTokenParams) {
|
||||||
|
{
|
||||||
|
key := middleware.ParameterKey{
|
||||||
|
Name: "lab_id",
|
||||||
|
In: "path",
|
||||||
|
}
|
||||||
|
params.LabID = packed[key].(uuid.UUID)
|
||||||
|
}
|
||||||
|
return params
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeCreateLabConsoleTokenParams(args [1]string, argsEscaped bool, r *http.Request) (params CreateLabConsoleTokenParams, _ error) {
|
||||||
|
// Decode path: lab_id.
|
||||||
|
if err := func() error {
|
||||||
|
param := args[0]
|
||||||
|
if argsEscaped {
|
||||||
|
unescaped, err := url.PathUnescape(args[0])
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "unescape path")
|
||||||
|
}
|
||||||
|
param = unescaped
|
||||||
|
}
|
||||||
|
if len(param) > 0 {
|
||||||
|
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||||
|
Param: "lab_id",
|
||||||
|
Value: param,
|
||||||
|
Style: uri.PathStyleSimple,
|
||||||
|
Explode: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
if err := func() error {
|
||||||
|
val, err := d.DecodeValue()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err := conv.ToUUID(val)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
params.LabID = c
|
||||||
|
return nil
|
||||||
|
}(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return validate.ErrFieldRequired
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}(); err != nil {
|
||||||
|
return params, &ogenerrors.DecodeParamError{
|
||||||
|
Name: "lab_id",
|
||||||
|
In: "path",
|
||||||
|
Err: err,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return params, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteLabParams is parameters of DeleteLab operation.
|
||||||
|
type DeleteLabParams struct {
|
||||||
|
// Random UUID chosen by the backend for one lab. It is the idempotency key of CreateLab and must not
|
||||||
|
// encode a candidate, attempt, or task identifier.
|
||||||
|
LabID uuid.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
func unpackDeleteLabParams(packed middleware.Parameters) (params DeleteLabParams) {
|
||||||
|
{
|
||||||
|
key := middleware.ParameterKey{
|
||||||
|
Name: "lab_id",
|
||||||
|
In: "path",
|
||||||
|
}
|
||||||
|
params.LabID = packed[key].(uuid.UUID)
|
||||||
|
}
|
||||||
|
return params
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeDeleteLabParams(args [1]string, argsEscaped bool, r *http.Request) (params DeleteLabParams, _ error) {
|
||||||
|
// Decode path: lab_id.
|
||||||
|
if err := func() error {
|
||||||
|
param := args[0]
|
||||||
|
if argsEscaped {
|
||||||
|
unescaped, err := url.PathUnescape(args[0])
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "unescape path")
|
||||||
|
}
|
||||||
|
param = unescaped
|
||||||
|
}
|
||||||
|
if len(param) > 0 {
|
||||||
|
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||||
|
Param: "lab_id",
|
||||||
|
Value: param,
|
||||||
|
Style: uri.PathStyleSimple,
|
||||||
|
Explode: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
if err := func() error {
|
||||||
|
val, err := d.DecodeValue()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err := conv.ToUUID(val)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
params.LabID = c
|
||||||
|
return nil
|
||||||
|
}(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return validate.ErrFieldRequired
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}(); err != nil {
|
||||||
|
return params, &ogenerrors.DecodeParamError{
|
||||||
|
Name: "lab_id",
|
||||||
|
In: "path",
|
||||||
|
Err: err,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return params, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLabParams is parameters of GetLab operation.
|
||||||
|
type GetLabParams struct {
|
||||||
|
// Random UUID chosen by the backend for one lab. It is the idempotency key of CreateLab and must not
|
||||||
|
// encode a candidate, attempt, or task identifier.
|
||||||
|
LabID uuid.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
func unpackGetLabParams(packed middleware.Parameters) (params GetLabParams) {
|
||||||
|
{
|
||||||
|
key := middleware.ParameterKey{
|
||||||
|
Name: "lab_id",
|
||||||
|
In: "path",
|
||||||
|
}
|
||||||
|
params.LabID = packed[key].(uuid.UUID)
|
||||||
|
}
|
||||||
|
return params
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeGetLabParams(args [1]string, argsEscaped bool, r *http.Request) (params GetLabParams, _ error) {
|
||||||
|
// Decode path: lab_id.
|
||||||
|
if err := func() error {
|
||||||
|
param := args[0]
|
||||||
|
if argsEscaped {
|
||||||
|
unescaped, err := url.PathUnescape(args[0])
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "unescape path")
|
||||||
|
}
|
||||||
|
param = unescaped
|
||||||
|
}
|
||||||
|
if len(param) > 0 {
|
||||||
|
d := uri.NewPathDecoder(uri.PathDecoderConfig{
|
||||||
|
Param: "lab_id",
|
||||||
|
Value: param,
|
||||||
|
Style: uri.PathStyleSimple,
|
||||||
|
Explode: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
if err := func() error {
|
||||||
|
val, err := d.DecodeValue()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err := conv.ToUUID(val)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
params.LabID = c
|
||||||
|
return nil
|
||||||
|
}(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return validate.ErrFieldRequired
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}(); err != nil {
|
||||||
|
return params, &ogenerrors.DecodeParamError{
|
||||||
|
Name: "lab_id",
|
||||||
|
In: "path",
|
||||||
|
Err: err,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return params, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
// Code generated by ogen, DO NOT EDIT.
|
||||||
|
|
||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"io"
|
||||||
|
"mime"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/go-faster/errors"
|
||||||
|
"github.com/go-faster/jx"
|
||||||
|
"github.com/ogen-go/ogen/ogenerrors"
|
||||||
|
"github.com/ogen-go/ogen/validate"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s *Server) decodeCreateLabRequest(r *http.Request) (
|
||||||
|
req *LabCreateRequest,
|
||||||
|
rawBody []byte,
|
||||||
|
close func() error,
|
||||||
|
rerr error,
|
||||||
|
) {
|
||||||
|
var closers []func() error
|
||||||
|
close = func() error {
|
||||||
|
var merr error
|
||||||
|
// Close in reverse order, to match defer behavior.
|
||||||
|
for i := len(closers) - 1; i >= 0; i-- {
|
||||||
|
c := closers[i]
|
||||||
|
merr = errors.Join(merr, c())
|
||||||
|
}
|
||||||
|
return merr
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
if rerr != nil {
|
||||||
|
rerr = errors.Join(rerr, close())
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||||
|
if err != nil {
|
||||||
|
return req, rawBody, close, errors.Wrap(err, "parse media type")
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case ct == "application/json":
|
||||||
|
if r.ContentLength == 0 {
|
||||||
|
return req, rawBody, close, validate.ErrBodyRequired
|
||||||
|
}
|
||||||
|
buf, err := io.ReadAll(r.Body)
|
||||||
|
defer func() {
|
||||||
|
_ = r.Body.Close()
|
||||||
|
}()
|
||||||
|
if err != nil {
|
||||||
|
return req, rawBody, close, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset the body to allow for downstream reading.
|
||||||
|
r.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||||
|
|
||||||
|
if len(buf) == 0 {
|
||||||
|
return req, rawBody, close, validate.ErrBodyRequired
|
||||||
|
}
|
||||||
|
|
||||||
|
rawBody = append(rawBody, buf...)
|
||||||
|
d := jx.DecodeBytes(buf)
|
||||||
|
|
||||||
|
var request LabCreateRequest
|
||||||
|
if err := func() error {
|
||||||
|
if err := request.Decode(d); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := d.Skip(); err != io.EOF {
|
||||||
|
return errors.New("unexpected trailing data")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}(); err != nil {
|
||||||
|
err = &ogenerrors.DecodeBodyError{
|
||||||
|
ContentType: ct,
|
||||||
|
Body: buf,
|
||||||
|
Err: err,
|
||||||
|
}
|
||||||
|
return req, rawBody, close, err
|
||||||
|
}
|
||||||
|
if err := func() error {
|
||||||
|
if err := request.Validate(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}(); err != nil {
|
||||||
|
return req, rawBody, close, errors.Wrap(err, "validate")
|
||||||
|
}
|
||||||
|
return &request, rawBody, close, nil
|
||||||
|
default:
|
||||||
|
return req, rawBody, close, validate.InvalidContentType(ct)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) decodeCreateLabConsoleTokenRequest(r *http.Request) (
|
||||||
|
req *ConsoleTokenRequest,
|
||||||
|
rawBody []byte,
|
||||||
|
close func() error,
|
||||||
|
rerr error,
|
||||||
|
) {
|
||||||
|
var closers []func() error
|
||||||
|
close = func() error {
|
||||||
|
var merr error
|
||||||
|
// Close in reverse order, to match defer behavior.
|
||||||
|
for i := len(closers) - 1; i >= 0; i-- {
|
||||||
|
c := closers[i]
|
||||||
|
merr = errors.Join(merr, c())
|
||||||
|
}
|
||||||
|
return merr
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
if rerr != nil {
|
||||||
|
rerr = errors.Join(rerr, close())
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||||
|
if err != nil {
|
||||||
|
return req, rawBody, close, errors.Wrap(err, "parse media type")
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case ct == "application/json":
|
||||||
|
if r.ContentLength == 0 {
|
||||||
|
return req, rawBody, close, validate.ErrBodyRequired
|
||||||
|
}
|
||||||
|
buf, err := io.ReadAll(r.Body)
|
||||||
|
defer func() {
|
||||||
|
_ = r.Body.Close()
|
||||||
|
}()
|
||||||
|
if err != nil {
|
||||||
|
return req, rawBody, close, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset the body to allow for downstream reading.
|
||||||
|
r.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||||
|
|
||||||
|
if len(buf) == 0 {
|
||||||
|
return req, rawBody, close, validate.ErrBodyRequired
|
||||||
|
}
|
||||||
|
|
||||||
|
rawBody = append(rawBody, buf...)
|
||||||
|
d := jx.DecodeBytes(buf)
|
||||||
|
|
||||||
|
var request ConsoleTokenRequest
|
||||||
|
if err := func() error {
|
||||||
|
if err := request.Decode(d); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := d.Skip(); err != io.EOF {
|
||||||
|
return errors.New("unexpected trailing data")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}(); err != nil {
|
||||||
|
err = &ogenerrors.DecodeBodyError{
|
||||||
|
ContentType: ct,
|
||||||
|
Body: buf,
|
||||||
|
Err: err,
|
||||||
|
}
|
||||||
|
return req, rawBody, close, err
|
||||||
|
}
|
||||||
|
if err := func() error {
|
||||||
|
if err := request.Validate(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}(); err != nil {
|
||||||
|
return req, rawBody, close, errors.Wrap(err, "validate")
|
||||||
|
}
|
||||||
|
return &request, rawBody, close, nil
|
||||||
|
default:
|
||||||
|
return req, rawBody, close, validate.InvalidContentType(ct)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
// Code generated by ogen, DO NOT EDIT.
|
||||||
|
|
||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/go-faster/errors"
|
||||||
|
"github.com/go-faster/jx"
|
||||||
|
"github.com/ogen-go/ogen/conv"
|
||||||
|
ht "github.com/ogen-go/ogen/http"
|
||||||
|
"github.com/ogen-go/ogen/uri"
|
||||||
|
"go.opentelemetry.io/otel/codes"
|
||||||
|
"go.opentelemetry.io/otel/trace"
|
||||||
|
)
|
||||||
|
|
||||||
|
func encodeCheckLabResponse(response *LabCheckResult, w http.ResponseWriter, span trace.Span) error {
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
w.WriteHeader(200)
|
||||||
|
|
||||||
|
e := new(jx.Encoder)
|
||||||
|
response.Encode(e)
|
||||||
|
if _, err := e.WriteTo(w); err != nil {
|
||||||
|
return errors.Wrap(err, "write")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func encodeCreateLabResponse(response CreateLabRes, w http.ResponseWriter, span trace.Span) error {
|
||||||
|
switch response := response.(type) {
|
||||||
|
case *CreateLabOK:
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
w.WriteHeader(200)
|
||||||
|
|
||||||
|
e := new(jx.Encoder)
|
||||||
|
response.Encode(e)
|
||||||
|
if _, err := e.WriteTo(w); err != nil {
|
||||||
|
return errors.Wrap(err, "write")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
|
||||||
|
case *CreateLabAccepted:
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
w.WriteHeader(202)
|
||||||
|
|
||||||
|
e := new(jx.Encoder)
|
||||||
|
response.Encode(e)
|
||||||
|
if _, err := e.WriteTo(w); err != nil {
|
||||||
|
return errors.Wrap(err, "write")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
|
||||||
|
case *LabPoolBusyHeaders:
|
||||||
|
w.Header().Set("Content-Type", "application/problem+json")
|
||||||
|
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
|
||||||
|
// Encoding response headers.
|
||||||
|
{
|
||||||
|
h := uri.NewHeaderEncoder(w.Header())
|
||||||
|
// Encode "Retry-After" header.
|
||||||
|
{
|
||||||
|
cfg := uri.HeaderParameterEncodingConfig{
|
||||||
|
Name: "Retry-After",
|
||||||
|
Explode: false,
|
||||||
|
}
|
||||||
|
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||||
|
return e.EncodeValue(conv.Int32ToString(response.RetryAfter))
|
||||||
|
}); err != nil {
|
||||||
|
return errors.Wrap(err, "encode Retry-After header")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w.WriteHeader(503)
|
||||||
|
span.SetStatus(codes.Error, http.StatusText(503))
|
||||||
|
|
||||||
|
e := new(jx.Encoder)
|
||||||
|
response.Response.Encode(e)
|
||||||
|
if _, err := e.WriteTo(w); err != nil {
|
||||||
|
return errors.Wrap(err, "write")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
|
||||||
|
default:
|
||||||
|
return errors.Errorf("unexpected response type: %T", response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func encodeCreateLabConsoleTokenResponse(response *ConsoleTokenHeaders, w http.ResponseWriter, span trace.Span) error {
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
// Encoding response headers.
|
||||||
|
{
|
||||||
|
h := uri.NewHeaderEncoder(w.Header())
|
||||||
|
// Encode "Cache-Control" header.
|
||||||
|
{
|
||||||
|
cfg := uri.HeaderParameterEncodingConfig{
|
||||||
|
Name: "Cache-Control",
|
||||||
|
Explode: false,
|
||||||
|
}
|
||||||
|
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||||
|
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
|
||||||
|
}); err != nil {
|
||||||
|
return errors.Wrap(err, "encode Cache-Control header")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w.WriteHeader(201)
|
||||||
|
|
||||||
|
e := new(jx.Encoder)
|
||||||
|
response.Response.Encode(e)
|
||||||
|
if _, err := e.WriteTo(w); err != nil {
|
||||||
|
return errors.Wrap(err, "write")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func encodeDeleteLabResponse(response DeleteLabRes, w http.ResponseWriter, span trace.Span) error {
|
||||||
|
switch response := response.(type) {
|
||||||
|
case *DeleteLabOK:
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
w.WriteHeader(200)
|
||||||
|
|
||||||
|
e := new(jx.Encoder)
|
||||||
|
response.Encode(e)
|
||||||
|
if _, err := e.WriteTo(w); err != nil {
|
||||||
|
return errors.Wrap(err, "write")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
|
||||||
|
case *DeleteLabAccepted:
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
w.WriteHeader(202)
|
||||||
|
|
||||||
|
e := new(jx.Encoder)
|
||||||
|
response.Encode(e)
|
||||||
|
if _, err := e.WriteTo(w); err != nil {
|
||||||
|
return errors.Wrap(err, "write")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
|
||||||
|
default:
|
||||||
|
return errors.Errorf("unexpected response type: %T", response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func encodeGetLabResponse(response *LabStatus, w http.ResponseWriter, span trace.Span) error {
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
w.WriteHeader(200)
|
||||||
|
|
||||||
|
e := new(jx.Encoder)
|
||||||
|
response.Encode(e)
|
||||||
|
if _, err := e.WriteTo(w); err != nil {
|
||||||
|
return errors.Wrap(err, "write")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func encodeGetLabdHealthzResponse(response *LabdHealthResponse, w http.ResponseWriter, span trace.Span) error {
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
w.WriteHeader(200)
|
||||||
|
|
||||||
|
e := new(jx.Encoder)
|
||||||
|
response.Encode(e)
|
||||||
|
if _, err := e.WriteTo(w); err != nil {
|
||||||
|
return errors.Wrap(err, "write")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func encodeGetLabdReadyzResponse(response GetLabdReadyzRes, w http.ResponseWriter, span trace.Span) error {
|
||||||
|
switch response := response.(type) {
|
||||||
|
case *GetLabdReadyzOK:
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
w.WriteHeader(200)
|
||||||
|
|
||||||
|
e := new(jx.Encoder)
|
||||||
|
response.Encode(e)
|
||||||
|
if _, err := e.WriteTo(w); err != nil {
|
||||||
|
return errors.Wrap(err, "write")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
|
||||||
|
case *GetLabdReadyzServiceUnavailable:
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
w.WriteHeader(503)
|
||||||
|
span.SetStatus(codes.Error, http.StatusText(503))
|
||||||
|
|
||||||
|
e := new(jx.Encoder)
|
||||||
|
response.Encode(e)
|
||||||
|
if _, err := e.WriteTo(w); err != nil {
|
||||||
|
return errors.Wrap(err, "write")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
|
||||||
|
default:
|
||||||
|
return errors.Errorf("unexpected response type: %T", response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func encodeErrorResponse(response *ProblemStatusCode, w http.ResponseWriter, span trace.Span) error {
|
||||||
|
w.Header().Set("Content-Type", "application/problem+json")
|
||||||
|
code := response.StatusCode
|
||||||
|
if code == 0 {
|
||||||
|
// Set default status code.
|
||||||
|
code = http.StatusOK
|
||||||
|
}
|
||||||
|
w.WriteHeader(code)
|
||||||
|
if code >= http.StatusInternalServerError {
|
||||||
|
span.SetStatus(codes.Error, http.StatusText(code))
|
||||||
|
}
|
||||||
|
|
||||||
|
e := new(jx.Encoder)
|
||||||
|
response.Response.Encode(e)
|
||||||
|
if _, err := e.WriteTo(w); err != nil {
|
||||||
|
return errors.Wrap(err, "write")
|
||||||
|
}
|
||||||
|
|
||||||
|
if code >= http.StatusInternalServerError {
|
||||||
|
return errors.Wrapf(ht.ErrInternalServerErrorResponse, "code: %d, message: %s", code, http.StatusText(code))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,513 @@
|
|||||||
|
// Code generated by ogen, DO NOT EDIT.
|
||||||
|
|
||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/ogen-go/ogen/uri"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
rn2AllowedHeaders = map[string]string{
|
||||||
|
"DELETE": "Authorization",
|
||||||
|
"GET": "Authorization",
|
||||||
|
"PUT": "Authorization,Content-Type",
|
||||||
|
}
|
||||||
|
rn3AllowedHeaders = map[string]string{
|
||||||
|
"POST": "Authorization",
|
||||||
|
}
|
||||||
|
rn5AllowedHeaders = map[string]string{
|
||||||
|
"POST": "Authorization,Content-Type",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s *Server) cutPrefix(path string) (string, bool) {
|
||||||
|
prefix := s.cfg.Prefix
|
||||||
|
if prefix == "" {
|
||||||
|
return path, true
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(path, prefix) {
|
||||||
|
// Prefix doesn't match.
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
// Cut prefix from the path.
|
||||||
|
return strings.TrimPrefix(path, prefix), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// ServeHTTP serves http request as defined by OpenAPI v3 specification,
|
||||||
|
// calling handler that matches the path or returning not found error.
|
||||||
|
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
elem := r.URL.Path
|
||||||
|
elemIsEscaped := false
|
||||||
|
if rawPath := r.URL.RawPath; rawPath != "" {
|
||||||
|
if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok {
|
||||||
|
elem = normalized
|
||||||
|
elemIsEscaped = strings.ContainsRune(elem, '%')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
elem, ok := s.cutPrefix(elem)
|
||||||
|
if !ok || len(elem) == 0 {
|
||||||
|
s.notFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
args := [1]string{}
|
||||||
|
|
||||||
|
// Static code generated router with unwrapped path search.
|
||||||
|
switch {
|
||||||
|
default:
|
||||||
|
if len(elem) == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
switch elem[0] {
|
||||||
|
case '/': // Prefix: "/"
|
||||||
|
|
||||||
|
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||||
|
elem = elem[l:]
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(elem) == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
switch elem[0] {
|
||||||
|
case 'h': // Prefix: "healthz"
|
||||||
|
|
||||||
|
if l := len("healthz"); len(elem) >= l && elem[0:l] == "healthz" {
|
||||||
|
elem = elem[l:]
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(elem) == 0 {
|
||||||
|
// Leaf node.
|
||||||
|
switch r.Method {
|
||||||
|
case "GET":
|
||||||
|
s.handleGetLabdHealthzRequest([0]string{}, elemIsEscaped, w, r)
|
||||||
|
default:
|
||||||
|
s.notAllowed(w, r, notAllowedParams{
|
||||||
|
allowedMethods: "GET",
|
||||||
|
allowedHeaders: nil,
|
||||||
|
acceptPost: "",
|
||||||
|
acceptPatch: "",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'r': // Prefix: "readyz"
|
||||||
|
|
||||||
|
if l := len("readyz"); len(elem) >= l && elem[0:l] == "readyz" {
|
||||||
|
elem = elem[l:]
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(elem) == 0 {
|
||||||
|
// Leaf node.
|
||||||
|
switch r.Method {
|
||||||
|
case "GET":
|
||||||
|
s.handleGetLabdReadyzRequest([0]string{}, elemIsEscaped, w, r)
|
||||||
|
default:
|
||||||
|
s.notAllowed(w, r, notAllowedParams{
|
||||||
|
allowedMethods: "GET",
|
||||||
|
allowedHeaders: nil,
|
||||||
|
acceptPost: "",
|
||||||
|
acceptPatch: "",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'v': // Prefix: "v1/labs/"
|
||||||
|
|
||||||
|
if l := len("v1/labs/"); len(elem) >= l && elem[0:l] == "v1/labs/" {
|
||||||
|
elem = elem[l:]
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
// Param: "lab_id"
|
||||||
|
// Match until "/"
|
||||||
|
idx := strings.IndexByte(elem, '/')
|
||||||
|
if idx < 0 {
|
||||||
|
idx = len(elem)
|
||||||
|
}
|
||||||
|
args[0] = elem[:idx]
|
||||||
|
elem = elem[idx:]
|
||||||
|
|
||||||
|
if len(elem) == 0 {
|
||||||
|
switch r.Method {
|
||||||
|
case "DELETE":
|
||||||
|
s.handleDeleteLabRequest([1]string{
|
||||||
|
args[0],
|
||||||
|
}, elemIsEscaped, w, r)
|
||||||
|
case "GET":
|
||||||
|
s.handleGetLabRequest([1]string{
|
||||||
|
args[0],
|
||||||
|
}, elemIsEscaped, w, r)
|
||||||
|
case "PUT":
|
||||||
|
s.handleCreateLabRequest([1]string{
|
||||||
|
args[0],
|
||||||
|
}, elemIsEscaped, w, r)
|
||||||
|
default:
|
||||||
|
s.notAllowed(w, r, notAllowedParams{
|
||||||
|
allowedMethods: "DELETE,GET,PUT",
|
||||||
|
allowedHeaders: rn2AllowedHeaders,
|
||||||
|
acceptPost: "",
|
||||||
|
acceptPatch: "",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch elem[0] {
|
||||||
|
case '/': // Prefix: "/c"
|
||||||
|
|
||||||
|
if l := len("/c"); len(elem) >= l && elem[0:l] == "/c" {
|
||||||
|
elem = elem[l:]
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(elem) == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
switch elem[0] {
|
||||||
|
case 'h': // Prefix: "heck"
|
||||||
|
|
||||||
|
if l := len("heck"); len(elem) >= l && elem[0:l] == "heck" {
|
||||||
|
elem = elem[l:]
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(elem) == 0 {
|
||||||
|
// Leaf node.
|
||||||
|
switch r.Method {
|
||||||
|
case "POST":
|
||||||
|
s.handleCheckLabRequest([1]string{
|
||||||
|
args[0],
|
||||||
|
}, elemIsEscaped, w, r)
|
||||||
|
default:
|
||||||
|
s.notAllowed(w, r, notAllowedParams{
|
||||||
|
allowedMethods: "POST",
|
||||||
|
allowedHeaders: rn3AllowedHeaders,
|
||||||
|
acceptPost: "",
|
||||||
|
acceptPatch: "",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'o': // Prefix: "onsole-tokens"
|
||||||
|
|
||||||
|
if l := len("onsole-tokens"); len(elem) >= l && elem[0:l] == "onsole-tokens" {
|
||||||
|
elem = elem[l:]
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(elem) == 0 {
|
||||||
|
// Leaf node.
|
||||||
|
switch r.Method {
|
||||||
|
case "POST":
|
||||||
|
s.handleCreateLabConsoleTokenRequest([1]string{
|
||||||
|
args[0],
|
||||||
|
}, elemIsEscaped, w, r)
|
||||||
|
default:
|
||||||
|
s.notAllowed(w, r, notAllowedParams{
|
||||||
|
allowedMethods: "POST",
|
||||||
|
allowedHeaders: rn5AllowedHeaders,
|
||||||
|
acceptPost: "application/json",
|
||||||
|
acceptPatch: "",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.notFound(w, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Route is route object.
|
||||||
|
type Route struct {
|
||||||
|
name string
|
||||||
|
summary string
|
||||||
|
operationID string
|
||||||
|
operationGroup string
|
||||||
|
pathPattern string
|
||||||
|
count int
|
||||||
|
args [1]string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Name returns ogen operation name.
|
||||||
|
//
|
||||||
|
// It is guaranteed to be unique and not empty.
|
||||||
|
func (r Route) Name() string {
|
||||||
|
return r.name
|
||||||
|
}
|
||||||
|
|
||||||
|
// Summary returns OpenAPI summary.
|
||||||
|
func (r Route) Summary() string {
|
||||||
|
return r.summary
|
||||||
|
}
|
||||||
|
|
||||||
|
// OperationID returns OpenAPI operationId.
|
||||||
|
func (r Route) OperationID() string {
|
||||||
|
return r.operationID
|
||||||
|
}
|
||||||
|
|
||||||
|
// OperationGroup returns the x-ogen-operation-group value.
|
||||||
|
func (r Route) OperationGroup() string {
|
||||||
|
return r.operationGroup
|
||||||
|
}
|
||||||
|
|
||||||
|
// PathPattern returns OpenAPI path.
|
||||||
|
func (r Route) PathPattern() string {
|
||||||
|
return r.pathPattern
|
||||||
|
}
|
||||||
|
|
||||||
|
// Args returns parsed arguments.
|
||||||
|
func (r Route) Args() []string {
|
||||||
|
return r.args[:r.count]
|
||||||
|
}
|
||||||
|
|
||||||
|
// FindRoute finds Route for given method and path.
|
||||||
|
//
|
||||||
|
// Note: this method does not unescape path or handle reserved characters in path properly. Use FindPath instead.
|
||||||
|
func (s *Server) FindRoute(method, path string) (Route, bool) {
|
||||||
|
return s.FindPath(method, &url.URL{Path: path})
|
||||||
|
}
|
||||||
|
|
||||||
|
// FindPath finds Route for given method and URL.
|
||||||
|
func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||||
|
var (
|
||||||
|
elem = u.Path
|
||||||
|
args = r.args
|
||||||
|
)
|
||||||
|
if rawPath := u.RawPath; rawPath != "" {
|
||||||
|
if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok {
|
||||||
|
elem = normalized
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
for i, arg := range r.args[:r.count] {
|
||||||
|
if unescaped, err := url.PathUnescape(arg); err == nil {
|
||||||
|
r.args[i] = unescaped
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
elem, ok := s.cutPrefix(elem)
|
||||||
|
if !ok {
|
||||||
|
return r, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Static code generated router with unwrapped path search.
|
||||||
|
switch {
|
||||||
|
default:
|
||||||
|
if len(elem) == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
switch elem[0] {
|
||||||
|
case '/': // Prefix: "/"
|
||||||
|
|
||||||
|
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||||
|
elem = elem[l:]
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(elem) == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
switch elem[0] {
|
||||||
|
case 'h': // Prefix: "healthz"
|
||||||
|
|
||||||
|
if l := len("healthz"); len(elem) >= l && elem[0:l] == "healthz" {
|
||||||
|
elem = elem[l:]
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(elem) == 0 {
|
||||||
|
// Leaf node.
|
||||||
|
switch method {
|
||||||
|
case "GET":
|
||||||
|
r.name = GetLabdHealthzOperation
|
||||||
|
r.summary = "Check whether the lab provisioner process is responding."
|
||||||
|
r.operationID = "GetLabdHealthz"
|
||||||
|
r.operationGroup = ""
|
||||||
|
r.pathPattern = "/healthz"
|
||||||
|
r.args = args
|
||||||
|
r.count = 0
|
||||||
|
return r, true
|
||||||
|
default:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'r': // Prefix: "readyz"
|
||||||
|
|
||||||
|
if l := len("readyz"); len(elem) >= l && elem[0:l] == "readyz" {
|
||||||
|
elem = elem[l:]
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(elem) == 0 {
|
||||||
|
// Leaf node.
|
||||||
|
switch method {
|
||||||
|
case "GET":
|
||||||
|
r.name = GetLabdReadyzOperation
|
||||||
|
r.summary = "Check whether the provisioner can create and delete labs."
|
||||||
|
r.operationID = "GetLabdReadyz"
|
||||||
|
r.operationGroup = ""
|
||||||
|
r.pathPattern = "/readyz"
|
||||||
|
r.args = args
|
||||||
|
r.count = 0
|
||||||
|
return r, true
|
||||||
|
default:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'v': // Prefix: "v1/labs/"
|
||||||
|
|
||||||
|
if l := len("v1/labs/"); len(elem) >= l && elem[0:l] == "v1/labs/" {
|
||||||
|
elem = elem[l:]
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
// Param: "lab_id"
|
||||||
|
// Match until "/"
|
||||||
|
idx := strings.IndexByte(elem, '/')
|
||||||
|
if idx < 0 {
|
||||||
|
idx = len(elem)
|
||||||
|
}
|
||||||
|
args[0] = elem[:idx]
|
||||||
|
elem = elem[idx:]
|
||||||
|
|
||||||
|
if len(elem) == 0 {
|
||||||
|
switch method {
|
||||||
|
case "DELETE":
|
||||||
|
r.name = DeleteLabOperation
|
||||||
|
r.summary = "Delete a lab before its timer."
|
||||||
|
r.operationID = "DeleteLab"
|
||||||
|
r.operationGroup = ""
|
||||||
|
r.pathPattern = "/v1/labs/{lab_id}"
|
||||||
|
r.args = args
|
||||||
|
r.count = 1
|
||||||
|
return r, true
|
||||||
|
case "GET":
|
||||||
|
r.name = GetLabOperation
|
||||||
|
r.summary = "Read the state of a lab."
|
||||||
|
r.operationID = "GetLab"
|
||||||
|
r.operationGroup = ""
|
||||||
|
r.pathPattern = "/v1/labs/{lab_id}"
|
||||||
|
r.args = args
|
||||||
|
r.count = 1
|
||||||
|
return r, true
|
||||||
|
case "PUT":
|
||||||
|
r.name = CreateLabOperation
|
||||||
|
r.summary = "Create a lab from a template and a variant seed."
|
||||||
|
r.operationID = "CreateLab"
|
||||||
|
r.operationGroup = ""
|
||||||
|
r.pathPattern = "/v1/labs/{lab_id}"
|
||||||
|
r.args = args
|
||||||
|
r.count = 1
|
||||||
|
return r, true
|
||||||
|
default:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch elem[0] {
|
||||||
|
case '/': // Prefix: "/c"
|
||||||
|
|
||||||
|
if l := len("/c"); len(elem) >= l && elem[0:l] == "/c" {
|
||||||
|
elem = elem[l:]
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(elem) == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
switch elem[0] {
|
||||||
|
case 'h': // Prefix: "heck"
|
||||||
|
|
||||||
|
if l := len("heck"); len(elem) >= l && elem[0:l] == "heck" {
|
||||||
|
elem = elem[l:]
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(elem) == 0 {
|
||||||
|
// Leaf node.
|
||||||
|
switch method {
|
||||||
|
case "POST":
|
||||||
|
r.name = CheckLabOperation
|
||||||
|
r.summary = "Run the checker of the template against the nodes of a ready lab."
|
||||||
|
r.operationID = "CheckLab"
|
||||||
|
r.operationGroup = ""
|
||||||
|
r.pathPattern = "/v1/labs/{lab_id}/check"
|
||||||
|
r.args = args
|
||||||
|
r.count = 1
|
||||||
|
return r, true
|
||||||
|
default:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'o': // Prefix: "onsole-tokens"
|
||||||
|
|
||||||
|
if l := len("onsole-tokens"); len(elem) >= l && elem[0:l] == "onsole-tokens" {
|
||||||
|
elem = elem[l:]
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(elem) == 0 {
|
||||||
|
// Leaf node.
|
||||||
|
switch method {
|
||||||
|
case "POST":
|
||||||
|
r.name = CreateLabConsoleTokenOperation
|
||||||
|
r.summary = "Issue a short-lived console token for one node of a ready lab."
|
||||||
|
r.operationID = "CreateLabConsoleToken"
|
||||||
|
r.operationGroup = ""
|
||||||
|
r.pathPattern = "/v1/labs/{lab_id}/console-tokens"
|
||||||
|
r.args = args
|
||||||
|
r.count = 1
|
||||||
|
return r, true
|
||||||
|
default:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return r, false
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,83 @@
|
|||||||
|
// Code generated by ogen, DO NOT EDIT.
|
||||||
|
|
||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/go-faster/errors"
|
||||||
|
"github.com/ogen-go/ogen/ogenerrors"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SecurityHandler is handler for security parameters.
|
||||||
|
type SecurityHandler interface {
|
||||||
|
// HandleBearerAuth handles bearerAuth security.
|
||||||
|
// Shared random service token sent as `Authorization: Bearer <token>` over TLS. `labd` compares it in
|
||||||
|
// constant time and never logs it. Rotation replaces the secret on both sides; there are no per-user
|
||||||
|
// tokens.
|
||||||
|
HandleBearerAuth(ctx context.Context, operationName OperationName, t BearerAuth) (context.Context, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func findAuthorization(h http.Header, prefix string) (string, bool) {
|
||||||
|
v, ok := h["Authorization"]
|
||||||
|
if !ok {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
for _, vv := range v {
|
||||||
|
scheme, value, ok := strings.Cut(vv, " ")
|
||||||
|
if !ok || !strings.EqualFold(scheme, prefix) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return value, true
|
||||||
|
}
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
// operationRolesBearerAuth is a private map storing roles per operation.
|
||||||
|
var operationRolesBearerAuth = map[string][]string{
|
||||||
|
CheckLabOperation: []string{},
|
||||||
|
CreateLabOperation: []string{},
|
||||||
|
CreateLabConsoleTokenOperation: []string{},
|
||||||
|
DeleteLabOperation: []string{},
|
||||||
|
GetLabOperation: []string{},
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetRolesForBearerAuth returns the required roles for the given operation.
|
||||||
|
//
|
||||||
|
// This is useful for authorization scenarios where you need to know which roles
|
||||||
|
// are required for an operation.
|
||||||
|
//
|
||||||
|
// Example:
|
||||||
|
//
|
||||||
|
// requiredRoles := GetRolesForBearerAuth(AddPetOperation)
|
||||||
|
//
|
||||||
|
// Returns nil if the operation has no role requirements or if the operation is unknown.
|
||||||
|
func GetRolesForBearerAuth(operation string) []string {
|
||||||
|
roles, ok := operationRolesBearerAuth[operation]
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// Return a copy to prevent external modification
|
||||||
|
result := make([]string, len(roles))
|
||||||
|
copy(result, roles)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) securityBearerAuth(ctx context.Context, operationName OperationName, req *http.Request) (context.Context, bool, error) {
|
||||||
|
var t BearerAuth
|
||||||
|
token, ok := findAuthorization(req.Header, "Bearer")
|
||||||
|
if !ok {
|
||||||
|
return ctx, false, nil
|
||||||
|
}
|
||||||
|
t.Token = token
|
||||||
|
t.Roles = operationRolesBearerAuth[operationName]
|
||||||
|
rctx, err := s.sec.HandleBearerAuth(ctx, operationName, t)
|
||||||
|
if errors.Is(err, ogenerrors.ErrSkipServerSecurity) {
|
||||||
|
return nil, false, nil
|
||||||
|
} else if err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
return rctx, true, err
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
// Code generated by ogen, DO NOT EDIT.
|
||||||
|
|
||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Handler handles operations described by OpenAPI v3 specification.
|
||||||
|
type Handler interface {
|
||||||
|
// CheckLab implements CheckLab operation.
|
||||||
|
//
|
||||||
|
// The checker of the template connects from the host side of the lab management bridge to the nodes
|
||||||
|
// (SSH or the RouterOS API) and evaluates the criteria of the variant that the seed selected. It only
|
||||||
|
// reads the node state and never changes it, so a repeated call is harmless; the result is not stored
|
||||||
|
// by `labd`. The call is synchronous and bounded by the check timeout of the provisioner.
|
||||||
|
//
|
||||||
|
// The result is checker state for the backend only: the backend scores the lab answer with it and
|
||||||
|
// never forwards it to the candidate.
|
||||||
|
//
|
||||||
|
// A lab that is not `ready` answers 409 `state_conflict`. When the checker cannot reach a node or the
|
||||||
|
// template has no working checker, the provisioner answers 503 `lab_unavailable`: nothing was
|
||||||
|
// evaluated, and the outcome is never a failed check.
|
||||||
|
//
|
||||||
|
// POST /v1/labs/{lab_id}/check
|
||||||
|
CheckLab(ctx context.Context, params CheckLabParams) (*LabCheckResult, error)
|
||||||
|
// CreateLab implements CreateLab operation.
|
||||||
|
//
|
||||||
|
// Idempotent by `lab_id`:
|
||||||
|
//
|
||||||
|
// - a new ID that fits the capacity reserves it, stores the lab, and answers 202 with
|
||||||
|
// `state: provisioning`; the nodes are cloned and booted in the background;
|
||||||
|
// - the same ID with the same payload answers 200 with the current state of that lab, including
|
||||||
|
// `deleted` or `failed`, and never creates a second one;
|
||||||
|
// - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing;
|
||||||
|
// - a new ID that does not fit the memory budget or the lab limit, or arrives while the provisioner
|
||||||
|
// is draining, answers 503 `lab_pool_busy` with Retry-After; nothing is stored, so the caller
|
||||||
|
// retries with the same ID.
|
||||||
|
//
|
||||||
|
// Payloads are compared by a SHA-256 fingerprint of the decoded request. An unknown template or
|
||||||
|
// template version, or a lifetime above the configured maximum, answers 400 `validation_failed` with a
|
||||||
|
// pointer such as `/template_id` or `/ttl_seconds`.
|
||||||
|
//
|
||||||
|
// The lab is deleted at `expires_at` = creation time + `ttl_seconds`, also when it is still
|
||||||
|
// provisioning. A lab that fails to provision or does not answer within the provisioning timeout
|
||||||
|
// becomes `failed` and its resources are deleted; its capacity returns when they are gone.
|
||||||
|
//
|
||||||
|
// A record of a deleted or failed lab is kept for a bounded retention time; after it, the ID is
|
||||||
|
// unknown again and a CreateLab with it starts a new lab.
|
||||||
|
//
|
||||||
|
// PUT /v1/labs/{lab_id}
|
||||||
|
CreateLab(ctx context.Context, req *LabCreateRequest, params CreateLabParams) (CreateLabRes, error)
|
||||||
|
// CreateLabConsoleToken implements CreateLabConsoleToken operation.
|
||||||
|
//
|
||||||
|
// The token lets the console gateway of the backend attach to the serial console of one node. It is
|
||||||
|
// random, single-use, bound to the lab and the node, and valid for at most 120 seconds; `labd` keeps
|
||||||
|
// only its SHA-256 digest in memory, so a restart invalidates every unused token. The token is never a
|
||||||
|
// node password or an SSH key, and the response carries no node address.
|
||||||
|
//
|
||||||
|
// Attaching: the gateway opens a WebSocket to `attach_path` on the same `labd` origin with the service
|
||||||
|
// bearer token and sends the console token in the `X-Lab-Console-Token` header. The WebSocket attach
|
||||||
|
// is described here as the planned interface; until it is implemented, `labd` answers the attach path
|
||||||
|
// with 501 and issuing a token changes nothing else.
|
||||||
|
//
|
||||||
|
// A lab that is not `ready` answers 409 `state_conflict`; an unknown node answers 400
|
||||||
|
// `validation_failed` with the pointer `/node`.
|
||||||
|
//
|
||||||
|
// POST /v1/labs/{lab_id}/console-tokens
|
||||||
|
CreateLabConsoleToken(ctx context.Context, req *ConsoleTokenRequest, params CreateLabConsoleTokenParams) (*ConsoleTokenHeaders, error)
|
||||||
|
// DeleteLab implements DeleteLab operation.
|
||||||
|
//
|
||||||
|
// Marks the lab for deletion and answers 202 with `state: deleting`; the provisioner removes its
|
||||||
|
// instances and bridges in the background and retries until LXD confirms that they are gone, also
|
||||||
|
// across its own restarts. Deleting a lab that is already `deleting` or `deleted` answers 200 with its
|
||||||
|
// state and changes nothing. An unknown ID answers 404 `not_found`.
|
||||||
|
//
|
||||||
|
// DELETE /v1/labs/{lab_id}
|
||||||
|
DeleteLab(ctx context.Context, params DeleteLabParams) (DeleteLabRes, error)
|
||||||
|
// GetLab implements GetLab operation.
|
||||||
|
//
|
||||||
|
// Answers 404 `not_found` for an ID the provisioner does not hold, including a lab whose `deleted`
|
||||||
|
// record outlived its retention time. The response never contains an address, a key, or an LXD object
|
||||||
|
// name.
|
||||||
|
//
|
||||||
|
// GET /v1/labs/{lab_id}
|
||||||
|
GetLab(ctx context.Context, params GetLabParams) (*LabStatus, error)
|
||||||
|
// GetLabdHealthz implements GetLabdHealthz operation.
|
||||||
|
//
|
||||||
|
// Check whether the lab provisioner process is responding.
|
||||||
|
//
|
||||||
|
// GET /healthz
|
||||||
|
GetLabdHealthz(ctx context.Context) (*LabdHealthResponse, error)
|
||||||
|
// GetLabdReadyz implements GetLabdReadyz operation.
|
||||||
|
//
|
||||||
|
// Ready means that the lab records were loaded, the startup reconciliation with LXD finished, the LXD
|
||||||
|
// API answered the latest probe, and the process is not draining. A provisioner without free capacity
|
||||||
|
// is still ready; capacity is reported by CreateLab.
|
||||||
|
//
|
||||||
|
// GET /readyz
|
||||||
|
GetLabdReadyz(ctx context.Context) (GetLabdReadyzRes, error)
|
||||||
|
// NewError creates *ProblemStatusCode from error returned by handler.
|
||||||
|
//
|
||||||
|
// Used for common default response.
|
||||||
|
NewError(ctx context.Context, err error) *ProblemStatusCode
|
||||||
|
}
|
||||||
|
|
||||||
|
// Server implements http server based on OpenAPI v3 specification and
|
||||||
|
// calls Handler to handle requests.
|
||||||
|
type Server struct {
|
||||||
|
h Handler
|
||||||
|
sec SecurityHandler
|
||||||
|
baseServer
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewServer creates new Server.
|
||||||
|
func NewServer(h Handler, sec SecurityHandler, opts ...ServerOption) (*Server, error) {
|
||||||
|
s, err := newServerConfig(opts...).baseServer()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &Server{
|
||||||
|
h: h,
|
||||||
|
sec: sec,
|
||||||
|
baseServer: s,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
// Code generated by ogen, DO NOT EDIT.
|
||||||
|
|
||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
ht "github.com/ogen-go/ogen/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
// UnimplementedHandler is no-op Handler which returns http.ErrNotImplemented.
|
||||||
|
type UnimplementedHandler struct{}
|
||||||
|
|
||||||
|
var _ Handler = UnimplementedHandler{}
|
||||||
|
|
||||||
|
// CheckLab implements CheckLab operation.
|
||||||
|
//
|
||||||
|
// The checker of the template connects from the host side of the lab management bridge to the nodes
|
||||||
|
// (SSH or the RouterOS API) and evaluates the criteria of the variant that the seed selected. It only
|
||||||
|
// reads the node state and never changes it, so a repeated call is harmless; the result is not stored
|
||||||
|
// by `labd`. The call is synchronous and bounded by the check timeout of the provisioner.
|
||||||
|
//
|
||||||
|
// The result is checker state for the backend only: the backend scores the lab answer with it and
|
||||||
|
// never forwards it to the candidate.
|
||||||
|
//
|
||||||
|
// A lab that is not `ready` answers 409 `state_conflict`. When the checker cannot reach a node or the
|
||||||
|
// template has no working checker, the provisioner answers 503 `lab_unavailable`: nothing was
|
||||||
|
// evaluated, and the outcome is never a failed check.
|
||||||
|
//
|
||||||
|
// POST /v1/labs/{lab_id}/check
|
||||||
|
func (UnimplementedHandler) CheckLab(ctx context.Context, params CheckLabParams) (r *LabCheckResult, _ error) {
|
||||||
|
return r, ht.ErrNotImplemented
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateLab implements CreateLab operation.
|
||||||
|
//
|
||||||
|
// Idempotent by `lab_id`:
|
||||||
|
//
|
||||||
|
// - a new ID that fits the capacity reserves it, stores the lab, and answers 202 with
|
||||||
|
// `state: provisioning`; the nodes are cloned and booted in the background;
|
||||||
|
// - the same ID with the same payload answers 200 with the current state of that lab, including
|
||||||
|
// `deleted` or `failed`, and never creates a second one;
|
||||||
|
// - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing;
|
||||||
|
// - a new ID that does not fit the memory budget or the lab limit, or arrives while the provisioner
|
||||||
|
// is draining, answers 503 `lab_pool_busy` with Retry-After; nothing is stored, so the caller
|
||||||
|
// retries with the same ID.
|
||||||
|
//
|
||||||
|
// Payloads are compared by a SHA-256 fingerprint of the decoded request. An unknown template or
|
||||||
|
// template version, or a lifetime above the configured maximum, answers 400 `validation_failed` with a
|
||||||
|
// pointer such as `/template_id` or `/ttl_seconds`.
|
||||||
|
//
|
||||||
|
// The lab is deleted at `expires_at` = creation time + `ttl_seconds`, also when it is still
|
||||||
|
// provisioning. A lab that fails to provision or does not answer within the provisioning timeout
|
||||||
|
// becomes `failed` and its resources are deleted; its capacity returns when they are gone.
|
||||||
|
//
|
||||||
|
// A record of a deleted or failed lab is kept for a bounded retention time; after it, the ID is
|
||||||
|
// unknown again and a CreateLab with it starts a new lab.
|
||||||
|
//
|
||||||
|
// PUT /v1/labs/{lab_id}
|
||||||
|
func (UnimplementedHandler) CreateLab(ctx context.Context, req *LabCreateRequest, params CreateLabParams) (r CreateLabRes, _ error) {
|
||||||
|
return r, ht.ErrNotImplemented
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateLabConsoleToken implements CreateLabConsoleToken operation.
|
||||||
|
//
|
||||||
|
// The token lets the console gateway of the backend attach to the serial console of one node. It is
|
||||||
|
// random, single-use, bound to the lab and the node, and valid for at most 120 seconds; `labd` keeps
|
||||||
|
// only its SHA-256 digest in memory, so a restart invalidates every unused token. The token is never a
|
||||||
|
// node password or an SSH key, and the response carries no node address.
|
||||||
|
//
|
||||||
|
// Attaching: the gateway opens a WebSocket to `attach_path` on the same `labd` origin with the service
|
||||||
|
// bearer token and sends the console token in the `X-Lab-Console-Token` header. The WebSocket attach
|
||||||
|
// is described here as the planned interface; until it is implemented, `labd` answers the attach path
|
||||||
|
// with 501 and issuing a token changes nothing else.
|
||||||
|
//
|
||||||
|
// A lab that is not `ready` answers 409 `state_conflict`; an unknown node answers 400
|
||||||
|
// `validation_failed` with the pointer `/node`.
|
||||||
|
//
|
||||||
|
// POST /v1/labs/{lab_id}/console-tokens
|
||||||
|
func (UnimplementedHandler) CreateLabConsoleToken(ctx context.Context, req *ConsoleTokenRequest, params CreateLabConsoleTokenParams) (r *ConsoleTokenHeaders, _ error) {
|
||||||
|
return r, ht.ErrNotImplemented
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteLab implements DeleteLab operation.
|
||||||
|
//
|
||||||
|
// Marks the lab for deletion and answers 202 with `state: deleting`; the provisioner removes its
|
||||||
|
// instances and bridges in the background and retries until LXD confirms that they are gone, also
|
||||||
|
// across its own restarts. Deleting a lab that is already `deleting` or `deleted` answers 200 with its
|
||||||
|
// state and changes nothing. An unknown ID answers 404 `not_found`.
|
||||||
|
//
|
||||||
|
// DELETE /v1/labs/{lab_id}
|
||||||
|
func (UnimplementedHandler) DeleteLab(ctx context.Context, params DeleteLabParams) (r DeleteLabRes, _ error) {
|
||||||
|
return r, ht.ErrNotImplemented
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLab implements GetLab operation.
|
||||||
|
//
|
||||||
|
// Answers 404 `not_found` for an ID the provisioner does not hold, including a lab whose `deleted`
|
||||||
|
// record outlived its retention time. The response never contains an address, a key, or an LXD object
|
||||||
|
// name.
|
||||||
|
//
|
||||||
|
// GET /v1/labs/{lab_id}
|
||||||
|
func (UnimplementedHandler) GetLab(ctx context.Context, params GetLabParams) (r *LabStatus, _ error) {
|
||||||
|
return r, ht.ErrNotImplemented
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLabdHealthz implements GetLabdHealthz operation.
|
||||||
|
//
|
||||||
|
// Check whether the lab provisioner process is responding.
|
||||||
|
//
|
||||||
|
// GET /healthz
|
||||||
|
func (UnimplementedHandler) GetLabdHealthz(ctx context.Context) (r *LabdHealthResponse, _ error) {
|
||||||
|
return r, ht.ErrNotImplemented
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLabdReadyz implements GetLabdReadyz operation.
|
||||||
|
//
|
||||||
|
// Ready means that the lab records were loaded, the startup reconciliation with LXD finished, the LXD
|
||||||
|
// API answered the latest probe, and the process is not draining. A provisioner without free capacity
|
||||||
|
// is still ready; capacity is reported by CreateLab.
|
||||||
|
//
|
||||||
|
// GET /readyz
|
||||||
|
func (UnimplementedHandler) GetLabdReadyz(ctx context.Context) (r GetLabdReadyzRes, _ error) {
|
||||||
|
return r, ht.ErrNotImplemented
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewError creates *ProblemStatusCode from error returned by handler.
|
||||||
|
//
|
||||||
|
// Used for common default response.
|
||||||
|
func (UnimplementedHandler) NewError(ctx context.Context, err error) (r *ProblemStatusCode) {
|
||||||
|
r = new(ProblemStatusCode)
|
||||||
|
return r
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,154 @@
|
|||||||
|
// Package app wires labd and controls its lifecycle.
|
||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"lincodex/labd/internal/config"
|
||||||
|
"lincodex/labd/internal/lxd"
|
||||||
|
"lincodex/labd/internal/pool"
|
||||||
|
"lincodex/labd/internal/reaper"
|
||||||
|
"lincodex/labd/internal/server"
|
||||||
|
"lincodex/labd/internal/store"
|
||||||
|
"lincodex/labd/internal/template"
|
||||||
|
)
|
||||||
|
|
||||||
|
// HTTP server bounds. Request bodies are bounded separately by
|
||||||
|
// LABD_MAX_REQUEST_BYTES; a check can take up to LABD_CHECK_TIMEOUT.
|
||||||
|
const (
|
||||||
|
readHeaderTimeout = 5 * time.Second
|
||||||
|
readTimeout = 30 * time.Second
|
||||||
|
idleTimeout = 60 * time.Second
|
||||||
|
maxHeaderBytes = 16 << 10
|
||||||
|
writeMargin = 15 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
// Run starts labd and blocks until SIGINT or SIGTERM.
|
||||||
|
func Run() error {
|
||||||
|
cfg, err := config.Load()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: cfg.LogLevel}))
|
||||||
|
|
||||||
|
registry, err := template.NewRegistry(template.Builtin()...)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
states, err := store.New(cfg.StateFile)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
client := lxd.NewUnix(cfg.LXDSocket, cfg.LXDProject)
|
||||||
|
manager, err := pool.New(pool.Config{
|
||||||
|
MemoryBudgetBytes: cfg.MemoryBudgetBytes,
|
||||||
|
MaxLabs: cfg.MaxLabs,
|
||||||
|
MaxLifetime: cfg.MaxLifetime,
|
||||||
|
ProvisionTimeout: cfg.ProvisionTimeout,
|
||||||
|
ProbeInterval: cfg.ProbeInterval,
|
||||||
|
DeletedRetention: cfg.DeletedRetention,
|
||||||
|
ConsoleTokenTTL: cfg.ConsoleTokenTTL,
|
||||||
|
CheckTimeout: cfg.CheckTimeout,
|
||||||
|
ManagementNetwork: cfg.ManagementNetwork,
|
||||||
|
ManagementPrefix: cfg.ManagementSubnet,
|
||||||
|
ManagementHost: cfg.ManagementHost,
|
||||||
|
ManagementFirst: cfg.ManagementFirst,
|
||||||
|
}, client, states, registry, pool.TCPProber{Timeout: cfg.ProbeTimeout}, time.Now, logger)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
if err := manager.Start(ctx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// Readiness needs one successful reconciliation: until then labd cannot
|
||||||
|
// tell its own objects from orphans of an earlier process.
|
||||||
|
var reconciled atomic.Bool
|
||||||
|
record := func(err error) { reconciled.Store(err == nil) }
|
||||||
|
if err := manager.Reconcile(ctx); err != nil {
|
||||||
|
logger.WarnContext(ctx, "startup reconciliation failed; labd is not ready until it succeeds", slog.String("error", err.Error()))
|
||||||
|
} else {
|
||||||
|
reconciled.Store(true)
|
||||||
|
}
|
||||||
|
reaperCtx, stopReaper := context.WithCancel(context.WithoutCancel(ctx))
|
||||||
|
var reaperDone sync.WaitGroup
|
||||||
|
reaperDone.Go(func() {
|
||||||
|
reaper.Run(reaperCtx, manager, reaper.Config{SweepInterval: cfg.SweepInterval, ReconcileInterval: cfg.ReconcileInterval}, record, logger)
|
||||||
|
})
|
||||||
|
|
||||||
|
ready := func() bool { return manager.Ready() && reconciled.Load() }
|
||||||
|
handler := server.NewHandler(manager, ready, cfg.RetryAfter, logger)
|
||||||
|
httpHandler, err := server.New(handler, server.Options{
|
||||||
|
Token: cfg.APIToken, MaxRequestBytes: cfg.MaxRequestBytes, AllowedClients: cfg.AllowedClients,
|
||||||
|
}, logger)
|
||||||
|
if err != nil {
|
||||||
|
stopReaper()
|
||||||
|
reaperDone.Wait()
|
||||||
|
return errors.Join(err, manager.Close(context.Background()))
|
||||||
|
}
|
||||||
|
httpServer := &http.Server{
|
||||||
|
Addr: cfg.ListenAddress,
|
||||||
|
Handler: httpHandler,
|
||||||
|
ReadHeaderTimeout: readHeaderTimeout,
|
||||||
|
ReadTimeout: readTimeout,
|
||||||
|
WriteTimeout: cfg.CheckTimeout + writeMargin,
|
||||||
|
IdleTimeout: idleTimeout,
|
||||||
|
MaxHeaderBytes: maxHeaderBytes,
|
||||||
|
TLSConfig: &tls.Config{MinVersion: tls.VersionTLS13},
|
||||||
|
ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelWarn),
|
||||||
|
}
|
||||||
|
serveErr := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
serveErr <- serve(httpServer, cfg, logger)
|
||||||
|
}()
|
||||||
|
used, labs := manager.Usage()
|
||||||
|
logger.InfoContext(ctx, "labd started",
|
||||||
|
slog.String("address", cfg.ListenAddress),
|
||||||
|
slog.Bool("tls", !cfg.AllowPlaintextHTTP),
|
||||||
|
slog.Int64("memory_budget_bytes", cfg.MemoryBudgetBytes),
|
||||||
|
slog.Int64("memory_used_bytes", used),
|
||||||
|
slog.Int("labs", labs),
|
||||||
|
slog.Int("templates", len(registry.All())),
|
||||||
|
)
|
||||||
|
|
||||||
|
var runErr error
|
||||||
|
select {
|
||||||
|
case runErr = <-serveErr:
|
||||||
|
case <-ctx.Done():
|
||||||
|
logger.InfoContext(ctx, "labd stopping")
|
||||||
|
}
|
||||||
|
manager.Drain()
|
||||||
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
|
||||||
|
defer cancel()
|
||||||
|
shutdownErr := httpServer.Shutdown(shutdownCtx)
|
||||||
|
stopReaper()
|
||||||
|
reaperDone.Wait()
|
||||||
|
return errors.Join(runErr, shutdownErr, manager.Close(shutdownCtx))
|
||||||
|
}
|
||||||
|
|
||||||
|
func serve(httpServer *http.Server, cfg config.Config, logger *slog.Logger) error {
|
||||||
|
var err error
|
||||||
|
if cfg.AllowPlaintextHTTP {
|
||||||
|
logger.Warn("serving plaintext HTTP; this switch is for local development only")
|
||||||
|
err = httpServer.ListenAndServe()
|
||||||
|
} else {
|
||||||
|
err = httpServer.ListenAndServeTLS(cfg.TLSCertFile, cfg.TLSKeyFile)
|
||||||
|
}
|
||||||
|
if errors.Is(err, http.ErrServerClosed) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return fmt.Errorf("app.serve - listen: %w", err)
|
||||||
|
}
|
||||||
@@ -0,0 +1,330 @@
|
|||||||
|
// Package config reads the labd configuration from the environment.
|
||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"net/netip"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Defaults of the labd settings. The management plane values match
|
||||||
|
// deploy/labs/lxd-preseed.yaml.
|
||||||
|
const (
|
||||||
|
DefaultListenAddress = "127.0.0.1:8445"
|
||||||
|
DefaultAllowedClients = "127.0.0.0/8,::1/128"
|
||||||
|
DefaultLXDSocket = "/var/snap/lxd/common/lxd/unix.socket"
|
||||||
|
DefaultLXDProject = "default"
|
||||||
|
DefaultStateFile = "/var/lib/lincodex-labd/labs.json"
|
||||||
|
DefaultMemoryBudgetMiB = 3072
|
||||||
|
DefaultMaxLabs = 0
|
||||||
|
DefaultMaxLifetime = 2 * time.Hour
|
||||||
|
DefaultProvisionTimeout = 5 * time.Minute
|
||||||
|
DefaultProbeInterval = 2 * time.Second
|
||||||
|
DefaultProbeTimeout = 2 * time.Second
|
||||||
|
DefaultRetryAfter = 30 * time.Second
|
||||||
|
DefaultSweepInterval = 15 * time.Second
|
||||||
|
DefaultReconcileInterval = 5 * time.Minute
|
||||||
|
DefaultDeletedRetention = time.Hour
|
||||||
|
DefaultConsoleTokenTTL = time.Minute
|
||||||
|
DefaultCheckTimeout = time.Minute
|
||||||
|
DefaultShutdownTimeout = 30 * time.Second
|
||||||
|
DefaultMaxRequestBytes = 64 << 10
|
||||||
|
DefaultManagementNetwork = "lxdbr-labmgmt"
|
||||||
|
DefaultManagementSubnet = "10.81.0.0/24"
|
||||||
|
DefaultManagementHost = "10.81.0.1"
|
||||||
|
DefaultManagementFirst = "10.81.0.16"
|
||||||
|
// MinTokenLength is the shortest accepted service token.
|
||||||
|
MinTokenLength = 32
|
||||||
|
// MaxConsoleTokenTTL is the contract bound of a console token.
|
||||||
|
MaxConsoleTokenTTL = 120 * time.Second
|
||||||
|
bytesPerMiB = 1 << 20
|
||||||
|
)
|
||||||
|
|
||||||
|
// Config is the validated labd configuration.
|
||||||
|
type Config struct {
|
||||||
|
ListenAddress string
|
||||||
|
TLSCertFile string
|
||||||
|
TLSKeyFile string
|
||||||
|
// AllowPlaintextHTTP serves HTTP without TLS, for local development only.
|
||||||
|
AllowPlaintextHTTP bool
|
||||||
|
APIToken string
|
||||||
|
// AllowedClients are the networks a request may come from. The token
|
||||||
|
// authorizes the caller; the list keeps every other network out even
|
||||||
|
// when the listener is reachable.
|
||||||
|
AllowedClients []netip.Prefix
|
||||||
|
|
||||||
|
LXDSocket string
|
||||||
|
LXDProject string
|
||||||
|
StateFile string
|
||||||
|
|
||||||
|
MemoryBudgetBytes int64
|
||||||
|
MaxLabs int
|
||||||
|
MaxLifetime time.Duration
|
||||||
|
ProvisionTimeout time.Duration
|
||||||
|
ProbeInterval time.Duration
|
||||||
|
ProbeTimeout time.Duration
|
||||||
|
RetryAfter time.Duration
|
||||||
|
SweepInterval time.Duration
|
||||||
|
ReconcileInterval time.Duration
|
||||||
|
DeletedRetention time.Duration
|
||||||
|
ConsoleTokenTTL time.Duration
|
||||||
|
CheckTimeout time.Duration
|
||||||
|
ShutdownTimeout time.Duration
|
||||||
|
MaxRequestBytes int64
|
||||||
|
|
||||||
|
ManagementNetwork string
|
||||||
|
ManagementSubnet netip.Prefix
|
||||||
|
ManagementHost netip.Addr
|
||||||
|
ManagementFirst netip.Addr
|
||||||
|
|
||||||
|
LogLevel slog.Level
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load reads the configuration from the process environment.
|
||||||
|
func Load() (Config, error) {
|
||||||
|
return parse(os.LookupEnv, os.ReadFile)
|
||||||
|
}
|
||||||
|
|
||||||
|
type (
|
||||||
|
lookupFunc func(string) (string, bool)
|
||||||
|
readFileFunc func(string) ([]byte, error)
|
||||||
|
)
|
||||||
|
|
||||||
|
func parse(lookup lookupFunc, readFile readFileFunc) (Config, error) {
|
||||||
|
r := reader{lookup: lookup}
|
||||||
|
cfg := Config{
|
||||||
|
ListenAddress: r.text("LABD_LISTEN_ADDRESS", DefaultListenAddress),
|
||||||
|
TLSCertFile: r.text("LABD_TLS_CERT_FILE", ""),
|
||||||
|
TLSKeyFile: r.text("LABD_TLS_KEY_FILE", ""),
|
||||||
|
AllowPlaintextHTTP: r.boolean("LABD_DEV_ALLOW_PLAINTEXT_HTTP"),
|
||||||
|
AllowedClients: r.prefixes("LABD_ALLOWED_CLIENTS", DefaultAllowedClients),
|
||||||
|
LXDSocket: r.text("LABD_LXD_SOCKET", DefaultLXDSocket),
|
||||||
|
LXDProject: r.text("LABD_LXD_PROJECT", DefaultLXDProject),
|
||||||
|
StateFile: r.text("LABD_STATE_FILE", DefaultStateFile),
|
||||||
|
MemoryBudgetBytes: r.int64("LABD_MEMORY_BUDGET_MIB", DefaultMemoryBudgetMiB) * bytesPerMiB,
|
||||||
|
MaxLabs: r.integer("LABD_MAX_LABS", DefaultMaxLabs),
|
||||||
|
MaxLifetime: r.duration("LABD_MAX_LIFETIME", DefaultMaxLifetime),
|
||||||
|
ProvisionTimeout: r.duration("LABD_PROVISION_TIMEOUT", DefaultProvisionTimeout),
|
||||||
|
ProbeInterval: r.duration("LABD_PROBE_INTERVAL", DefaultProbeInterval),
|
||||||
|
ProbeTimeout: r.duration("LABD_PROBE_TIMEOUT", DefaultProbeTimeout),
|
||||||
|
RetryAfter: r.duration("LABD_RETRY_AFTER", DefaultRetryAfter),
|
||||||
|
SweepInterval: r.duration("LABD_SWEEP_INTERVAL", DefaultSweepInterval),
|
||||||
|
ReconcileInterval: r.duration("LABD_RECONCILE_INTERVAL", DefaultReconcileInterval),
|
||||||
|
DeletedRetention: r.duration("LABD_DELETED_RETENTION", DefaultDeletedRetention),
|
||||||
|
ConsoleTokenTTL: r.duration("LABD_CONSOLE_TOKEN_TTL", DefaultConsoleTokenTTL),
|
||||||
|
CheckTimeout: r.duration("LABD_CHECK_TIMEOUT", DefaultCheckTimeout),
|
||||||
|
ShutdownTimeout: r.duration("LABD_SHUTDOWN_TIMEOUT", DefaultShutdownTimeout),
|
||||||
|
MaxRequestBytes: r.int64("LABD_MAX_REQUEST_BYTES", DefaultMaxRequestBytes),
|
||||||
|
ManagementNetwork: r.text("LABD_MGMT_NETWORK", DefaultManagementNetwork),
|
||||||
|
ManagementSubnet: r.prefix("LABD_MGMT_SUBNET", DefaultManagementSubnet),
|
||||||
|
ManagementHost: r.address("LABD_MGMT_HOST_ADDRESS", DefaultManagementHost),
|
||||||
|
ManagementFirst: r.address("LABD_MGMT_FIRST_ADDRESS", DefaultManagementFirst),
|
||||||
|
LogLevel: r.logLevel("LABD_LOG_LEVEL"),
|
||||||
|
}
|
||||||
|
cfg.APIToken = r.token(readFile)
|
||||||
|
// Report parse and validation errors together, so one start names every
|
||||||
|
// setting to fix.
|
||||||
|
if err := errors.Join(append(r.errs, cfg.validate())...); err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Config) validate() error {
|
||||||
|
return errors.Join(c.validateTransport(), c.validateLimits(), c.validatePlacement())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Config) validateTransport() error {
|
||||||
|
tlsSet := c.TLSCertFile != "" || c.TLSKeyFile != ""
|
||||||
|
switch {
|
||||||
|
case tlsSet && (c.TLSCertFile == "" || c.TLSKeyFile == ""):
|
||||||
|
return errors.New("config.validate - LABD_TLS_CERT_FILE and LABD_TLS_KEY_FILE must be set together")
|
||||||
|
case tlsSet && c.AllowPlaintextHTTP:
|
||||||
|
return errors.New("config.validate - LABD_DEV_ALLOW_PLAINTEXT_HTTP conflicts with TLS settings")
|
||||||
|
case !tlsSet && !c.AllowPlaintextHTTP:
|
||||||
|
return errors.New("config.validate - TLS is required: set LABD_TLS_CERT_FILE and LABD_TLS_KEY_FILE")
|
||||||
|
case len(c.AllowedClients) == 0:
|
||||||
|
return errors.New("config.validate - LABD_ALLOWED_CLIENTS must name at least one network")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Config) validateLimits() error {
|
||||||
|
var errs []error
|
||||||
|
positive := map[string]int64{
|
||||||
|
"LABD_MEMORY_BUDGET_MIB": c.MemoryBudgetBytes,
|
||||||
|
"LABD_MAX_LIFETIME": int64(c.MaxLifetime),
|
||||||
|
"LABD_PROVISION_TIMEOUT": int64(c.ProvisionTimeout),
|
||||||
|
"LABD_PROBE_INTERVAL": int64(c.ProbeInterval),
|
||||||
|
"LABD_PROBE_TIMEOUT": int64(c.ProbeTimeout),
|
||||||
|
"LABD_RETRY_AFTER": int64(c.RetryAfter),
|
||||||
|
"LABD_SWEEP_INTERVAL": int64(c.SweepInterval),
|
||||||
|
"LABD_RECONCILE_INTERVAL": int64(c.ReconcileInterval),
|
||||||
|
"LABD_DELETED_RETENTION": int64(c.DeletedRetention),
|
||||||
|
"LABD_CONSOLE_TOKEN_TTL": int64(c.ConsoleTokenTTL),
|
||||||
|
"LABD_CHECK_TIMEOUT": int64(c.CheckTimeout),
|
||||||
|
"LABD_SHUTDOWN_TIMEOUT": int64(c.ShutdownTimeout),
|
||||||
|
"LABD_MAX_REQUEST_BYTES": c.MaxRequestBytes,
|
||||||
|
}
|
||||||
|
for name, value := range positive {
|
||||||
|
if value <= 0 {
|
||||||
|
errs = append(errs, fmt.Errorf("config.validate - %s must be positive", name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if c.MaxLabs < 0 {
|
||||||
|
errs = append(errs, errors.New("config.validate - LABD_MAX_LABS must not be negative"))
|
||||||
|
}
|
||||||
|
if c.ConsoleTokenTTL > MaxConsoleTokenTTL {
|
||||||
|
errs = append(errs, errors.New("config.validate - LABD_CONSOLE_TOKEN_TTL must not exceed 120s"))
|
||||||
|
}
|
||||||
|
// The contract bounds a lifetime by 4 hours.
|
||||||
|
if c.MaxLifetime > 4*time.Hour {
|
||||||
|
errs = append(errs, errors.New("config.validate - LABD_MAX_LIFETIME must not exceed 4h"))
|
||||||
|
}
|
||||||
|
return errors.Join(errs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Config) validatePlacement() error {
|
||||||
|
var errs []error
|
||||||
|
for name, path := range map[string]string{"LABD_LXD_SOCKET": c.LXDSocket, "LABD_STATE_FILE": c.StateFile} {
|
||||||
|
if !filepath.IsAbs(path) {
|
||||||
|
errs = append(errs, fmt.Errorf("config.validate - %s must be an absolute path", name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if c.ManagementNetwork == "" || c.LXDProject == "" {
|
||||||
|
errs = append(errs, errors.New("config.validate - LABD_MGMT_NETWORK and LABD_LXD_PROJECT must not be empty"))
|
||||||
|
}
|
||||||
|
if !c.ManagementSubnet.IsValid() || !c.ManagementSubnet.Addr().Is4() ||
|
||||||
|
!c.ManagementSubnet.Contains(c.ManagementHost) || !c.ManagementSubnet.Contains(c.ManagementFirst) {
|
||||||
|
errs = append(errs, errors.New("config.validate - LABD_MGMT_HOST_ADDRESS and LABD_MGMT_FIRST_ADDRESS must be in the IPv4 LABD_MGMT_SUBNET"))
|
||||||
|
}
|
||||||
|
return errors.Join(errs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// reader collects parse errors so that one start reports every bad value.
|
||||||
|
type reader struct {
|
||||||
|
lookup lookupFunc
|
||||||
|
errs []error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *reader) text(name, fallback string) string {
|
||||||
|
value, ok := r.lookup(name)
|
||||||
|
if !ok || value == "" {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *reader) boolean(name string) bool {
|
||||||
|
value, ok := r.lookup(name)
|
||||||
|
if !ok || value == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
parsed, err := strconv.ParseBool(value)
|
||||||
|
if err != nil {
|
||||||
|
r.errs = append(r.errs, fmt.Errorf("config.reader.boolean - %s is not a boolean", name))
|
||||||
|
}
|
||||||
|
return parsed
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *reader) integer(name string, fallback int) int {
|
||||||
|
return int(r.int64(name, int64(fallback)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *reader) int64(name string, fallback int64) int64 {
|
||||||
|
value, ok := r.lookup(name)
|
||||||
|
if !ok || value == "" {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
parsed, err := strconv.ParseInt(value, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
r.errs = append(r.errs, fmt.Errorf("config.reader.int64 - %s is not an integer", name))
|
||||||
|
}
|
||||||
|
return parsed
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *reader) duration(name string, fallback time.Duration) time.Duration {
|
||||||
|
value, ok := r.lookup(name)
|
||||||
|
if !ok || value == "" {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
parsed, err := time.ParseDuration(value)
|
||||||
|
if err != nil {
|
||||||
|
r.errs = append(r.errs, fmt.Errorf("config.reader.duration - %s is not a duration", name))
|
||||||
|
}
|
||||||
|
return parsed
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *reader) prefix(name, fallback string) netip.Prefix {
|
||||||
|
parsed, err := netip.ParsePrefix(r.text(name, fallback))
|
||||||
|
if err != nil {
|
||||||
|
r.errs = append(r.errs, fmt.Errorf("config.reader.prefix - %s is not a network", name))
|
||||||
|
}
|
||||||
|
return parsed.Masked()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *reader) prefixes(name, fallback string) []netip.Prefix {
|
||||||
|
var result []netip.Prefix
|
||||||
|
for _, part := range strings.Split(r.text(name, fallback), ",") {
|
||||||
|
parsed, err := netip.ParsePrefix(strings.TrimSpace(part))
|
||||||
|
if err != nil {
|
||||||
|
r.errs = append(r.errs, fmt.Errorf("config.reader.prefixes - %s holds a value that is not a network", name))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
result = append(result, parsed.Masked())
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *reader) address(name, fallback string) netip.Addr {
|
||||||
|
parsed, err := netip.ParseAddr(r.text(name, fallback))
|
||||||
|
if err != nil {
|
||||||
|
r.errs = append(r.errs, fmt.Errorf("config.reader.address - %s is not an address", name))
|
||||||
|
}
|
||||||
|
return parsed
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *reader) logLevel(name string) slog.Level {
|
||||||
|
value, ok := r.lookup(name)
|
||||||
|
if !ok || value == "" {
|
||||||
|
return slog.LevelInfo
|
||||||
|
}
|
||||||
|
var level slog.Level
|
||||||
|
if err := level.UnmarshalText([]byte(value)); err != nil {
|
||||||
|
r.errs = append(r.errs, fmt.Errorf("config.reader.logLevel - %s is not a log level", name))
|
||||||
|
}
|
||||||
|
return level
|
||||||
|
}
|
||||||
|
|
||||||
|
// token reads the service token from LABD_API_TOKEN_FILE or, failing that,
|
||||||
|
// LABD_API_TOKEN. The value never appears in an error.
|
||||||
|
func (r *reader) token(readFile readFileFunc) string {
|
||||||
|
file := r.text("LABD_API_TOKEN_FILE", "")
|
||||||
|
direct := r.text("LABD_API_TOKEN", "")
|
||||||
|
var token string
|
||||||
|
switch {
|
||||||
|
case file != "" && direct != "":
|
||||||
|
r.errs = append(r.errs, errors.New("config.reader.token - set LABD_API_TOKEN_FILE or LABD_API_TOKEN, not both"))
|
||||||
|
return ""
|
||||||
|
case file != "":
|
||||||
|
content, err := readFile(file)
|
||||||
|
if err != nil {
|
||||||
|
r.errs = append(r.errs, fmt.Errorf("config.reader.token - read LABD_API_TOKEN_FILE: %w", err))
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
token = strings.TrimSpace(string(content))
|
||||||
|
default:
|
||||||
|
token = direct
|
||||||
|
}
|
||||||
|
if len(token) < MinTokenLength {
|
||||||
|
r.errs = append(r.errs, fmt.Errorf("config.reader.token - the service token must have at least %d characters", MinTokenLength))
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return token
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/netip"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const testToken = "0123456789abcdef0123456789abcdef"
|
||||||
|
|
||||||
|
func lookupFrom(values map[string]string) lookupFunc {
|
||||||
|
return func(name string) (string, bool) {
|
||||||
|
value, ok := values[name]
|
||||||
|
return value, ok
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func noFiles(string) ([]byte, error) { return nil, errors.New("no file") }
|
||||||
|
|
||||||
|
func TestDefaultsNeedTLSAndAToken(t *testing.T) {
|
||||||
|
_, err := parse(lookupFrom(nil), noFiles)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "TLS is required") || !strings.Contains(err.Error(), "service token") {
|
||||||
|
t.Fatalf("parse() error = %v, want TLS and token errors together", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseReadsEverySetting(t *testing.T) {
|
||||||
|
cfg, err := parse(lookupFrom(map[string]string{
|
||||||
|
"LABD_TLS_CERT_FILE": "/etc/lincodex-labd/tls.crt",
|
||||||
|
"LABD_TLS_KEY_FILE": "/etc/lincodex-labd/tls.key",
|
||||||
|
"LABD_API_TOKEN_FILE": "/etc/lincodex-labd/api-token",
|
||||||
|
"LABD_ALLOWED_CLIENTS": "172.29.79.0/24, 127.0.0.1/32",
|
||||||
|
"LABD_MEMORY_BUDGET_MIB": "6144",
|
||||||
|
"LABD_MAX_LABS": "4",
|
||||||
|
"LABD_MAX_LIFETIME": "90m",
|
||||||
|
"LABD_CONSOLE_TOKEN_TTL": "2m",
|
||||||
|
"LABD_MGMT_FIRST_ADDRESS": "10.81.0.32",
|
||||||
|
}), func(string) ([]byte, error) { return []byte(testToken + "\n"), nil })
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parse() error = %v", err)
|
||||||
|
}
|
||||||
|
if cfg.APIToken != testToken || cfg.MemoryBudgetBytes != 6144<<20 || cfg.MaxLabs != 4 ||
|
||||||
|
cfg.MaxLifetime != 90*time.Minute || cfg.ConsoleTokenTTL != 2*time.Minute ||
|
||||||
|
cfg.ManagementFirst != netip.MustParseAddr("10.81.0.32") || len(cfg.AllowedClients) != 2 ||
|
||||||
|
cfg.AllowedClients[0] != netip.MustParsePrefix("172.29.79.0/24") {
|
||||||
|
t.Fatalf("parse() = %+v", cfg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseRejectsUnsafeValues(t *testing.T) {
|
||||||
|
base := map[string]string{"LABD_DEV_ALLOW_PLAINTEXT_HTTP": "true", "LABD_API_TOKEN": testToken}
|
||||||
|
tests := map[string]map[string]string{
|
||||||
|
"short token": {"LABD_API_TOKEN": "short"},
|
||||||
|
"token twice": {"LABD_API_TOKEN_FILE": "/run/token"},
|
||||||
|
"plaintext with TLS": {"LABD_TLS_CERT_FILE": "/a", "LABD_TLS_KEY_FILE": "/b"},
|
||||||
|
"no budget": {"LABD_MEMORY_BUDGET_MIB": "0"},
|
||||||
|
"negative lab cap": {"LABD_MAX_LABS": "-1"},
|
||||||
|
"console token too long": {"LABD_CONSOLE_TOKEN_TTL": "3m"},
|
||||||
|
"lifetime above 4h": {"LABD_MAX_LIFETIME": "5h"},
|
||||||
|
"relative state file": {"LABD_STATE_FILE": "labs.json"},
|
||||||
|
"host outside subnet": {"LABD_MGMT_HOST_ADDRESS": "10.82.0.1"},
|
||||||
|
"bad client network": {"LABD_ALLOWED_CLIENTS": "backend"},
|
||||||
|
"bad duration": {"LABD_SWEEP_INTERVAL": "often"},
|
||||||
|
}
|
||||||
|
for name, change := range tests {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
values := map[string]string{}
|
||||||
|
for key, value := range base {
|
||||||
|
values[key] = value
|
||||||
|
}
|
||||||
|
for key, value := range change {
|
||||||
|
values[key] = value
|
||||||
|
}
|
||||||
|
if _, err := parse(lookupFrom(values), noFiles); err == nil {
|
||||||
|
t.Fatal("parse() accepted the value")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTokenNeverAppearsInErrors(t *testing.T) {
|
||||||
|
secret := "secret-token-marker"
|
||||||
|
_, err := parse(lookupFrom(map[string]string{"LABD_API_TOKEN": secret}), noFiles)
|
||||||
|
if err == nil || strings.Contains(err.Error(), secret) {
|
||||||
|
t.Fatalf("parse() error = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
// Package lab holds the persisted record of a lab and the names of its LXD
|
||||||
|
// objects.
|
||||||
|
package lab
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"net/netip"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// State is the lifecycle state of a lab record.
|
||||||
|
type State string
|
||||||
|
|
||||||
|
const (
|
||||||
|
Provisioning State = "provisioning"
|
||||||
|
Ready State = "ready"
|
||||||
|
Deleting State = "deleting"
|
||||||
|
Deleted State = "deleted"
|
||||||
|
Failed State = "failed"
|
||||||
|
)
|
||||||
|
|
||||||
|
// FailureReason says why a lab failed. None depends on the lab user.
|
||||||
|
type FailureReason string
|
||||||
|
|
||||||
|
const (
|
||||||
|
FailureProvisioning FailureReason = "provisioning_failed"
|
||||||
|
FailureTimedOut FailureReason = "provisioning_timed_out"
|
||||||
|
FailureInterrupted FailureReason = "interrupted"
|
||||||
|
)
|
||||||
|
|
||||||
|
// LXD markers. Every instance and bridge that labd creates carries the lab ID
|
||||||
|
// in ConfigLab and a name with its prefix; reconciliation deletes only
|
||||||
|
// objects that have both, so an object that an operator created by hand is
|
||||||
|
// never touched.
|
||||||
|
const (
|
||||||
|
ConfigLab = "user.lincodex.lab"
|
||||||
|
ConfigNode = "user.lincodex.node"
|
||||||
|
ConfigExpiresAt = "user.lincodex.expires-at"
|
||||||
|
InstancePrefix = "lcxl-"
|
||||||
|
// BridgePrefix is short because a Linux interface name, and so an LXD
|
||||||
|
// bridge name, has at most 15 characters.
|
||||||
|
BridgePrefix = "lxl"
|
||||||
|
|
||||||
|
shortIDBytes = 5
|
||||||
|
// MaxBridges bounds the links of a lab by the two-digit bridge suffix.
|
||||||
|
MaxBridges = 100
|
||||||
|
)
|
||||||
|
|
||||||
|
// Node is a node of a lab with its LXD instance and management address.
|
||||||
|
type Node struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Instance string `json:"instance"`
|
||||||
|
ManagementAddress netip.Addr `json:"management_address"`
|
||||||
|
ManagementPort uint16 `json:"management_port"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lab is the durable record of one lab. labd writes it before it creates any
|
||||||
|
// LXD object and removes it only after every object is gone, so a restart
|
||||||
|
// always knows what to delete.
|
||||||
|
type Lab struct {
|
||||||
|
ID uuid.UUID `json:"id"`
|
||||||
|
TemplateID string `json:"template_id"`
|
||||||
|
TemplateVersion int `json:"template_version"`
|
||||||
|
// Seed is the variant seed in hex. The state file is readable only by
|
||||||
|
// the labd user.
|
||||||
|
Seed string `json:"seed"`
|
||||||
|
Fingerprint string `json:"fingerprint"`
|
||||||
|
State State `json:"state"`
|
||||||
|
FailureReason FailureReason `json:"failure_reason,omitempty"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
ReadyAt time.Time `json:"ready_at,omitzero"`
|
||||||
|
ExpiresAt time.Time `json:"expires_at"`
|
||||||
|
// DeletedAt is set once every instance and bridge of the lab is gone.
|
||||||
|
// Until then the lab holds its memory and addresses.
|
||||||
|
DeletedAt time.Time `json:"deleted_at,omitzero"`
|
||||||
|
MemoryBytes int64 `json:"memory_bytes"`
|
||||||
|
Nodes []Node `json:"nodes"`
|
||||||
|
Bridges []string `json:"bridges"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// HoldsResources reports whether LXD objects of the lab may exist.
|
||||||
|
func (l *Lab) HoldsResources() bool { return l.DeletedAt.IsZero() }
|
||||||
|
|
||||||
|
// NeedsTeardown reports whether the lab ended but its objects may remain.
|
||||||
|
func (l *Lab) NeedsTeardown() bool {
|
||||||
|
return l.HoldsResources() && (l.State == Deleting || l.State == Failed)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Active reports whether the lab is provisioning or ready.
|
||||||
|
func (l *Lab) Active() bool { return l.State == Provisioning || l.State == Ready }
|
||||||
|
|
||||||
|
// Node returns the node with the given template name.
|
||||||
|
func (l *Lab) Node(name string) (Node, bool) {
|
||||||
|
for _, node := range l.Nodes {
|
||||||
|
if node.Name == name {
|
||||||
|
return node, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Node{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clone returns a deep copy that a caller may keep without the lock.
|
||||||
|
func (l *Lab) Clone() Lab {
|
||||||
|
clone := *l
|
||||||
|
clone.Nodes = slices.Clone(l.Nodes)
|
||||||
|
clone.Bridges = slices.Clone(l.Bridges)
|
||||||
|
return clone
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShortID is the part of the lab ID used in LXD object names.
|
||||||
|
func ShortID(id uuid.UUID) string { return hex.EncodeToString(id[:shortIDBytes]) }
|
||||||
|
|
||||||
|
// InstanceName is the LXD instance name of a node.
|
||||||
|
func InstanceName(id uuid.UUID, node string) string {
|
||||||
|
return InstancePrefix + ShortID(id) + "-" + node
|
||||||
|
}
|
||||||
|
|
||||||
|
// BridgeName is the LXD network name of the link with the given index.
|
||||||
|
func BridgeName(id uuid.UUID, index int) string {
|
||||||
|
return fmt.Sprintf("%s%s%02d", BridgePrefix, ShortID(id), index)
|
||||||
|
}
|
||||||
|
|
||||||
|
// OwnedInstance reports whether an instance name and config mark it as a lab
|
||||||
|
// node created by labd.
|
||||||
|
func OwnedInstance(name string, config map[string]string) bool {
|
||||||
|
return strings.HasPrefix(name, InstancePrefix) && config[ConfigLab] != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// OwnedBridge reports whether a network name and config mark it as a lab
|
||||||
|
// link bridge created by labd.
|
||||||
|
func OwnedBridge(name string, config map[string]string) bool {
|
||||||
|
return strings.HasPrefix(name, BridgePrefix) && config[ConfigLab] != ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,341 @@
|
|||||||
|
// Package lxd is a small client of the LXD REST API over its unix socket.
|
||||||
|
//
|
||||||
|
// labd needs a dozen calls: list, create, start, stop, and delete instances
|
||||||
|
// and bridge networks, and wait for their operations. The official client
|
||||||
|
// (github.com/canonical/lxd/client) is AGPL-3.0 since LXD 5.20 and pulls in
|
||||||
|
// much of the LXD tree, so this package speaks the documented REST API with
|
||||||
|
// net/http instead.
|
||||||
|
package lxd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// maxResponseBytes bounds a response body; the largest one is a list of
|
||||||
|
// instances with their config.
|
||||||
|
maxResponseBytes = 8 << 20
|
||||||
|
// operationWaitSeconds is the server-side wait of one poll of an
|
||||||
|
// operation; the context bounds the whole wait.
|
||||||
|
operationWaitSeconds = 30
|
||||||
|
startTimeoutSeconds = 60
|
||||||
|
stopTimeoutSeconds = 30
|
||||||
|
idleConnTimeout = 30 * time.Second
|
||||||
|
maxIdleConns = 4
|
||||||
|
operationsPrefix = "/1.0/operations/"
|
||||||
|
statusRunning = "Running"
|
||||||
|
// Operation status codes of the LXD API.
|
||||||
|
operationSuccess = 200
|
||||||
|
operationFailure = 400
|
||||||
|
operationCancelled = 401
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrNotFound means that LXD does not hold the object.
|
||||||
|
var ErrNotFound = errors.New("lxd object not found")
|
||||||
|
|
||||||
|
// APIError is an error answer of the LXD API. Message is the LXD text; it may
|
||||||
|
// name objects and paths of the host and is only logged, never returned to a
|
||||||
|
// client of labd.
|
||||||
|
type APIError struct {
|
||||||
|
Code int
|
||||||
|
Message string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *APIError) Error() string { return fmt.Sprintf("lxd error %d: %s", e.Code, e.Message) }
|
||||||
|
|
||||||
|
// InstanceSpec is a new instance copied from a prepared snapshot.
|
||||||
|
type InstanceSpec struct {
|
||||||
|
Name string
|
||||||
|
Description string
|
||||||
|
// Source is the snapshot to copy, as instance/snapshot.
|
||||||
|
Source string
|
||||||
|
Profiles []string
|
||||||
|
Config map[string]string
|
||||||
|
Devices map[string]map[string]string
|
||||||
|
}
|
||||||
|
|
||||||
|
// NetworkSpec is a new bridge network.
|
||||||
|
type NetworkSpec struct {
|
||||||
|
Name string
|
||||||
|
Description string
|
||||||
|
Config map[string]string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Instance is an instance as listed by LXD.
|
||||||
|
type Instance struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
Config map[string]string `json:"config"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Network is a network as listed by LXD.
|
||||||
|
type Network struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Managed bool `json:"managed"`
|
||||||
|
Config map[string]string `json:"config"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Client calls the LXD API.
|
||||||
|
type Client struct {
|
||||||
|
httpClient *http.Client
|
||||||
|
baseURL string
|
||||||
|
project string
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewUnix returns a client of the LXD socket at socketPath for one project.
|
||||||
|
func NewUnix(socketPath, project string) *Client {
|
||||||
|
transport := &http.Transport{
|
||||||
|
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||||
|
var dialer net.Dialer
|
||||||
|
return dialer.DialContext(ctx, "unix", socketPath)
|
||||||
|
},
|
||||||
|
Proxy: nil,
|
||||||
|
MaxIdleConns: maxIdleConns,
|
||||||
|
IdleConnTimeout: idleConnTimeout,
|
||||||
|
DisableCompression: true,
|
||||||
|
}
|
||||||
|
return NewWithHTTPClient(&http.Client{Transport: transport}, "http://lxd", project)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewWithHTTPClient returns a client that sends requests to baseURL with
|
||||||
|
// httpClient. Tests use it with an httptest server.
|
||||||
|
func NewWithHTTPClient(httpClient *http.Client, baseURL, project string) *Client {
|
||||||
|
client := *httpClient
|
||||||
|
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
||||||
|
return &Client{httpClient: &client, baseURL: strings.TrimSuffix(baseURL, "/"), project: project}
|
||||||
|
}
|
||||||
|
|
||||||
|
type envelope struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Operation string `json:"operation"`
|
||||||
|
ErrorCode int `json:"error_code"`
|
||||||
|
Error string `json:"error"`
|
||||||
|
Metadata json.RawMessage `json:"metadata"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type operation struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
StatusCode int `json:"status_code"`
|
||||||
|
Err string `json:"err"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ping checks that the API answers.
|
||||||
|
func (c *Client) Ping(ctx context.Context) error {
|
||||||
|
_, err := c.do(ctx, http.MethodGet, "/1.0", nil, nil)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListInstances returns every instance of the project.
|
||||||
|
func (c *Client) ListInstances(ctx context.Context) ([]Instance, error) {
|
||||||
|
answer, err := c.do(ctx, http.MethodGet, "/1.0/instances", url.Values{"recursion": {"1"}}, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var instances []Instance
|
||||||
|
if err := json.Unmarshal(answer.Metadata, &instances); err != nil {
|
||||||
|
return nil, fmt.Errorf("Client.ListInstances - decode: %w", err)
|
||||||
|
}
|
||||||
|
return instances, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateInstance copies a virtual machine from spec.Source and waits for the
|
||||||
|
// copy to finish. The instance is not started.
|
||||||
|
func (c *Client) CreateInstance(ctx context.Context, spec InstanceSpec) error {
|
||||||
|
body := map[string]any{
|
||||||
|
"name": spec.Name,
|
||||||
|
"description": spec.Description,
|
||||||
|
"type": "virtual-machine",
|
||||||
|
"source": map[string]any{"type": "copy", "source": spec.Source, "instance_only": true},
|
||||||
|
"profiles": spec.Profiles,
|
||||||
|
"config": spec.Config,
|
||||||
|
"devices": spec.Devices,
|
||||||
|
}
|
||||||
|
answer, err := c.do(ctx, http.MethodPost, "/1.0/instances", nil, body)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return c.wait(ctx, answer)
|
||||||
|
}
|
||||||
|
|
||||||
|
// InstanceRunning reports whether the instance runs.
|
||||||
|
func (c *Client) InstanceRunning(ctx context.Context, name string) (bool, error) {
|
||||||
|
answer, err := c.do(ctx, http.MethodGet, "/1.0/instances/"+url.PathEscape(name)+"/state", nil, nil)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
var state struct {
|
||||||
|
Status string `json:"status"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(answer.Metadata, &state); err != nil {
|
||||||
|
return false, fmt.Errorf("Client.InstanceRunning - decode: %w", err)
|
||||||
|
}
|
||||||
|
return state.Status == statusRunning, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartInstance starts an instance and waits for LXD to report it started.
|
||||||
|
func (c *Client) StartInstance(ctx context.Context, name string) error {
|
||||||
|
return c.changeState(ctx, name, map[string]any{"action": "start", "timeout": startTimeoutSeconds})
|
||||||
|
}
|
||||||
|
|
||||||
|
// StopInstance stops a running instance at once; a stopped one is left as
|
||||||
|
// it is.
|
||||||
|
func (c *Client) StopInstance(ctx context.Context, name string) error {
|
||||||
|
running, err := c.InstanceRunning(ctx, name)
|
||||||
|
if err != nil || !running {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return c.changeState(ctx, name, map[string]any{"action": "stop", "force": true, "timeout": stopTimeoutSeconds})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) changeState(ctx context.Context, name string, body map[string]any) error {
|
||||||
|
answer, err := c.do(ctx, http.MethodPut, "/1.0/instances/"+url.PathEscape(name)+"/state", nil, body)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return c.wait(ctx, answer)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteInstance deletes a stopped instance with its root volume.
|
||||||
|
func (c *Client) DeleteInstance(ctx context.Context, name string) error {
|
||||||
|
answer, err := c.do(ctx, http.MethodDelete, "/1.0/instances/"+url.PathEscape(name), nil, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return c.wait(ctx, answer)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListNetworks returns every network of the project.
|
||||||
|
func (c *Client) ListNetworks(ctx context.Context) ([]Network, error) {
|
||||||
|
answer, err := c.do(ctx, http.MethodGet, "/1.0/networks", url.Values{"recursion": {"1"}}, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var networks []Network
|
||||||
|
if err := json.Unmarshal(answer.Metadata, &networks); err != nil {
|
||||||
|
return nil, fmt.Errorf("Client.ListNetworks - decode: %w", err)
|
||||||
|
}
|
||||||
|
return networks, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateNetwork creates a managed bridge.
|
||||||
|
func (c *Client) CreateNetwork(ctx context.Context, spec NetworkSpec) error {
|
||||||
|
body := map[string]any{"name": spec.Name, "description": spec.Description, "type": "bridge", "config": spec.Config}
|
||||||
|
answer, err := c.do(ctx, http.MethodPost, "/1.0/networks", nil, body)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return c.wait(ctx, answer)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteNetwork deletes a managed network that no instance uses.
|
||||||
|
func (c *Client) DeleteNetwork(ctx context.Context, name string) error {
|
||||||
|
answer, err := c.do(ctx, http.MethodDelete, "/1.0/networks/"+url.PathEscape(name), nil, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return c.wait(ctx, answer)
|
||||||
|
}
|
||||||
|
|
||||||
|
// wait follows an asynchronous answer until its operation ends.
|
||||||
|
func (c *Client) wait(ctx context.Context, answer envelope) error {
|
||||||
|
if answer.Type != "async" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
id := strings.TrimPrefix(answer.Operation, operationsPrefix)
|
||||||
|
if id == "" || strings.Contains(id, "/") {
|
||||||
|
return errors.New("Client.wait - the answer names no operation")
|
||||||
|
}
|
||||||
|
query := url.Values{"timeout": {fmt.Sprint(operationWaitSeconds)}}
|
||||||
|
for {
|
||||||
|
result, err := c.do(ctx, http.MethodGet, operationsPrefix+url.PathEscape(id)+"/wait", query, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var state operation
|
||||||
|
if err := json.Unmarshal(result.Metadata, &state); err != nil {
|
||||||
|
return fmt.Errorf("Client.wait - decode: %w", err)
|
||||||
|
}
|
||||||
|
switch state.StatusCode {
|
||||||
|
case operationSuccess:
|
||||||
|
return nil
|
||||||
|
case operationFailure, operationCancelled:
|
||||||
|
return &APIError{Code: state.StatusCode, Message: state.Err}
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) do(ctx context.Context, method, path string, query url.Values, body any) (envelope, error) {
|
||||||
|
request, err := c.newRequest(ctx, method, path, query, body)
|
||||||
|
if err != nil {
|
||||||
|
return envelope{}, err
|
||||||
|
}
|
||||||
|
response, err := c.httpClient.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return envelope{}, fmt.Errorf("Client.do - %s %s: %w", method, path, err)
|
||||||
|
}
|
||||||
|
defer func() { _ = response.Body.Close() }() // The body was read or is discarded.
|
||||||
|
content, err := io.ReadAll(io.LimitReader(response.Body, maxResponseBytes+1))
|
||||||
|
if err != nil {
|
||||||
|
return envelope{}, fmt.Errorf("Client.do - read: %w", err)
|
||||||
|
}
|
||||||
|
if len(content) > maxResponseBytes {
|
||||||
|
return envelope{}, errors.New("Client.do - the LXD answer is too large")
|
||||||
|
}
|
||||||
|
var answer envelope
|
||||||
|
if err := json.Unmarshal(content, &answer); err != nil {
|
||||||
|
return envelope{}, fmt.Errorf("Client.do - %s %s answered %d without an LXD body", method, path, response.StatusCode)
|
||||||
|
}
|
||||||
|
if answer.Type != "error" && response.StatusCode < http.StatusBadRequest {
|
||||||
|
return answer, nil
|
||||||
|
}
|
||||||
|
code := answer.ErrorCode
|
||||||
|
if code == 0 {
|
||||||
|
code = response.StatusCode
|
||||||
|
}
|
||||||
|
if code == http.StatusNotFound {
|
||||||
|
return envelope{}, fmt.Errorf("Client.do - %s %s: %w", method, path, ErrNotFound)
|
||||||
|
}
|
||||||
|
return envelope{}, &APIError{Code: code, Message: answer.Error}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) newRequest(ctx context.Context, method, path string, query url.Values, body any) (*http.Request, error) {
|
||||||
|
if query == nil {
|
||||||
|
query = url.Values{}
|
||||||
|
}
|
||||||
|
if c.project != "" {
|
||||||
|
query.Set("project", c.project)
|
||||||
|
}
|
||||||
|
target := c.baseURL + path
|
||||||
|
if encoded := query.Encode(); encoded != "" {
|
||||||
|
target += "?" + encoded
|
||||||
|
}
|
||||||
|
var reader io.Reader = http.NoBody
|
||||||
|
if body != nil {
|
||||||
|
encoded, err := json.Marshal(body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("Client.newRequest - encode: %w", err)
|
||||||
|
}
|
||||||
|
reader = bytes.NewReader(encoded)
|
||||||
|
}
|
||||||
|
request, err := http.NewRequestWithContext(ctx, method, target, reader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("Client.newRequest - request: %w", err)
|
||||||
|
}
|
||||||
|
if body != nil {
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
}
|
||||||
|
return request, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
package lxd_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"lincodex/labd/internal/lxd"
|
||||||
|
)
|
||||||
|
|
||||||
|
// apiStub answers like the LXD API: requests are recorded, and mutating
|
||||||
|
// calls return an async operation that the client must wait for.
|
||||||
|
type apiStub struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
requests []string
|
||||||
|
bodies map[string]map[string]any
|
||||||
|
waits int
|
||||||
|
running bool
|
||||||
|
failOp bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *apiStub) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
key := r.Method + " " + r.URL.Path
|
||||||
|
s.requests = append(s.requests, key+"?"+r.URL.RawQuery)
|
||||||
|
if r.Body != nil && r.ContentLength != 0 {
|
||||||
|
var body map[string]any
|
||||||
|
_ = json.NewDecoder(r.Body).Decode(&body) // A stub; malformed bodies fail the assertions.
|
||||||
|
s.bodies[key] = body
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case key == "GET /1.0/instances":
|
||||||
|
writeSync(w, []map[string]any{{"name": "lcxl-0102030405-r1", "status": "Running", "config": map[string]string{"user.lincodex.lab": "x"}}})
|
||||||
|
case key == "GET /1.0/instances/lcxl-0102030405-r1/state":
|
||||||
|
status := "Stopped"
|
||||||
|
if s.running {
|
||||||
|
status = "Running"
|
||||||
|
}
|
||||||
|
writeSync(w, map[string]any{"status": status})
|
||||||
|
case key == "DELETE /1.0/instances/missing", key == "DELETE /1.0/networks/missing":
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
_, _ = w.Write([]byte(`{"type":"error","error":"Not found","error_code":404}`))
|
||||||
|
case key == "POST /1.0/networks":
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
_, _ = w.Write([]byte(`{"type":"error","error":"The network already exists","error_code":400}`))
|
||||||
|
case strings.HasPrefix(key, "GET /1.0/operations/op-1/wait"):
|
||||||
|
s.waits++
|
||||||
|
code := 103
|
||||||
|
if s.waits > 1 {
|
||||||
|
code = 200
|
||||||
|
if s.failOp {
|
||||||
|
code = 400
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writeSync(w, map[string]any{"id": "op-1", "status_code": code, "err": "copy failed"})
|
||||||
|
case r.Method == http.MethodPost || r.Method == http.MethodPut || r.Method == http.MethodDelete:
|
||||||
|
w.WriteHeader(http.StatusAccepted)
|
||||||
|
_, _ = w.Write([]byte(`{"type":"async","status_code":100,"operation":"/1.0/operations/op-1","metadata":{}}`))
|
||||||
|
default:
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeSync(w http.ResponseWriter, metadata any) {
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"type": "sync", "status_code": 200, "metadata": metadata})
|
||||||
|
}
|
||||||
|
|
||||||
|
func newStub(t *testing.T) (*apiStub, *lxd.Client) {
|
||||||
|
t.Helper()
|
||||||
|
stub := &apiStub{bodies: map[string]map[string]any{}}
|
||||||
|
server := httptest.NewServer(stub)
|
||||||
|
t.Cleanup(server.Close)
|
||||||
|
return stub, lxd.NewWithHTTPClient(server.Client(), server.URL, "labs")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateInstanceCopiesTheSnapshotAndWaitsForTheOperation(t *testing.T) {
|
||||||
|
stub, client := newStub(t)
|
||||||
|
err := client.CreateInstance(context.Background(), lxd.InstanceSpec{
|
||||||
|
Name: "lcxl-0102030405-r1", Source: "lincodex-tpl-chr/base", Profiles: []string{"lincodex-lab-small"},
|
||||||
|
Config: map[string]string{"user.lincodex.lab": "x"},
|
||||||
|
Devices: map[string]map[string]string{"eth1": {"type": "nic", "network": "lxl010203040500"}},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("CreateInstance() error = %v", err)
|
||||||
|
}
|
||||||
|
body := stub.bodies["POST /1.0/instances"]
|
||||||
|
source, _ := body["source"].(map[string]any)
|
||||||
|
if body["type"] != "virtual-machine" || source["type"] != "copy" || source["source"] != "lincodex-tpl-chr/base" {
|
||||||
|
t.Fatalf("create body = %v", body)
|
||||||
|
}
|
||||||
|
if stub.waits != 2 {
|
||||||
|
t.Fatalf("operation polls = %d, want 2 (running, then success)", stub.waits)
|
||||||
|
}
|
||||||
|
for _, request := range stub.requests {
|
||||||
|
if !strings.Contains(request, "project=labs") {
|
||||||
|
t.Fatalf("request %q does not name the project", request)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFailedOperationIsAnAPIError(t *testing.T) {
|
||||||
|
stub, client := newStub(t)
|
||||||
|
stub.failOp = true
|
||||||
|
err := client.DeleteInstance(context.Background(), "lcxl-0102030405-r1")
|
||||||
|
var apiErr *lxd.APIError
|
||||||
|
if !errors.As(err, &apiErr) || apiErr.Code != 400 {
|
||||||
|
t.Fatalf("DeleteInstance() error = %v, want an APIError 400", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMissingObjectsAreNotFound(t *testing.T) {
|
||||||
|
_, client := newStub(t)
|
||||||
|
if err := client.DeleteInstance(context.Background(), "missing"); !errors.Is(err, lxd.ErrNotFound) {
|
||||||
|
t.Fatalf("DeleteInstance() error = %v, want ErrNotFound", err)
|
||||||
|
}
|
||||||
|
if err := client.DeleteNetwork(context.Background(), "missing"); !errors.Is(err, lxd.ErrNotFound) {
|
||||||
|
t.Fatalf("DeleteNetwork() error = %v, want ErrNotFound", err)
|
||||||
|
}
|
||||||
|
var apiErr *lxd.APIError
|
||||||
|
if err := client.CreateNetwork(context.Background(), lxd.NetworkSpec{Name: "lxl010203040500"}); !errors.As(err, &apiErr) {
|
||||||
|
t.Fatalf("CreateNetwork() error = %v, want an APIError", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStopInstanceSkipsAStoppedInstance(t *testing.T) {
|
||||||
|
stub, client := newStub(t)
|
||||||
|
if err := client.StopInstance(context.Background(), "lcxl-0102030405-r1"); err != nil {
|
||||||
|
t.Fatalf("StopInstance() error = %v", err)
|
||||||
|
}
|
||||||
|
if _, sent := stub.bodies["PUT /1.0/instances/lcxl-0102030405-r1/state"]; sent {
|
||||||
|
t.Fatal("StopInstance() sent a stop for a stopped instance")
|
||||||
|
}
|
||||||
|
stub.running = true
|
||||||
|
if err := client.StopInstance(context.Background(), "lcxl-0102030405-r1"); err != nil {
|
||||||
|
t.Fatalf("StopInstance() error = %v", err)
|
||||||
|
}
|
||||||
|
body := stub.bodies["PUT /1.0/instances/lcxl-0102030405-r1/state"]
|
||||||
|
if body["action"] != "stop" || body["force"] != true {
|
||||||
|
t.Fatalf("stop body = %v", body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestListInstancesDecodesConfig(t *testing.T) {
|
||||||
|
_, client := newStub(t)
|
||||||
|
instances, err := client.ListInstances(context.Background())
|
||||||
|
if err != nil || len(instances) != 1 || instances[0].Config["user.lincodex.lab"] != "x" {
|
||||||
|
t.Fatalf("ListInstances() = %+v, %v", instances, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
package lxd_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"slices"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"lincodex/labd/internal/lxd"
|
||||||
|
)
|
||||||
|
|
||||||
|
const liveTimeout = 5 * time.Minute
|
||||||
|
|
||||||
|
// TestLiveLXD creates one lab bridge and one instance copied from a prepared
|
||||||
|
// snapshot on a real LXD, checks that they appear, and deletes them. It runs
|
||||||
|
// only with LABD_LIVE_SOCKET and LABD_LIVE_SOURCE set (make -C labd
|
||||||
|
// test-live) and is meant for a test host, never the production app host.
|
||||||
|
// LABD_LIVE_START=1 also boots the instance, which needs KVM.
|
||||||
|
func TestLiveLXD(t *testing.T) {
|
||||||
|
socket, source := os.Getenv("LABD_LIVE_SOCKET"), os.Getenv("LABD_LIVE_SOURCE")
|
||||||
|
if socket == "" || source == "" {
|
||||||
|
t.Skip("set LABD_LIVE_SOCKET and LABD_LIVE_SOURCE to run against a real LXD")
|
||||||
|
}
|
||||||
|
project := envOr("LABD_LIVE_PROJECT", "default")
|
||||||
|
profile := envOr("LABD_LIVE_PROFILE", "lincodex-lab-small")
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), liveTimeout)
|
||||||
|
defer cancel()
|
||||||
|
client := lxd.NewUnix(socket, project)
|
||||||
|
if err := client.Ping(ctx); err != nil {
|
||||||
|
t.Fatalf("Ping() error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
suffix := randomHex(t, 3)
|
||||||
|
bridge := "lxllive" + suffix
|
||||||
|
instance := "lcxl-live-" + suffix
|
||||||
|
marker := map[string]string{"user.lincodex.lab": "live-test-" + suffix}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
// Best effort if an assertion stopped the test half way.
|
||||||
|
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), liveTimeout)
|
||||||
|
defer cleanupCancel()
|
||||||
|
_ = client.StopInstance(cleanupCtx, instance)
|
||||||
|
_ = client.DeleteInstance(cleanupCtx, instance)
|
||||||
|
_ = client.DeleteNetwork(cleanupCtx, bridge)
|
||||||
|
})
|
||||||
|
|
||||||
|
if err := client.CreateNetwork(ctx, lxd.NetworkSpec{
|
||||||
|
Name: bridge, Description: "labd live test",
|
||||||
|
Config: map[string]string{"ipv4.address": "none", "ipv6.address": "none", "user.lincodex.lab": marker["user.lincodex.lab"]},
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("CreateNetwork() error = %v", err)
|
||||||
|
}
|
||||||
|
started := time.Now()
|
||||||
|
if err := client.CreateInstance(ctx, lxd.InstanceSpec{
|
||||||
|
Name: instance, Description: "labd live test", Source: source, Profiles: []string{profile}, Config: marker,
|
||||||
|
Devices: map[string]map[string]string{"eth1": {"type": "nic", "network": bridge}},
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatalf("CreateInstance() error = %v", err)
|
||||||
|
}
|
||||||
|
t.Logf("copy of %s took %s", source, time.Since(started))
|
||||||
|
if !hasInstance(t, client, instance) || !hasNetwork(t, client, bridge) {
|
||||||
|
t.Fatal("the created objects are not listed")
|
||||||
|
}
|
||||||
|
if os.Getenv("LABD_LIVE_START") == "1" {
|
||||||
|
if err := client.StartInstance(ctx, instance); err != nil {
|
||||||
|
t.Fatalf("StartInstance() error = %v", err)
|
||||||
|
}
|
||||||
|
if running, err := client.InstanceRunning(ctx, instance); err != nil || !running {
|
||||||
|
t.Fatalf("InstanceRunning() = %v, %v", running, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := client.StopInstance(ctx, instance); err != nil {
|
||||||
|
t.Fatalf("StopInstance() error = %v", err)
|
||||||
|
}
|
||||||
|
if err := client.DeleteInstance(ctx, instance); err != nil {
|
||||||
|
t.Fatalf("DeleteInstance() error = %v", err)
|
||||||
|
}
|
||||||
|
if err := client.DeleteNetwork(ctx, bridge); err != nil {
|
||||||
|
t.Fatalf("DeleteNetwork() error = %v", err)
|
||||||
|
}
|
||||||
|
if hasInstance(t, client, instance) || hasNetwork(t, client, bridge) {
|
||||||
|
t.Fatal("deleted objects are still listed")
|
||||||
|
}
|
||||||
|
if err := client.DeleteInstance(ctx, instance); !errors.Is(err, lxd.ErrNotFound) {
|
||||||
|
t.Fatalf("second DeleteInstance() error = %v, want ErrNotFound", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func envOr(name, fallback string) string {
|
||||||
|
if value := os.Getenv(name); value != "" {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
func randomHex(t *testing.T, size int) string {
|
||||||
|
t.Helper()
|
||||||
|
raw := make([]byte, size)
|
||||||
|
if _, err := rand.Read(raw); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasInstance(t *testing.T, client *lxd.Client, name string) bool {
|
||||||
|
t.Helper()
|
||||||
|
instances, err := client.ListInstances(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ListInstances() error = %v", err)
|
||||||
|
}
|
||||||
|
return slices.ContainsFunc(instances, func(instance lxd.Instance) bool { return instance.Name == name })
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasNetwork(t *testing.T, client *lxd.Client, name string) bool {
|
||||||
|
t.Helper()
|
||||||
|
networks, err := client.ListNetworks(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ListNetworks() error = %v", err)
|
||||||
|
}
|
||||||
|
return slices.ContainsFunc(networks, func(network lxd.Network) bool { return network.Name == name })
|
||||||
|
}
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
// Package lxdfake is an in-memory LXD for unit tests of labd. It enforces the
|
||||||
|
// rules of LXD that the provisioner depends on: an instance is copied only
|
||||||
|
// from a known snapshot, its NICs need existing networks, a running instance
|
||||||
|
// cannot be deleted, and a network in use cannot be deleted.
|
||||||
|
package lxdfake
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"maps"
|
||||||
|
"slices"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"lincodex/labd/internal/lxd"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrInjected is the error of an injected failure.
|
||||||
|
var ErrInjected = errors.New("injected lxd failure")
|
||||||
|
|
||||||
|
// Instance is the fake state of an instance.
|
||||||
|
type Instance struct {
|
||||||
|
Spec lxd.InstanceSpec
|
||||||
|
Running bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// LXD is the fake. It is safe for concurrent use.
|
||||||
|
type LXD struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
sources map[string]struct{}
|
||||||
|
instances map[string]*Instance
|
||||||
|
networks map[string]lxd.NetworkSpec
|
||||||
|
// external networks exist but were not created through the fake, such
|
||||||
|
// as the management bridge.
|
||||||
|
external map[string]struct{}
|
||||||
|
// failCreateInstance, when set, is called before an instance is created
|
||||||
|
// and fails the call with its error.
|
||||||
|
failCreateInstance func(name string) error
|
||||||
|
failDelete bool
|
||||||
|
unreachable bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// New returns a fake with the given prepared snapshots and pre-existing
|
||||||
|
// networks.
|
||||||
|
func New(sources []string, networks ...string) *LXD {
|
||||||
|
fake := &LXD{
|
||||||
|
sources: make(map[string]struct{}),
|
||||||
|
instances: make(map[string]*Instance),
|
||||||
|
networks: make(map[string]lxd.NetworkSpec),
|
||||||
|
external: make(map[string]struct{}),
|
||||||
|
}
|
||||||
|
for _, source := range sources {
|
||||||
|
fake.sources[source] = struct{}{}
|
||||||
|
}
|
||||||
|
for _, network := range networks {
|
||||||
|
fake.external[network] = struct{}{}
|
||||||
|
}
|
||||||
|
return fake
|
||||||
|
}
|
||||||
|
|
||||||
|
// FailCreateInstance makes CreateInstance fail for the names that fail
|
||||||
|
// returns an error for.
|
||||||
|
func (f *LXD) FailCreateInstance(fail func(name string) error) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
f.failCreateInstance = fail
|
||||||
|
}
|
||||||
|
|
||||||
|
// FailDeletes makes every delete fail until it is switched off.
|
||||||
|
func (f *LXD) FailDeletes(fail bool) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
f.failDelete = fail
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetUnreachable makes every call fail as if the socket were gone.
|
||||||
|
func (f *LXD) SetUnreachable(unreachable bool) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
f.unreachable = unreachable
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddInstance puts an instance into the fake without labd, as an operator or
|
||||||
|
// a crashed labd would leave it.
|
||||||
|
func (f *LXD) AddInstance(spec lxd.InstanceSpec, running bool) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
f.instances[spec.Name] = &Instance{Spec: spec, Running: running}
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddNetwork puts a managed network into the fake without labd.
|
||||||
|
func (f *LXD) AddNetwork(spec lxd.NetworkSpec) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
f.networks[spec.Name] = spec
|
||||||
|
}
|
||||||
|
|
||||||
|
// Instances returns a copy of every instance by name.
|
||||||
|
func (f *LXD) Instances() map[string]Instance {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
result := make(map[string]Instance, len(f.instances))
|
||||||
|
for name, instance := range f.instances {
|
||||||
|
result[name] = *instance
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// Networks returns a copy of every network created in the fake by name.
|
||||||
|
func (f *LXD) Networks() map[string]lxd.NetworkSpec {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
return maps.Clone(f.networks)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *LXD) check() error {
|
||||||
|
if f.unreachable {
|
||||||
|
return fmt.Errorf("lxdfake: dial: %w", ErrInjected)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *LXD) Ping(context.Context) error {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
return f.check()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *LXD) ListInstances(context.Context) ([]lxd.Instance, error) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
if err := f.check(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
names := slices.Sorted(maps.Keys(f.instances))
|
||||||
|
result := make([]lxd.Instance, 0, len(names))
|
||||||
|
for _, name := range names {
|
||||||
|
instance := f.instances[name]
|
||||||
|
status := "Stopped"
|
||||||
|
if instance.Running {
|
||||||
|
status = "Running"
|
||||||
|
}
|
||||||
|
result = append(result, lxd.Instance{Name: name, Status: status, Config: maps.Clone(instance.Spec.Config)})
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *LXD) CreateInstance(_ context.Context, spec lxd.InstanceSpec) error {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
if err := f.check(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if f.failCreateInstance != nil {
|
||||||
|
if err := f.failCreateInstance(spec.Name); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, exists := f.instances[spec.Name]; exists {
|
||||||
|
return &lxd.APIError{Code: 409, Message: "instance exists"}
|
||||||
|
}
|
||||||
|
if _, known := f.sources[spec.Source]; !known {
|
||||||
|
return fmt.Errorf("lxdfake: source %s: %w", spec.Source, lxd.ErrNotFound)
|
||||||
|
}
|
||||||
|
for device, config := range spec.Devices {
|
||||||
|
if config["type"] != "nic" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !f.networkExists(config["network"]) {
|
||||||
|
return &lxd.APIError{Code: 400, Message: "device " + device + " names an unknown network"}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
f.instances[spec.Name] = &Instance{Spec: spec}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *LXD) networkExists(name string) bool {
|
||||||
|
_, managed := f.networks[name]
|
||||||
|
_, external := f.external[name]
|
||||||
|
return managed || external
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *LXD) InstanceRunning(_ context.Context, name string) (bool, error) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
if err := f.check(); err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
instance, ok := f.instances[name]
|
||||||
|
if !ok {
|
||||||
|
return false, lxd.ErrNotFound
|
||||||
|
}
|
||||||
|
return instance.Running, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *LXD) StartInstance(_ context.Context, name string) error {
|
||||||
|
return f.setRunning(name, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *LXD) StopInstance(_ context.Context, name string) error {
|
||||||
|
return f.setRunning(name, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *LXD) setRunning(name string, running bool) error {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
if err := f.check(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
instance, ok := f.instances[name]
|
||||||
|
if !ok {
|
||||||
|
return lxd.ErrNotFound
|
||||||
|
}
|
||||||
|
instance.Running = running
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *LXD) DeleteInstance(_ context.Context, name string) error {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
if err := f.check(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if f.failDelete {
|
||||||
|
return fmt.Errorf("lxdfake: delete %s: %w", name, ErrInjected)
|
||||||
|
}
|
||||||
|
instance, ok := f.instances[name]
|
||||||
|
if !ok {
|
||||||
|
return lxd.ErrNotFound
|
||||||
|
}
|
||||||
|
if instance.Running {
|
||||||
|
return &lxd.APIError{Code: 400, Message: "instance is running"}
|
||||||
|
}
|
||||||
|
delete(f.instances, name)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *LXD) ListNetworks(context.Context) ([]lxd.Network, error) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
if err := f.check(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
names := slices.Sorted(maps.Keys(f.networks))
|
||||||
|
result := make([]lxd.Network, 0, len(names))
|
||||||
|
for _, name := range names {
|
||||||
|
result = append(result, lxd.Network{Name: name, Managed: true, Config: maps.Clone(f.networks[name].Config)})
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *LXD) CreateNetwork(_ context.Context, spec lxd.NetworkSpec) error {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
if err := f.check(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(spec.Name) > 15 {
|
||||||
|
return &lxd.APIError{Code: 400, Message: "network name too long"}
|
||||||
|
}
|
||||||
|
if f.networkExists(spec.Name) {
|
||||||
|
return &lxd.APIError{Code: 409, Message: "network exists"}
|
||||||
|
}
|
||||||
|
f.networks[spec.Name] = spec
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *LXD) DeleteNetwork(_ context.Context, name string) error {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
if err := f.check(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if f.failDelete {
|
||||||
|
return fmt.Errorf("lxdfake: delete %s: %w", name, ErrInjected)
|
||||||
|
}
|
||||||
|
if _, ok := f.networks[name]; !ok {
|
||||||
|
return lxd.ErrNotFound
|
||||||
|
}
|
||||||
|
for _, instance := range f.instances {
|
||||||
|
for _, config := range instance.Spec.Devices {
|
||||||
|
if config["network"] == name {
|
||||||
|
return &lxd.APIError{Code: 400, Message: "network is in use"}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
delete(f.networks, name)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,662 @@
|
|||||||
|
// Package pool owns the labs of labd: admission by the host memory budget,
|
||||||
|
// cloning nodes from prepared snapshots, readiness, console tokens, checks,
|
||||||
|
// expiry, and guaranteed deletion.
|
||||||
|
//
|
||||||
|
// Every lab is written to the state file before any LXD object exists and
|
||||||
|
// stays there until LXD confirms that all its objects are gone, so a crash at
|
||||||
|
// any point leaves a record that the next start finishes: a lab caught while
|
||||||
|
// provisioning fails as interrupted and is deleted, and an expired one is
|
||||||
|
// deleted by the next sweep. Reconcile deletes objects that carry the labd
|
||||||
|
// markers but belong to no record.
|
||||||
|
//
|
||||||
|
// Clones are copy-on-write snapshots on the btrfs pool and take seconds, so
|
||||||
|
// the pool keeps no pre-started nodes: every node boots with the
|
||||||
|
// configuration of its own variant, and "pool" is the bounded set of
|
||||||
|
// concurrent labs that the memory budget allows.
|
||||||
|
package pool
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"net/netip"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"lincodex/labd/internal/lab"
|
||||||
|
"lincodex/labd/internal/lxd"
|
||||||
|
"lincodex/labd/internal/template"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Errors of the manager. Busy is a capacity signal; it is never reported as
|
||||||
|
// an infrastructure failure.
|
||||||
|
var (
|
||||||
|
ErrBusy = errors.New("lab pool busy")
|
||||||
|
ErrNotFound = errors.New("lab not found")
|
||||||
|
ErrPayloadMismatch = errors.New("lab ID reused with another payload")
|
||||||
|
ErrUnknownTemplate = errors.New("unknown lab template")
|
||||||
|
ErrLifetimeTooLong = errors.New("lab lifetime above the maximum")
|
||||||
|
ErrUnknownNode = errors.New("unknown lab node")
|
||||||
|
ErrNotReady = errors.New("lab is not ready")
|
||||||
|
ErrCheckUnavailable = errors.New("lab check unavailable")
|
||||||
|
ErrIDCollision = errors.New("lab ID collides with the LXD names of another lab")
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
consoleTokenBytes = 32
|
||||||
|
// MaxConsoleTokenTTL is the contract bound of a console token.
|
||||||
|
MaxConsoleTokenTTL = 120 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
// LXD is the part of the LXD API that the manager uses.
|
||||||
|
type LXD interface {
|
||||||
|
ListInstances(ctx context.Context) ([]lxd.Instance, error)
|
||||||
|
CreateInstance(ctx context.Context, spec lxd.InstanceSpec) error
|
||||||
|
StartInstance(ctx context.Context, name string) error
|
||||||
|
StopInstance(ctx context.Context, name string) error
|
||||||
|
DeleteInstance(ctx context.Context, name string) error
|
||||||
|
ListNetworks(ctx context.Context) ([]lxd.Network, error)
|
||||||
|
CreateNetwork(ctx context.Context, spec lxd.NetworkSpec) error
|
||||||
|
DeleteNetwork(ctx context.Context, name string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store persists the lab records.
|
||||||
|
type Store interface {
|
||||||
|
Load() ([]lab.Lab, error)
|
||||||
|
Save(labs []lab.Lab) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prober tells whether a node answers on its management port.
|
||||||
|
type Prober interface {
|
||||||
|
Probe(ctx context.Context, address netip.AddrPort) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Config holds the limits of the manager.
|
||||||
|
type Config struct {
|
||||||
|
// MemoryBudgetBytes is the guest memory that all labs together may use.
|
||||||
|
MemoryBudgetBytes int64
|
||||||
|
// MaxLabs additionally caps the number of labs; zero means only the
|
||||||
|
// memory budget applies.
|
||||||
|
MaxLabs int
|
||||||
|
MaxLifetime time.Duration
|
||||||
|
ProvisionTimeout time.Duration
|
||||||
|
ProbeInterval time.Duration
|
||||||
|
DeletedRetention time.Duration
|
||||||
|
ConsoleTokenTTL time.Duration
|
||||||
|
CheckTimeout time.Duration
|
||||||
|
// ManagementNetwork is the LXD bridge of the management plane.
|
||||||
|
ManagementNetwork string
|
||||||
|
ManagementPrefix netip.Prefix
|
||||||
|
// ManagementHost is the host side of the management bridge, where labd
|
||||||
|
// and the checker connect from.
|
||||||
|
ManagementHost netip.Addr
|
||||||
|
// ManagementFirst is the first address handed to nodes.
|
||||||
|
ManagementFirst netip.Addr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Config) validate() error {
|
||||||
|
var errs []error
|
||||||
|
if c.MemoryBudgetBytes <= 0 || c.MaxLabs < 0 {
|
||||||
|
errs = append(errs, errors.New("pool.Config - the memory budget must be positive and the lab cap not negative"))
|
||||||
|
}
|
||||||
|
for _, value := range []time.Duration{c.MaxLifetime, c.ProvisionTimeout, c.ProbeInterval, c.DeletedRetention, c.CheckTimeout} {
|
||||||
|
if value <= 0 {
|
||||||
|
errs = append(errs, errors.New("pool.Config - durations must be positive"))
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if c.ConsoleTokenTTL <= 0 || c.ConsoleTokenTTL > MaxConsoleTokenTTL {
|
||||||
|
errs = append(errs, errors.New("pool.Config - the console token TTL must be 1 to 120 seconds"))
|
||||||
|
}
|
||||||
|
if c.ManagementNetwork == "" || !c.ManagementPrefix.IsValid() || !c.ManagementPrefix.Addr().Is4() ||
|
||||||
|
!c.ManagementPrefix.Contains(c.ManagementHost) || !c.ManagementPrefix.Contains(c.ManagementFirst) {
|
||||||
|
errs = append(errs, errors.New("pool.Config - the management network, host, and first address must form one IPv4 subnet"))
|
||||||
|
}
|
||||||
|
return errors.Join(errs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateRequest is a lab of one template variant.
|
||||||
|
type CreateRequest struct {
|
||||||
|
TemplateID string
|
||||||
|
TemplateVersion int
|
||||||
|
Seed [template.SeedBytes]byte
|
||||||
|
Lifetime time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fingerprint identifies the payload of a request for idempotency.
|
||||||
|
func (r CreateRequest) Fingerprint() string {
|
||||||
|
sum := sha256.Sum256(fmt.Appendf(nil, "%s\x00%d\x00%x\x00%d", r.TemplateID, r.TemplateVersion, r.Seed, r.Lifetime))
|
||||||
|
return hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckResult is the outcome of one check.
|
||||||
|
type CheckResult struct {
|
||||||
|
CheckedAt time.Time
|
||||||
|
Criteria []template.Criterion
|
||||||
|
}
|
||||||
|
|
||||||
|
type consoleGrant struct {
|
||||||
|
lab uuid.UUID
|
||||||
|
node string
|
||||||
|
expiresAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// Manager owns every lab of the process. It is safe for concurrent use.
|
||||||
|
type Manager struct {
|
||||||
|
cfg Config
|
||||||
|
lxd LXD
|
||||||
|
store Store
|
||||||
|
templates *template.Registry
|
||||||
|
prober Prober
|
||||||
|
now func() time.Time
|
||||||
|
logger *slog.Logger
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
labs map[uuid.UUID]*lab.Lab
|
||||||
|
workers map[uuid.UUID]context.CancelFunc
|
||||||
|
grants map[[sha256.Size]byte]consoleGrant
|
||||||
|
started bool
|
||||||
|
draining bool
|
||||||
|
// base is the lifetime of the background workers; Close cancels it.
|
||||||
|
base context.Context
|
||||||
|
stop context.CancelFunc
|
||||||
|
wg sync.WaitGroup
|
||||||
|
}
|
||||||
|
|
||||||
|
// New returns a manager. It refuses a template that can never fit the memory
|
||||||
|
// budget, so a configuration error does not look like a busy pool forever.
|
||||||
|
func New(cfg Config, client LXD, store Store, templates *template.Registry, prober Prober, now func() time.Time, logger *slog.Logger) (*Manager, error) {
|
||||||
|
if err := cfg.validate(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, candidate := range templates.All() {
|
||||||
|
if candidate.MemoryBytes() > cfg.MemoryBudgetBytes {
|
||||||
|
return nil, fmt.Errorf("pool.New - template %s version %d needs more memory than the budget", candidate.ID, candidate.Version)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &Manager{
|
||||||
|
cfg: cfg, lxd: client, store: store, templates: templates, prober: prober, now: now, logger: logger,
|
||||||
|
labs: make(map[uuid.UUID]*lab.Lab),
|
||||||
|
workers: make(map[uuid.UUID]context.CancelFunc),
|
||||||
|
grants: make(map[[sha256.Size]byte]consoleGrant),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start loads the records and resumes unfinished work. A lab that was
|
||||||
|
// provisioning when the previous process stopped fails as interrupted and is
|
||||||
|
// deleted, because its partial objects cannot be trusted.
|
||||||
|
func (m *Manager) Start(ctx context.Context) error {
|
||||||
|
records, err := m.store.Load()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Manager.Start - load: %w", err)
|
||||||
|
}
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
if m.started {
|
||||||
|
return errors.New("Manager.Start - already started")
|
||||||
|
}
|
||||||
|
interrupted := false
|
||||||
|
for index := range records {
|
||||||
|
record := records[index]
|
||||||
|
if record.State == lab.Provisioning {
|
||||||
|
record.State = lab.Failed
|
||||||
|
record.FailureReason = lab.FailureInterrupted
|
||||||
|
interrupted = true
|
||||||
|
}
|
||||||
|
m.labs[record.ID] = &record
|
||||||
|
}
|
||||||
|
if interrupted {
|
||||||
|
if err := m.persistLocked(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m.base, m.stop = context.WithCancel(context.WithoutCancel(ctx))
|
||||||
|
m.started = true
|
||||||
|
for id, record := range m.labs {
|
||||||
|
if record.NeedsTeardown() {
|
||||||
|
m.startWorkerLocked(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m.logger.InfoContext(ctx, "lab records loaded", slog.Int("labs", len(m.labs)))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ready reports whether the manager accepts labs.
|
||||||
|
func (m *Manager) Ready() bool {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
return m.started && !m.draining
|
||||||
|
}
|
||||||
|
|
||||||
|
// Usage returns the memory in use and the number of labs that hold LXD
|
||||||
|
// objects.
|
||||||
|
func (m *Manager) Usage() (int64, int) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
return m.usageLocked()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create admits and stores a lab and starts its provisioning. It is
|
||||||
|
// idempotent by id: the same payload returns the stored lab with created
|
||||||
|
// false.
|
||||||
|
func (m *Manager) Create(id uuid.UUID, request CreateRequest) (lab.Lab, bool, error) {
|
||||||
|
chosen, ok := m.templates.Lookup(request.TemplateID, request.TemplateVersion)
|
||||||
|
if !ok {
|
||||||
|
return lab.Lab{}, false, ErrUnknownTemplate
|
||||||
|
}
|
||||||
|
if request.Lifetime > m.cfg.MaxLifetime {
|
||||||
|
return lab.Lab{}, false, ErrLifetimeTooLong
|
||||||
|
}
|
||||||
|
fingerprint := request.Fingerprint()
|
||||||
|
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
if existing, found := m.labs[id]; found {
|
||||||
|
if existing.Fingerprint != fingerprint {
|
||||||
|
return lab.Lab{}, false, ErrPayloadMismatch
|
||||||
|
}
|
||||||
|
return existing.Clone(), false, nil
|
||||||
|
}
|
||||||
|
if !m.started || m.draining {
|
||||||
|
return lab.Lab{}, false, ErrBusy
|
||||||
|
}
|
||||||
|
if m.collidesLocked(id) {
|
||||||
|
return lab.Lab{}, false, ErrIDCollision
|
||||||
|
}
|
||||||
|
used, count := m.usageLocked()
|
||||||
|
cost := chosen.MemoryBytes()
|
||||||
|
if used+cost > m.cfg.MemoryBudgetBytes || (m.cfg.MaxLabs > 0 && count >= m.cfg.MaxLabs) {
|
||||||
|
return lab.Lab{}, false, ErrBusy
|
||||||
|
}
|
||||||
|
addresses, ok := m.allocateLocked(len(chosen.Nodes))
|
||||||
|
if !ok {
|
||||||
|
return lab.Lab{}, false, ErrBusy
|
||||||
|
}
|
||||||
|
|
||||||
|
now := m.now().UTC()
|
||||||
|
record := &lab.Lab{
|
||||||
|
ID: id, TemplateID: chosen.ID, TemplateVersion: chosen.Version,
|
||||||
|
Seed: hex.EncodeToString(request.Seed[:]), Fingerprint: fingerprint,
|
||||||
|
State: lab.Provisioning, CreatedAt: now, ExpiresAt: now.Add(request.Lifetime),
|
||||||
|
MemoryBytes: cost,
|
||||||
|
}
|
||||||
|
for index, node := range chosen.Nodes {
|
||||||
|
record.Nodes = append(record.Nodes, lab.Node{
|
||||||
|
Name: node.Name, Kind: string(node.Kind), Instance: lab.InstanceName(id, node.Name),
|
||||||
|
ManagementAddress: addresses[index], ManagementPort: node.Port(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
for index := range chosen.Links {
|
||||||
|
record.Bridges = append(record.Bridges, lab.BridgeName(id, index))
|
||||||
|
}
|
||||||
|
m.labs[id] = record
|
||||||
|
if err := m.persistLocked(); err != nil {
|
||||||
|
delete(m.labs, id)
|
||||||
|
return lab.Lab{}, false, err
|
||||||
|
}
|
||||||
|
m.startWorkerLocked(id)
|
||||||
|
m.logger.Info("lab admitted", slog.String("lab_id", id.String()), slog.String("template", chosen.ID),
|
||||||
|
slog.Int64("memory_bytes", cost), slog.Int64("used_bytes", used+cost))
|
||||||
|
return record.Clone(), true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get returns a lab.
|
||||||
|
func (m *Manager) Get(id uuid.UUID) (lab.Lab, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
record, ok := m.labs[id]
|
||||||
|
if !ok {
|
||||||
|
return lab.Lab{}, ErrNotFound
|
||||||
|
}
|
||||||
|
return record.Clone(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete ends a lab before its timer. It returns changed false for a lab that
|
||||||
|
// is already ending.
|
||||||
|
func (m *Manager) Delete(id uuid.UUID) (lab.Lab, bool, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
record, ok := m.labs[id]
|
||||||
|
if !ok {
|
||||||
|
return lab.Lab{}, false, ErrNotFound
|
||||||
|
}
|
||||||
|
if !record.Active() {
|
||||||
|
return record.Clone(), false, nil
|
||||||
|
}
|
||||||
|
m.endLocked(id, record)
|
||||||
|
if err := m.persistLocked(); err != nil {
|
||||||
|
// The deletion proceeds; the next successful save records it, and a
|
||||||
|
// restart before that deletes the lab at its timer.
|
||||||
|
m.logger.Error("lab state not saved", slog.String("lab_id", id.String()), slog.String("error", err.Error()))
|
||||||
|
}
|
||||||
|
return record.Clone(), true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// endLocked moves an active lab to deleting and makes sure a worker removes
|
||||||
|
// it.
|
||||||
|
func (m *Manager) endLocked(id uuid.UUID, record *lab.Lab) {
|
||||||
|
record.State = lab.Deleting
|
||||||
|
if cancel, running := m.workers[id]; running {
|
||||||
|
cancel()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
m.startWorkerLocked(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConsoleToken issues a single-use console token for a node of a ready lab.
|
||||||
|
func (m *Manager) ConsoleToken(id uuid.UUID, node string) (string, time.Time, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
record, err := m.readyLocked(id)
|
||||||
|
if err != nil {
|
||||||
|
return "", time.Time{}, err
|
||||||
|
}
|
||||||
|
if _, known := record.Node(node); !known {
|
||||||
|
return "", time.Time{}, ErrUnknownNode
|
||||||
|
}
|
||||||
|
raw := make([]byte, consoleTokenBytes)
|
||||||
|
if _, err := rand.Read(raw); err != nil {
|
||||||
|
return "", time.Time{}, fmt.Errorf("Manager.ConsoleToken - random: %w", err)
|
||||||
|
}
|
||||||
|
token := base64.RawURLEncoding.EncodeToString(raw)
|
||||||
|
expiresAt := m.now().UTC().Add(m.cfg.ConsoleTokenTTL)
|
||||||
|
m.grants[sha256.Sum256([]byte(token))] = consoleGrant{lab: id, node: node, expiresAt: expiresAt}
|
||||||
|
return token, expiresAt, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConsumeConsoleToken redeems a console token once. The console attach uses
|
||||||
|
// it; an unknown, used, or expired token and a lab that is no longer ready
|
||||||
|
// all fail alike.
|
||||||
|
func (m *Manager) ConsumeConsoleToken(token string) (uuid.UUID, string, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
digest := sha256.Sum256([]byte(token))
|
||||||
|
grant, ok := m.grants[digest]
|
||||||
|
delete(m.grants, digest)
|
||||||
|
if !ok || !m.now().Before(grant.expiresAt) {
|
||||||
|
return uuid.Nil, "", ErrNotFound
|
||||||
|
}
|
||||||
|
if _, err := m.readyLocked(grant.lab); err != nil {
|
||||||
|
return uuid.Nil, "", err
|
||||||
|
}
|
||||||
|
return grant.lab, grant.node, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check runs the checker of the template against a ready lab.
|
||||||
|
func (m *Manager) Check(ctx context.Context, id uuid.UUID) (CheckResult, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
record, err := m.readyLocked(id)
|
||||||
|
if err != nil {
|
||||||
|
m.mu.Unlock()
|
||||||
|
return CheckResult{}, err
|
||||||
|
}
|
||||||
|
snapshot := record.Clone()
|
||||||
|
m.mu.Unlock()
|
||||||
|
|
||||||
|
chosen, ok := m.templates.Lookup(snapshot.TemplateID, snapshot.TemplateVersion)
|
||||||
|
if !ok {
|
||||||
|
return CheckResult{}, fmt.Errorf("Manager.Check - template of lab %s is gone: %w", id, ErrCheckUnavailable)
|
||||||
|
}
|
||||||
|
variant, err := m.plan(snapshot, chosen)
|
||||||
|
if err != nil {
|
||||||
|
return CheckResult{}, fmt.Errorf("Manager.Check - plan: %w: %w", ErrCheckUnavailable, err)
|
||||||
|
}
|
||||||
|
access := make([]template.NodeAccess, 0, len(snapshot.Nodes))
|
||||||
|
for _, node := range snapshot.Nodes {
|
||||||
|
access = append(access, template.NodeAccess{
|
||||||
|
Name: node.Name, Kind: template.Kind(node.Kind),
|
||||||
|
Address: netip.AddrPortFrom(node.ManagementAddress, node.ManagementPort),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
checkCtx, cancel := context.WithTimeout(ctx, m.cfg.CheckTimeout)
|
||||||
|
defer cancel()
|
||||||
|
criteria, err := chosen.Check(checkCtx, variant, access)
|
||||||
|
if err != nil {
|
||||||
|
return CheckResult{}, fmt.Errorf("Manager.Check - checker: %w: %w", ErrCheckUnavailable, err)
|
||||||
|
}
|
||||||
|
if err := template.ValidateCriteria(criteria); err != nil {
|
||||||
|
return CheckResult{}, fmt.Errorf("Manager.Check - checker output: %w: %w", ErrCheckUnavailable, err)
|
||||||
|
}
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
// A lab that ended during the check may have been read half deleted.
|
||||||
|
if _, err := m.readyLocked(id); err != nil {
|
||||||
|
return CheckResult{}, err
|
||||||
|
}
|
||||||
|
return CheckResult{CheckedAt: m.now().UTC(), Criteria: slices.Clone(criteria)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) readyLocked(id uuid.UUID) (*lab.Lab, error) {
|
||||||
|
record, ok := m.labs[id]
|
||||||
|
if !ok {
|
||||||
|
return nil, ErrNotFound
|
||||||
|
}
|
||||||
|
if record.State != lab.Ready || !m.now().Before(record.ExpiresAt) {
|
||||||
|
return nil, ErrNotReady
|
||||||
|
}
|
||||||
|
return record, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sweep ends expired labs, restarts pending deletions, forgets deleted
|
||||||
|
// labs after their retention, and drops expired console tokens. The reaper
|
||||||
|
// calls it periodically.
|
||||||
|
func (m *Manager) Sweep(ctx context.Context) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
if !m.started {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
now := m.now()
|
||||||
|
changed := false
|
||||||
|
for id, record := range m.labs {
|
||||||
|
if record.Active() && !now.Before(record.ExpiresAt) {
|
||||||
|
m.logger.InfoContext(ctx, "lab expired", slog.String("lab_id", id.String()))
|
||||||
|
m.endLocked(id, record)
|
||||||
|
changed = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if record.NeedsTeardown() {
|
||||||
|
m.startWorkerLocked(id)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !record.HoldsResources() && now.Sub(record.DeletedAt) >= m.cfg.DeletedRetention {
|
||||||
|
delete(m.labs, id)
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for digest, grant := range m.grants {
|
||||||
|
if !now.Before(grant.expiresAt) {
|
||||||
|
delete(m.grants, digest)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if changed {
|
||||||
|
if err := m.persistLocked(); err != nil {
|
||||||
|
m.logger.ErrorContext(ctx, "lab state not saved", slog.String("error", err.Error()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reconcile deletes LXD objects that carry the labd markers but belong to no
|
||||||
|
// lab that may hold objects. Objects with the name prefix but without the
|
||||||
|
// marker are reported and left alone.
|
||||||
|
func (m *Manager) Reconcile(ctx context.Context) error {
|
||||||
|
// List before taking the snapshot: a lab created after the listing is
|
||||||
|
// not in it, and a lab deleted in between only yields not-found deletes.
|
||||||
|
instances, err := m.lxd.ListInstances(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Manager.Reconcile - list instances: %w", err)
|
||||||
|
}
|
||||||
|
networks, err := m.lxd.ListNetworks(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Manager.Reconcile - list networks: %w", err)
|
||||||
|
}
|
||||||
|
knownInstances, knownBridges := m.knownObjects()
|
||||||
|
|
||||||
|
var errs []error
|
||||||
|
removed := 0
|
||||||
|
for _, instance := range instances {
|
||||||
|
if !strings.HasPrefix(instance.Name, lab.InstancePrefix) || knownInstances[instance.Name] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !lab.OwnedInstance(instance.Name, instance.Config) {
|
||||||
|
m.logger.WarnContext(ctx, "instance with the lab prefix has no labd marker; left alone", slog.String("instance", instance.Name))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := m.deleteInstance(ctx, instance.Name); err != nil {
|
||||||
|
errs = append(errs, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
removed++
|
||||||
|
}
|
||||||
|
for _, network := range networks {
|
||||||
|
if !strings.HasPrefix(network.Name, lab.BridgePrefix) || knownBridges[network.Name] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !lab.OwnedBridge(network.Name, network.Config) {
|
||||||
|
m.logger.WarnContext(ctx, "network with the lab prefix has no labd marker; left alone", slog.String("network", network.Name))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := m.deleteNetwork(ctx, network.Name); err != nil {
|
||||||
|
errs = append(errs, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
removed++
|
||||||
|
}
|
||||||
|
if removed > 0 {
|
||||||
|
m.logger.InfoContext(ctx, "orphaned lab objects deleted", slog.Int("objects", removed))
|
||||||
|
}
|
||||||
|
return errors.Join(errs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) knownObjects() (map[string]bool, map[string]bool) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
instances := make(map[string]bool)
|
||||||
|
bridges := make(map[string]bool)
|
||||||
|
for _, record := range m.labs {
|
||||||
|
if !record.HoldsResources() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, node := range record.Nodes {
|
||||||
|
instances[node.Instance] = true
|
||||||
|
}
|
||||||
|
for _, bridge := range record.Bridges {
|
||||||
|
bridges[bridge] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return instances, bridges
|
||||||
|
}
|
||||||
|
|
||||||
|
// Drain stops admitting labs; existing labs keep running.
|
||||||
|
func (m *Manager) Drain() {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
m.draining = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close stops the workers and waits for them. Labs keep their records: the
|
||||||
|
// next start deletes a lab that was provisioning and expires the others on
|
||||||
|
// their timers.
|
||||||
|
func (m *Manager) Close(ctx context.Context) error {
|
||||||
|
m.mu.Lock()
|
||||||
|
m.draining = true
|
||||||
|
if m.stop != nil {
|
||||||
|
m.stop()
|
||||||
|
}
|
||||||
|
m.mu.Unlock()
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
m.wg.Wait()
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
return nil
|
||||||
|
case <-ctx.Done():
|
||||||
|
return fmt.Errorf("Manager.Close - wait for workers: %w", ctx.Err())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) usageLocked() (int64, int) {
|
||||||
|
var used int64
|
||||||
|
count := 0
|
||||||
|
for _, record := range m.labs {
|
||||||
|
if record.HoldsResources() {
|
||||||
|
used += record.MemoryBytes
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return used, count
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) collidesLocked(id uuid.UUID) bool {
|
||||||
|
short := lab.ShortID(id)
|
||||||
|
for _, record := range m.labs {
|
||||||
|
if record.HoldsResources() && lab.ShortID(record.ID) == short {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// allocateLocked picks free management addresses, skipping the host side
|
||||||
|
// and the broadcast address.
|
||||||
|
func (m *Manager) allocateLocked(count int) ([]netip.Addr, bool) {
|
||||||
|
used := make(map[netip.Addr]bool)
|
||||||
|
for _, record := range m.labs {
|
||||||
|
if record.HoldsResources() {
|
||||||
|
for _, node := range record.Nodes {
|
||||||
|
used[node.ManagementAddress] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
addresses := make([]netip.Addr, 0, count)
|
||||||
|
for address := m.cfg.ManagementFirst; len(addresses) < count; address = address.Next() {
|
||||||
|
next := address.Next()
|
||||||
|
if !m.cfg.ManagementPrefix.Contains(address) || !next.IsValid() || !m.cfg.ManagementPrefix.Contains(next) {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
if address != m.cfg.ManagementHost && !used[address] {
|
||||||
|
addresses = append(addresses, address)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return addresses, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) persistLocked() error {
|
||||||
|
records := make([]lab.Lab, 0, len(m.labs))
|
||||||
|
for _, record := range m.labs {
|
||||||
|
records = append(records, record.Clone())
|
||||||
|
}
|
||||||
|
slices.SortFunc(records, func(a, b lab.Lab) int {
|
||||||
|
if order := a.CreatedAt.Compare(b.CreatedAt); order != 0 {
|
||||||
|
return order
|
||||||
|
}
|
||||||
|
return strings.Compare(a.ID.String(), b.ID.String())
|
||||||
|
})
|
||||||
|
if err := m.store.Save(records); err != nil {
|
||||||
|
return fmt.Errorf("Manager.persist - save: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) plan(record lab.Lab, chosen template.Template) (template.Variant, error) {
|
||||||
|
seed, err := hex.DecodeString(record.Seed)
|
||||||
|
if err != nil || len(seed) != template.SeedBytes {
|
||||||
|
return template.Variant{}, errors.New("Manager.plan - the stored seed is malformed")
|
||||||
|
}
|
||||||
|
addresses := make([]netip.Addr, 0, len(record.Nodes))
|
||||||
|
for _, node := range record.Nodes {
|
||||||
|
addresses = append(addresses, node.ManagementAddress)
|
||||||
|
}
|
||||||
|
return chosen.Plan([template.SeedBytes]byte(seed), addresses, m.cfg.ManagementPrefix.Bits(), m.cfg.ManagementHost)
|
||||||
|
}
|
||||||
@@ -0,0 +1,593 @@
|
|||||||
|
package pool_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"log/slog"
|
||||||
|
"net/netip"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"lincodex/labd/internal/lab"
|
||||||
|
"lincodex/labd/internal/lxd"
|
||||||
|
"lincodex/labd/internal/lxd/lxdfake"
|
||||||
|
"lincodex/labd/internal/pool"
|
||||||
|
"lincodex/labd/internal/store"
|
||||||
|
"lincodex/labd/internal/template"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
managementNetwork = "lxdbr-labmgmt"
|
||||||
|
nodeMemory = 768 << 20
|
||||||
|
labMemory = 2 * nodeMemory
|
||||||
|
waitLimit = 5 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
var errCheckerOffline = errors.New("checker cannot reach the node")
|
||||||
|
|
||||||
|
type clock struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
now time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *clock) Now() time.Time {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
return c.now
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *clock) Advance(d time.Duration) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
c.now = c.now.Add(d)
|
||||||
|
}
|
||||||
|
|
||||||
|
type prober struct{ down atomic.Bool }
|
||||||
|
|
||||||
|
func (p *prober) Probe(context.Context, netip.AddrPort) error {
|
||||||
|
if p.down.Load() {
|
||||||
|
return errors.New("connection refused")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func testTemplate() template.Template {
|
||||||
|
return template.Template{
|
||||||
|
ID: "mikrotik-pair", Version: 1,
|
||||||
|
Nodes: []template.Node{
|
||||||
|
{Name: "r1", Kind: template.MikroTik, Profile: "lincodex-lab-small", Source: "tpl-chr/base", MemoryBytes: nodeMemory},
|
||||||
|
{Name: "srv", Kind: template.Ubuntu, Profile: "lincodex-lab-small", Source: "tpl-ubuntu/base", MemoryBytes: nodeMemory},
|
||||||
|
},
|
||||||
|
Links: []template.Link{{Name: "lan", Nodes: []string{"r1", "srv"}}, {Name: "wan", Nodes: []string{"r1"}}},
|
||||||
|
Render: func(variant template.Variant) (map[string]template.Bootstrap, error) {
|
||||||
|
r1, _ := variant.Node("r1")
|
||||||
|
srv, _ := variant.Node("srv")
|
||||||
|
return map[string]template.Bootstrap{
|
||||||
|
"r1": {UserData: template.RouterOSManagementScript(r1)},
|
||||||
|
"srv": {NetworkConfig: template.UbuntuNetworkConfig(srv)},
|
||||||
|
}, nil
|
||||||
|
},
|
||||||
|
Check: func(_ context.Context, variant template.Variant, nodes []template.NodeAccess) ([]template.Criterion, error) {
|
||||||
|
if len(nodes) != 2 || nodes[0].Address.Port() != 8728 || nodes[1].Address.Port() != 22 {
|
||||||
|
return nil, errCheckerOffline
|
||||||
|
}
|
||||||
|
// The variant decides the result, as a real checker would.
|
||||||
|
passed := variant.Rand("criteria").IntN(2) == 0
|
||||||
|
return []template.Criterion{{ID: "ospf", Passed: passed}, {ID: "ping", Passed: true}}, nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type harness struct {
|
||||||
|
t *testing.T
|
||||||
|
fake *lxdfake.LXD
|
||||||
|
statePath string
|
||||||
|
clock *clock
|
||||||
|
prober *prober
|
||||||
|
cfg pool.Config
|
||||||
|
registry *template.Registry
|
||||||
|
}
|
||||||
|
|
||||||
|
func newHarness(t *testing.T, change func(*pool.Config)) *harness {
|
||||||
|
t.Helper()
|
||||||
|
registry, err := template.NewRegistry(testTemplate())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cfg := pool.Config{
|
||||||
|
MemoryBudgetBytes: 2 * labMemory,
|
||||||
|
MaxLifetime: 2 * time.Hour,
|
||||||
|
ProvisionTimeout: waitLimit,
|
||||||
|
ProbeInterval: time.Millisecond,
|
||||||
|
DeletedRetention: time.Hour,
|
||||||
|
ConsoleTokenTTL: time.Minute,
|
||||||
|
CheckTimeout: time.Second,
|
||||||
|
ManagementNetwork: managementNetwork,
|
||||||
|
ManagementPrefix: netip.MustParsePrefix("10.81.0.0/24"),
|
||||||
|
ManagementHost: netip.MustParseAddr("10.81.0.1"),
|
||||||
|
ManagementFirst: netip.MustParseAddr("10.81.0.16"),
|
||||||
|
}
|
||||||
|
if change != nil {
|
||||||
|
change(&cfg)
|
||||||
|
}
|
||||||
|
return &harness{
|
||||||
|
t: t,
|
||||||
|
fake: lxdfake.New([]string{"tpl-chr/base", "tpl-ubuntu/base"}, managementNetwork),
|
||||||
|
statePath: filepath.Join(t.TempDir(), "labs.json"),
|
||||||
|
clock: &clock{now: time.Date(2026, 10, 11, 9, 0, 0, 0, time.UTC)},
|
||||||
|
prober: &prober{},
|
||||||
|
cfg: cfg,
|
||||||
|
registry: registry,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// start creates and starts a manager on the shared fake and state file. Two
|
||||||
|
// managers in a row model a restart of labd.
|
||||||
|
func (h *harness) start() *pool.Manager {
|
||||||
|
h.t.Helper()
|
||||||
|
states, err := store.New(h.statePath)
|
||||||
|
if err != nil {
|
||||||
|
h.t.Fatal(err)
|
||||||
|
}
|
||||||
|
logger := slog.New(slog.DiscardHandler)
|
||||||
|
manager, err := pool.New(h.cfg, h.fake, states, h.registry, h.prober, h.clock.Now, logger)
|
||||||
|
if err != nil {
|
||||||
|
h.t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := manager.Start(context.Background()); err != nil {
|
||||||
|
h.t.Fatal(err)
|
||||||
|
}
|
||||||
|
h.t.Cleanup(func() {
|
||||||
|
if err := manager.Close(context.Background()); err != nil {
|
||||||
|
h.t.Errorf("Close() error = %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return manager
|
||||||
|
}
|
||||||
|
|
||||||
|
func request(seed byte) pool.CreateRequest {
|
||||||
|
return pool.CreateRequest{TemplateID: "mikrotik-pair", TemplateVersion: 1, Seed: [32]byte{seed}, Lifetime: 30 * time.Minute}
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitFor(t *testing.T, manager *pool.Manager, id uuid.UUID, done func(lab.Lab) bool) lab.Lab {
|
||||||
|
t.Helper()
|
||||||
|
deadline := time.Now().Add(waitLimit)
|
||||||
|
for {
|
||||||
|
record, err := manager.Get(id)
|
||||||
|
if err == nil && done(record) {
|
||||||
|
return record
|
||||||
|
}
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatalf("lab %s did not reach the expected state; last %+v, %v", id, record, err)
|
||||||
|
}
|
||||||
|
time.Sleep(2 * time.Millisecond)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func inState(state lab.State) func(lab.Lab) bool {
|
||||||
|
return func(record lab.Lab) bool { return record.State == state }
|
||||||
|
}
|
||||||
|
|
||||||
|
func removed(record lab.Lab) bool { return !record.HoldsResources() }
|
||||||
|
|
||||||
|
func (h *harness) labObjects(id uuid.UUID) (int, int) {
|
||||||
|
short := lab.ShortID(id)
|
||||||
|
instances, bridges := 0, 0
|
||||||
|
for name := range h.fake.Instances() {
|
||||||
|
if strings.Contains(name, short) {
|
||||||
|
instances++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for name := range h.fake.Networks() {
|
||||||
|
if strings.Contains(name, short) {
|
||||||
|
bridges++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return instances, bridges
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateClonesNodesOnIsolatedBridgesAndDeleteRemovesEverything(t *testing.T) {
|
||||||
|
h := newHarness(t, nil)
|
||||||
|
manager := h.start()
|
||||||
|
id := uuid.New()
|
||||||
|
|
||||||
|
created, isNew, err := manager.Create(id, request(1))
|
||||||
|
if err != nil || !isNew || created.State != lab.Provisioning {
|
||||||
|
t.Fatalf("Create() = %+v, %v, %v", created, isNew, err)
|
||||||
|
}
|
||||||
|
ready := waitFor(t, manager, id, inState(lab.Ready))
|
||||||
|
if ready.ReadyAt.IsZero() || !ready.ExpiresAt.Equal(ready.CreatedAt.Add(30*time.Minute)) {
|
||||||
|
t.Fatalf("ready lab times = %+v", ready)
|
||||||
|
}
|
||||||
|
|
||||||
|
instances := h.fake.Instances()
|
||||||
|
networks := h.fake.Networks()
|
||||||
|
if len(instances) != 2 || len(networks) != 2 {
|
||||||
|
t.Fatalf("LXD holds %d instances and %d networks, want 2 and 2", len(instances), len(networks))
|
||||||
|
}
|
||||||
|
for _, bridge := range ready.Bridges {
|
||||||
|
spec := networks[bridge]
|
||||||
|
if len(bridge) > 15 || spec.Config["ipv4.address"] != "none" || spec.Config["ipv6.address"] != "none" ||
|
||||||
|
spec.Config[lab.ConfigLab] != id.String() {
|
||||||
|
t.Fatalf("bridge %s = %+v, want an L2-only bridge marked with the lab", bridge, spec)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
r1 := instances[lab.InstanceName(id, "r1")]
|
||||||
|
srv := instances[lab.InstanceName(id, "srv")]
|
||||||
|
if !r1.Running || !srv.Running || r1.Spec.Source != "tpl-chr/base" || r1.Spec.Config[lab.ConfigLab] != id.String() {
|
||||||
|
t.Fatalf("r1 = %+v", r1)
|
||||||
|
}
|
||||||
|
management := r1.Spec.Devices["eth0"]
|
||||||
|
if management["network"] != managementNetwork || management["security.port_isolation"] != "true" ||
|
||||||
|
management["security.mac_filtering"] != "true" {
|
||||||
|
t.Fatalf("r1 management NIC = %v", management)
|
||||||
|
}
|
||||||
|
// r1 is on both links, srv only on the first; no node has a NIC on a
|
||||||
|
// bridge of another lab or on any other network.
|
||||||
|
if r1.Spec.Devices["eth1"]["network"] != ready.Bridges[0] || r1.Spec.Devices["eth2"]["network"] != ready.Bridges[1] ||
|
||||||
|
srv.Spec.Devices["eth1"]["network"] != ready.Bridges[0] || len(srv.Spec.Devices) != 3 {
|
||||||
|
t.Fatalf("data NICs: r1 %v, srv %v", r1.Spec.Devices, srv.Spec.Devices)
|
||||||
|
}
|
||||||
|
if !strings.Contains(r1.Spec.Config["cloud-init.user-data"], "address=10.81.0.16/24") ||
|
||||||
|
!strings.Contains(srv.Spec.Config["cloud-init.network-config"], "10.81.0.17/24") ||
|
||||||
|
srv.Spec.Devices["cloud-init"]["source"] != "cloud-init:config" {
|
||||||
|
t.Fatalf("bootstrap: r1 %v, srv %v", r1.Spec.Config, srv.Spec.Config)
|
||||||
|
}
|
||||||
|
|
||||||
|
deleting, changed, err := manager.Delete(id)
|
||||||
|
if err != nil || !changed || deleting.State != lab.Deleting {
|
||||||
|
t.Fatalf("Delete() = %+v, %v, %v", deleting, changed, err)
|
||||||
|
}
|
||||||
|
deleted := waitFor(t, manager, id, inState(lab.Deleted))
|
||||||
|
if deleted.DeletedAt.IsZero() {
|
||||||
|
t.Fatal("deleted lab has no deletion time")
|
||||||
|
}
|
||||||
|
if got := len(h.fake.Instances()) + len(h.fake.Networks()); got != 0 {
|
||||||
|
t.Fatalf("LXD still holds %d objects of the lab", got)
|
||||||
|
}
|
||||||
|
if used, count := manager.Usage(); used != 0 || count != 0 {
|
||||||
|
t.Fatalf("Usage() = %d, %d after deletion", used, count)
|
||||||
|
}
|
||||||
|
again, changed, err := manager.Delete(id)
|
||||||
|
if err != nil || changed || again.State != lab.Deleted {
|
||||||
|
t.Fatalf("second Delete() = %+v, %v, %v", again, changed, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLabsBeyondTheMemoryBudgetAreBusyAndStoreNothing(t *testing.T) {
|
||||||
|
h := newHarness(t, nil)
|
||||||
|
manager := h.start()
|
||||||
|
first, second := uuid.New(), uuid.New()
|
||||||
|
for index, id := range []uuid.UUID{first, second} {
|
||||||
|
if _, _, err := manager.Create(id, request(byte(index+1))); err != nil {
|
||||||
|
t.Fatalf("Create(%d) error = %v", index, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
extra := uuid.New()
|
||||||
|
if _, _, err := manager.Create(extra, request(9)); !errors.Is(err, pool.ErrBusy) {
|
||||||
|
t.Fatalf("third Create() error = %v, want ErrBusy", err)
|
||||||
|
}
|
||||||
|
if _, err := manager.Get(extra); !errors.Is(err, pool.ErrNotFound) {
|
||||||
|
t.Fatalf("a busy request was stored: %v", err)
|
||||||
|
}
|
||||||
|
if used, count := manager.Usage(); used != 2*labMemory || count != 2 {
|
||||||
|
t.Fatalf("Usage() = %d, %d", used, count)
|
||||||
|
}
|
||||||
|
|
||||||
|
waitFor(t, manager, first, inState(lab.Ready))
|
||||||
|
if _, _, err := manager.Delete(first); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
waitFor(t, manager, first, removed)
|
||||||
|
// Capacity returns only after the objects are gone; then the same ID is
|
||||||
|
// admitted.
|
||||||
|
if _, isNew, err := manager.Create(extra, request(9)); err != nil || !isNew {
|
||||||
|
t.Fatalf("Create() after a deletion = %v, %v", isNew, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLabCapAppliesBesideTheMemoryBudget(t *testing.T) {
|
||||||
|
h := newHarness(t, func(cfg *pool.Config) { cfg.MaxLabs = 1 })
|
||||||
|
manager := h.start()
|
||||||
|
if _, _, err := manager.Create(uuid.New(), request(1)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, _, err := manager.Create(uuid.New(), request(2)); !errors.Is(err, pool.ErrBusy) {
|
||||||
|
t.Fatalf("Create() error = %v, want ErrBusy", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateIsIdempotentByID(t *testing.T) {
|
||||||
|
h := newHarness(t, nil)
|
||||||
|
manager := h.start()
|
||||||
|
id := uuid.New()
|
||||||
|
if _, _, err := manager.Create(id, request(1)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
repeated, isNew, err := manager.Create(id, request(1))
|
||||||
|
if err != nil || isNew || repeated.ID != id {
|
||||||
|
t.Fatalf("repeated Create() = %+v, %v, %v", repeated, isNew, err)
|
||||||
|
}
|
||||||
|
if _, _, err := manager.Create(id, request(2)); !errors.Is(err, pool.ErrPayloadMismatch) {
|
||||||
|
t.Fatalf("Create() with another seed error = %v, want ErrPayloadMismatch", err)
|
||||||
|
}
|
||||||
|
if used, count := manager.Usage(); used != labMemory || count != 1 {
|
||||||
|
t.Fatalf("a repeat reserved capacity again: %d, %d", used, count)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateRefusesUnknownTemplatesAndLongLifetimes(t *testing.T) {
|
||||||
|
h := newHarness(t, nil)
|
||||||
|
manager := h.start()
|
||||||
|
unknown := request(1)
|
||||||
|
unknown.TemplateVersion = 2
|
||||||
|
if _, _, err := manager.Create(uuid.New(), unknown); !errors.Is(err, pool.ErrUnknownTemplate) {
|
||||||
|
t.Fatalf("Create() error = %v, want ErrUnknownTemplate", err)
|
||||||
|
}
|
||||||
|
long := request(1)
|
||||||
|
long.Lifetime = 3 * time.Hour
|
||||||
|
if _, _, err := manager.Create(uuid.New(), long); !errors.Is(err, pool.ErrLifetimeTooLong) {
|
||||||
|
t.Fatalf("Create() error = %v, want ErrLifetimeTooLong", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExpiryDeletesTheLabAfterARestart(t *testing.T) {
|
||||||
|
h := newHarness(t, nil)
|
||||||
|
first := h.start()
|
||||||
|
id := uuid.New()
|
||||||
|
if _, _, err := first.Create(id, request(1)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
waitFor(t, first, id, inState(lab.Ready))
|
||||||
|
// The process stops in the middle of the lab's life; its timer lives in
|
||||||
|
// the state file, not in the process.
|
||||||
|
if err := first.Close(context.Background()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
second := h.start()
|
||||||
|
second.Sweep(context.Background())
|
||||||
|
if record := waitFor(t, second, id, inState(lab.Ready)); h.fake.Instances()[record.Nodes[0].Instance].Spec.Name == "" {
|
||||||
|
t.Fatal("a running lab lost its nodes across the restart")
|
||||||
|
}
|
||||||
|
h.clock.Advance(29 * time.Minute)
|
||||||
|
second.Sweep(context.Background())
|
||||||
|
if record, _ := second.Get(id); record.State != lab.Ready {
|
||||||
|
t.Fatalf("lab ended before its timer: %s", record.State)
|
||||||
|
}
|
||||||
|
h.clock.Advance(time.Minute)
|
||||||
|
second.Sweep(context.Background())
|
||||||
|
waitFor(t, second, id, inState(lab.Deleted))
|
||||||
|
if instances, bridges := h.labObjects(id); instances+bridges != 0 {
|
||||||
|
t.Fatalf("LXD still holds %d instances and %d bridges after expiry", instances, bridges)
|
||||||
|
}
|
||||||
|
if _, _, err := second.ConsoleToken(id, "r1"); !errors.Is(err, pool.ErrNotReady) {
|
||||||
|
t.Fatalf("ConsoleToken() for a deleted lab error = %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
h.clock.Advance(time.Hour)
|
||||||
|
second.Sweep(context.Background())
|
||||||
|
if _, err := second.Get(id); !errors.Is(err, pool.ErrNotFound) {
|
||||||
|
t.Fatalf("Get() after the retention error = %v, want ErrNotFound", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRestartDuringProvisioningFailsAndDeletesTheLab(t *testing.T) {
|
||||||
|
h := newHarness(t, nil)
|
||||||
|
id := uuid.New()
|
||||||
|
created := h.clock.Now()
|
||||||
|
// The previous process wrote the record and created one bridge and one
|
||||||
|
// instance before it died.
|
||||||
|
record := lab.Lab{
|
||||||
|
ID: id, TemplateID: "mikrotik-pair", TemplateVersion: 1, Seed: strings.Repeat("01", 32), Fingerprint: "x",
|
||||||
|
State: lab.Provisioning, CreatedAt: created, ExpiresAt: created.Add(time.Hour), MemoryBytes: labMemory,
|
||||||
|
Nodes: []lab.Node{
|
||||||
|
{Name: "r1", Kind: "mikrotik", Instance: lab.InstanceName(id, "r1"), ManagementAddress: netip.MustParseAddr("10.81.0.16"), ManagementPort: 8728},
|
||||||
|
{Name: "srv", Kind: "ubuntu", Instance: lab.InstanceName(id, "srv"), ManagementAddress: netip.MustParseAddr("10.81.0.17"), ManagementPort: 22},
|
||||||
|
},
|
||||||
|
Bridges: []string{lab.BridgeName(id, 0), lab.BridgeName(id, 1)},
|
||||||
|
}
|
||||||
|
states, err := store.New(h.statePath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := states.Save([]lab.Lab{record}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
h.fake.AddNetwork(lxd.NetworkSpec{Name: record.Bridges[0], Config: map[string]string{lab.ConfigLab: id.String()}})
|
||||||
|
h.fake.AddInstance(lxd.InstanceSpec{
|
||||||
|
Name: record.Nodes[0].Instance, Config: map[string]string{lab.ConfigLab: id.String()},
|
||||||
|
Devices: map[string]map[string]string{"eth1": {"type": "nic", "network": record.Bridges[0]}},
|
||||||
|
}, true)
|
||||||
|
|
||||||
|
manager := h.start()
|
||||||
|
failed := waitFor(t, manager, id, removed)
|
||||||
|
if failed.State != lab.Failed || failed.FailureReason != lab.FailureInterrupted {
|
||||||
|
t.Fatalf("interrupted lab = %s %s", failed.State, failed.FailureReason)
|
||||||
|
}
|
||||||
|
if got := len(h.fake.Instances()) + len(h.fake.Networks()); got != 0 {
|
||||||
|
t.Fatalf("LXD still holds %d objects of the interrupted lab", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReconcileDeletesOrphansAndLeavesForeignObjects(t *testing.T) {
|
||||||
|
h := newHarness(t, nil)
|
||||||
|
manager := h.start()
|
||||||
|
kept := uuid.New()
|
||||||
|
if _, _, err := manager.Create(kept, request(1)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
waitFor(t, manager, kept, inState(lab.Ready))
|
||||||
|
|
||||||
|
orphan := uuid.New()
|
||||||
|
h.fake.AddNetwork(lxd.NetworkSpec{Name: lab.BridgeName(orphan, 0), Config: map[string]string{lab.ConfigLab: orphan.String()}})
|
||||||
|
h.fake.AddInstance(lxd.InstanceSpec{
|
||||||
|
Name: lab.InstanceName(orphan, "r1"), Config: map[string]string{lab.ConfigLab: orphan.String()},
|
||||||
|
Devices: map[string]map[string]string{"eth1": {"type": "nic", "network": lab.BridgeName(orphan, 0)}},
|
||||||
|
}, true)
|
||||||
|
// Same prefix, no marker: an object an operator made by hand.
|
||||||
|
h.fake.AddInstance(lxd.InstanceSpec{Name: "lcxl-operator-test"}, false)
|
||||||
|
h.fake.AddInstance(lxd.InstanceSpec{Name: "lincodex-runner", Config: map[string]string{lab.ConfigLab: "x"}}, true)
|
||||||
|
|
||||||
|
if err := manager.Reconcile(context.Background()); err != nil {
|
||||||
|
t.Fatalf("Reconcile() error = %v", err)
|
||||||
|
}
|
||||||
|
instances := h.fake.Instances()
|
||||||
|
if _, ok := instances[lab.InstanceName(orphan, "r1")]; ok {
|
||||||
|
t.Fatal("the orphaned instance survived")
|
||||||
|
}
|
||||||
|
if _, ok := h.fake.Networks()[lab.BridgeName(orphan, 0)]; ok {
|
||||||
|
t.Fatal("the orphaned bridge survived")
|
||||||
|
}
|
||||||
|
for _, name := range []string{"lcxl-operator-test", "lincodex-runner", lab.InstanceName(kept, "r1"), lab.InstanceName(kept, "srv")} {
|
||||||
|
if _, ok := instances[name]; !ok {
|
||||||
|
t.Fatalf("Reconcile() deleted %s", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProvisioningFailureFailsTheLabAndReturnsItsCapacity(t *testing.T) {
|
||||||
|
h := newHarness(t, nil)
|
||||||
|
h.fake.FailCreateInstance(func(name string) error {
|
||||||
|
if strings.HasSuffix(name, "-srv") {
|
||||||
|
return lxdfake.ErrInjected
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
manager := h.start()
|
||||||
|
id := uuid.New()
|
||||||
|
if _, _, err := manager.Create(id, request(1)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
failed := waitFor(t, manager, id, removed)
|
||||||
|
if failed.State != lab.Failed || failed.FailureReason != lab.FailureProvisioning {
|
||||||
|
t.Fatalf("lab = %s %s", failed.State, failed.FailureReason)
|
||||||
|
}
|
||||||
|
if instances, bridges := h.labObjects(id); instances+bridges != 0 {
|
||||||
|
t.Fatalf("a failed lab left %d instances and %d bridges", instances, bridges)
|
||||||
|
}
|
||||||
|
if used, count := manager.Usage(); used != 0 || count != 0 {
|
||||||
|
t.Fatalf("Usage() = %d, %d", used, count)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProvisioningTimeoutFailsTheLab(t *testing.T) {
|
||||||
|
h := newHarness(t, func(cfg *pool.Config) { cfg.ProvisionTimeout = 20 * time.Millisecond })
|
||||||
|
h.prober.down.Store(true)
|
||||||
|
manager := h.start()
|
||||||
|
id := uuid.New()
|
||||||
|
if _, _, err := manager.Create(id, request(1)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
failed := waitFor(t, manager, id, removed)
|
||||||
|
if failed.State != lab.Failed || failed.FailureReason != lab.FailureTimedOut {
|
||||||
|
t.Fatalf("lab = %s %s", failed.State, failed.FailureReason)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeletionIsRetriedUntilLXDConfirmsIt(t *testing.T) {
|
||||||
|
h := newHarness(t, nil)
|
||||||
|
manager := h.start()
|
||||||
|
id := uuid.New()
|
||||||
|
if _, _, err := manager.Create(id, request(1)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
waitFor(t, manager, id, inState(lab.Ready))
|
||||||
|
h.fake.FailDeletes(true)
|
||||||
|
if _, _, err := manager.Delete(id); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
time.Sleep(20 * time.Millisecond)
|
||||||
|
if record, _ := manager.Get(id); record.State != lab.Deleting || !record.HoldsResources() {
|
||||||
|
t.Fatalf("lab = %s with deleted_at %v, want deleting while LXD refuses", record.State, record.DeletedAt)
|
||||||
|
}
|
||||||
|
if _, count := manager.Usage(); count != 1 {
|
||||||
|
t.Fatal("capacity returned before the objects were gone")
|
||||||
|
}
|
||||||
|
h.fake.FailDeletes(false)
|
||||||
|
manager.Sweep(context.Background())
|
||||||
|
waitFor(t, manager, id, inState(lab.Deleted))
|
||||||
|
if instances, bridges := h.labObjects(id); instances+bridges != 0 {
|
||||||
|
t.Fatalf("LXD still holds %d instances and %d bridges", instances, bridges)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConsoleTokensAreSingleUseAndBoundToTheNode(t *testing.T) {
|
||||||
|
h := newHarness(t, nil)
|
||||||
|
manager := h.start()
|
||||||
|
id := uuid.New()
|
||||||
|
if _, _, err := manager.Create(id, request(1)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, _, err := manager.ConsoleToken(id, "r1"); !errors.Is(err, pool.ErrNotReady) && err != nil {
|
||||||
|
t.Fatalf("ConsoleToken() while provisioning error = %v", err)
|
||||||
|
}
|
||||||
|
waitFor(t, manager, id, inState(lab.Ready))
|
||||||
|
if _, _, err := manager.ConsoleToken(id, "r9"); !errors.Is(err, pool.ErrUnknownNode) {
|
||||||
|
t.Fatalf("ConsoleToken() for an unknown node error = %v", err)
|
||||||
|
}
|
||||||
|
token, expiresAt, err := manager.ConsoleToken(id, "srv")
|
||||||
|
if err != nil || len(token) != 43 || !expiresAt.Equal(h.clock.Now().Add(time.Minute)) {
|
||||||
|
t.Fatalf("ConsoleToken() = %q, %v, %v", token, expiresAt, err)
|
||||||
|
}
|
||||||
|
labID, node, err := manager.ConsumeConsoleToken(token)
|
||||||
|
if err != nil || labID != id || node != "srv" {
|
||||||
|
t.Fatalf("ConsumeConsoleToken() = %v, %q, %v", labID, node, err)
|
||||||
|
}
|
||||||
|
if _, _, err := manager.ConsumeConsoleToken(token); !errors.Is(err, pool.ErrNotFound) {
|
||||||
|
t.Fatalf("a token was accepted twice: %v", err)
|
||||||
|
}
|
||||||
|
expired, _, err := manager.ConsoleToken(id, "r1")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
h.clock.Advance(time.Minute)
|
||||||
|
if _, _, err := manager.ConsumeConsoleToken(expired); !errors.Is(err, pool.ErrNotFound) {
|
||||||
|
t.Fatalf("an expired token was accepted: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckRunsTheTemplateCheckerOnlyOnAReadyLab(t *testing.T) {
|
||||||
|
h := newHarness(t, nil)
|
||||||
|
manager := h.start()
|
||||||
|
id := uuid.New()
|
||||||
|
if _, _, err := manager.Create(id, request(1)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
waitFor(t, manager, id, inState(lab.Ready))
|
||||||
|
first, err := manager.Check(context.Background(), id)
|
||||||
|
if err != nil || len(first.Criteria) != 2 {
|
||||||
|
t.Fatalf("Check() = %+v, %v", first, err)
|
||||||
|
}
|
||||||
|
second, err := manager.Check(context.Background(), id)
|
||||||
|
if err != nil || second.Criteria[0] != first.Criteria[0] {
|
||||||
|
t.Fatalf("a repeated check of the same variant differs: %+v, %+v, %v", first, second, err)
|
||||||
|
}
|
||||||
|
if _, _, err := manager.Delete(id); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := manager.Check(context.Background(), id); !errors.Is(err, pool.ErrNotReady) {
|
||||||
|
t.Fatalf("Check() of a deleting lab error = %v, want ErrNotReady", err)
|
||||||
|
}
|
||||||
|
if _, err := manager.Check(context.Background(), uuid.New()); !errors.Is(err, pool.ErrNotFound) {
|
||||||
|
t.Fatalf("Check() of an unknown lab error = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewRefusesATemplateThatCanNeverFit(t *testing.T) {
|
||||||
|
h := newHarness(t, func(cfg *pool.Config) { cfg.MemoryBudgetBytes = labMemory - 1 })
|
||||||
|
states, err := store.New(h.statePath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
logger := slog.New(slog.DiscardHandler)
|
||||||
|
if _, err := pool.New(h.cfg, h.fake, states, h.registry, h.prober, h.clock.Now, logger); err == nil {
|
||||||
|
t.Fatal("New() accepted a budget below the smallest lab")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package pool
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TCPProber reports a node as reachable when its management port accepts a
|
||||||
|
// TCP connection from the host side of the management bridge.
|
||||||
|
type TCPProber struct {
|
||||||
|
Timeout time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// Probe opens and closes one connection.
|
||||||
|
func (p TCPProber) Probe(ctx context.Context, address netip.AddrPort) error {
|
||||||
|
dialer := net.Dialer{Timeout: p.Timeout}
|
||||||
|
connection, err := dialer.DialContext(ctx, "tcp", address.String())
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("TCPProber.Probe - dial: %w", err)
|
||||||
|
}
|
||||||
|
_ = connection.Close() // Only the accepted connection matters.
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
package pool
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"net/netip"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"lincodex/labd/internal/lab"
|
||||||
|
"lincodex/labd/internal/lxd"
|
||||||
|
"lincodex/labd/internal/template"
|
||||||
|
)
|
||||||
|
|
||||||
|
// startWorkerLocked runs the provisioning and deletion of one lab in its own
|
||||||
|
// goroutine. At most one worker exists per lab, so the provisioning and the
|
||||||
|
// deletion of a lab never race.
|
||||||
|
func (m *Manager) startWorkerLocked(id uuid.UUID) {
|
||||||
|
if _, running := m.workers[id]; running || !m.started || m.base.Err() != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
provisionCtx, cancel := context.WithCancel(m.base)
|
||||||
|
m.workers[id] = cancel
|
||||||
|
m.wg.Add(1)
|
||||||
|
go m.run(provisionCtx, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) run(provisionCtx context.Context, id uuid.UUID) {
|
||||||
|
defer m.wg.Done()
|
||||||
|
tornDown := false
|
||||||
|
defer func() {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
if cancel, ok := m.workers[id]; ok {
|
||||||
|
cancel()
|
||||||
|
delete(m.workers, id)
|
||||||
|
}
|
||||||
|
// A deletion requested while this worker finished provisioning
|
||||||
|
// starts at once instead of at the next sweep.
|
||||||
|
if record, ok := m.labs[id]; ok && !tornDown && record.NeedsTeardown() {
|
||||||
|
m.startWorkerLocked(id)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
if record, ok := m.snapshot(id); ok && record.State == lab.Provisioning {
|
||||||
|
m.provision(provisionCtx, record)
|
||||||
|
}
|
||||||
|
if m.base.Err() != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if record, ok := m.snapshot(id); ok && record.NeedsTeardown() {
|
||||||
|
tornDown = true
|
||||||
|
m.teardown(m.base, record)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) snapshot(id uuid.UUID) (lab.Lab, bool) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
record, ok := m.labs[id]
|
||||||
|
if !ok {
|
||||||
|
return lab.Lab{}, false
|
||||||
|
}
|
||||||
|
return record.Clone(), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// provision builds the lab and records the outcome. A cancelled
|
||||||
|
// provisioning (deletion, expiry) records nothing: the lab is already
|
||||||
|
// deleting. A stopped process records nothing either: the next start fails
|
||||||
|
// the lab as interrupted.
|
||||||
|
func (m *Manager) provision(provisionCtx context.Context, record lab.Lab) {
|
||||||
|
ctx, cancel := context.WithTimeout(provisionCtx, m.cfg.ProvisionTimeout)
|
||||||
|
defer cancel()
|
||||||
|
started := time.Now()
|
||||||
|
err := m.build(ctx, record)
|
||||||
|
switch {
|
||||||
|
case err == nil:
|
||||||
|
m.finishProvisioning(record.ID, "", nil)
|
||||||
|
m.logger.Info("lab ready", slog.String("lab_id", record.ID.String()),
|
||||||
|
slog.Int64("provision_ms", time.Since(started).Milliseconds()))
|
||||||
|
case provisionCtx.Err() != nil:
|
||||||
|
return
|
||||||
|
case errors.Is(err, context.DeadlineExceeded):
|
||||||
|
m.finishProvisioning(record.ID, lab.FailureTimedOut, err)
|
||||||
|
default:
|
||||||
|
m.finishProvisioning(record.ID, lab.FailureProvisioning, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) finishProvisioning(id uuid.UUID, reason lab.FailureReason, cause error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
record, ok := m.labs[id]
|
||||||
|
if !ok || record.State != lab.Provisioning {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if reason == "" {
|
||||||
|
record.State = lab.Ready
|
||||||
|
record.ReadyAt = m.now().UTC()
|
||||||
|
} else {
|
||||||
|
record.State = lab.Failed
|
||||||
|
record.FailureReason = reason
|
||||||
|
// The LXD text may name host paths; it stays in the labd log.
|
||||||
|
m.logger.Warn("lab provisioning failed", slog.String("lab_id", id.String()),
|
||||||
|
slog.String("reason", string(reason)), slog.String("error", cause.Error()))
|
||||||
|
}
|
||||||
|
if err := m.persistLocked(); err != nil {
|
||||||
|
m.logger.Error("lab state not saved", slog.String("lab_id", id.String()), slog.String("error", err.Error()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// build creates the bridges and instances of a lab, starts the instances,
|
||||||
|
// and waits until every node answers on its management port.
|
||||||
|
func (m *Manager) build(ctx context.Context, record lab.Lab) error {
|
||||||
|
chosen, ok := m.templates.Lookup(record.TemplateID, record.TemplateVersion)
|
||||||
|
if !ok {
|
||||||
|
return errors.New("Manager.build - the template of the lab is not in this build")
|
||||||
|
}
|
||||||
|
variant, err := m.plan(record, chosen)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
bootstraps, err := chosen.Render(variant)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Manager.build - render: %w", err)
|
||||||
|
}
|
||||||
|
for index, link := range chosen.Links {
|
||||||
|
spec := lxd.NetworkSpec{
|
||||||
|
Name: record.Bridges[index],
|
||||||
|
Description: "Lincodex lab link " + link.Name,
|
||||||
|
// No address on the host side: the bridge is L2 only, so lab
|
||||||
|
// traffic is neither routed nor answered by the host.
|
||||||
|
Config: map[string]string{"ipv4.address": "none", "ipv6.address": "none", lab.ConfigLab: record.ID.String()},
|
||||||
|
}
|
||||||
|
if err := m.lxd.CreateNetwork(ctx, spec); err != nil {
|
||||||
|
return fmt.Errorf("Manager.build - create bridge: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for index, node := range chosen.Nodes {
|
||||||
|
bootstrap := bootstraps[node.Name]
|
||||||
|
if err := template.ValidateBootstrap(bootstrap); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
spec := m.instanceSpec(record, chosen, node, variant.Nodes[index], bootstrap)
|
||||||
|
if err := m.lxd.CreateInstance(ctx, spec); err != nil {
|
||||||
|
return fmt.Errorf("Manager.build - create instance: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, node := range record.Nodes {
|
||||||
|
if err := m.lxd.StartInstance(ctx, node.Instance); err != nil {
|
||||||
|
return fmt.Errorf("Manager.build - start instance: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return m.waitReachable(ctx, record)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) instanceSpec(record lab.Lab, chosen template.Template, node template.Node, planned template.PlannedNode, bootstrap template.Bootstrap) lxd.InstanceSpec {
|
||||||
|
config := map[string]string{
|
||||||
|
lab.ConfigLab: record.ID.String(),
|
||||||
|
lab.ConfigNode: node.Name,
|
||||||
|
lab.ConfigExpiresAt: record.ExpiresAt.Format(time.RFC3339),
|
||||||
|
// The guest gets no LXD guest API.
|
||||||
|
"security.devlxd": "false",
|
||||||
|
}
|
||||||
|
devices := map[string]map[string]string{
|
||||||
|
// The management NIC overrides the profile NIC: a fixed MAC that
|
||||||
|
// cloud-init matches, no MAC spoofing, and no traffic to other
|
||||||
|
// isolated ports of the bridge, that is, to other nodes.
|
||||||
|
"eth0": {
|
||||||
|
"type": "nic", "network": m.cfg.ManagementNetwork, "hwaddr": planned.ManagementMAC,
|
||||||
|
"security.mac_filtering": "true", "security.port_isolation": "true",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
bridges := make(map[string]string, len(chosen.Links))
|
||||||
|
for index, link := range chosen.Links {
|
||||||
|
bridges[link.Name] = record.Bridges[index]
|
||||||
|
}
|
||||||
|
for _, nic := range planned.Interfaces {
|
||||||
|
devices[nic.Device] = map[string]string{"type": "nic", "network": bridges[nic.Link], "hwaddr": nic.MAC}
|
||||||
|
}
|
||||||
|
if bootstrap.UserData != "" || bootstrap.NetworkConfig != "" {
|
||||||
|
if bootstrap.UserData != "" {
|
||||||
|
config["cloud-init.user-data"] = bootstrap.UserData
|
||||||
|
}
|
||||||
|
if bootstrap.NetworkConfig != "" {
|
||||||
|
config["cloud-init.network-config"] = bootstrap.NetworkConfig
|
||||||
|
}
|
||||||
|
// A VM reads its cloud-init data from this config drive.
|
||||||
|
devices["cloud-init"] = map[string]string{"type": "disk", "source": "cloud-init:config"}
|
||||||
|
}
|
||||||
|
return lxd.InstanceSpec{
|
||||||
|
Name: lab.InstanceName(record.ID, node.Name),
|
||||||
|
Description: "Lincodex lab node " + node.Name,
|
||||||
|
Source: node.Source,
|
||||||
|
Profiles: []string{node.Profile},
|
||||||
|
Config: config,
|
||||||
|
Devices: devices,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) waitReachable(ctx context.Context, record lab.Lab) error {
|
||||||
|
for _, node := range record.Nodes {
|
||||||
|
address := netip.AddrPortFrom(node.ManagementAddress, node.ManagementPort)
|
||||||
|
for {
|
||||||
|
err := m.prober.Probe(ctx, address)
|
||||||
|
if err == nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
timer := time.NewTimer(m.cfg.ProbeInterval)
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
timer.Stop()
|
||||||
|
return fmt.Errorf("Manager.waitReachable - node %s: %w", node.Name, ctx.Err())
|
||||||
|
case <-timer.C:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// teardown deletes every instance and bridge of a lab. LXD answers not found
|
||||||
|
// for an object that never existed or is already gone, which counts as
|
||||||
|
// deleted. On any other failure the lab stays deleting and the next sweep
|
||||||
|
// tries again.
|
||||||
|
func (m *Manager) teardown(ctx context.Context, record lab.Lab) {
|
||||||
|
var errs []error
|
||||||
|
for _, node := range record.Nodes {
|
||||||
|
if err := m.deleteInstance(ctx, node.Instance); err != nil {
|
||||||
|
errs = append(errs, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(errs) == 0 {
|
||||||
|
for _, bridge := range record.Bridges {
|
||||||
|
if err := m.deleteNetwork(ctx, bridge); err != nil {
|
||||||
|
errs = append(errs, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := errors.Join(errs...); err != nil {
|
||||||
|
m.logger.Warn("lab deletion incomplete; retrying on the next sweep",
|
||||||
|
slog.String("lab_id", record.ID.String()), slog.String("error", err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
current, ok := m.labs[record.ID]
|
||||||
|
if !ok || !current.NeedsTeardown() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
current.DeletedAt = m.now().UTC()
|
||||||
|
if current.State == lab.Deleting {
|
||||||
|
current.State = lab.Deleted
|
||||||
|
}
|
||||||
|
if err := m.persistLocked(); err != nil {
|
||||||
|
m.logger.Error("lab state not saved", slog.String("lab_id", record.ID.String()), slog.String("error", err.Error()))
|
||||||
|
}
|
||||||
|
m.logger.Info("lab deleted", slog.String("lab_id", record.ID.String()), slog.String("state", string(current.State)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) deleteInstance(ctx context.Context, name string) error {
|
||||||
|
if err := m.lxd.StopInstance(ctx, name); err != nil {
|
||||||
|
if errors.Is(err, lxd.ErrNotFound) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return fmt.Errorf("Manager.deleteInstance - stop %s: %w", name, err)
|
||||||
|
}
|
||||||
|
if err := m.lxd.DeleteInstance(ctx, name); err != nil && !errors.Is(err, lxd.ErrNotFound) {
|
||||||
|
return fmt.Errorf("Manager.deleteInstance - delete %s: %w", name, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) deleteNetwork(ctx context.Context, name string) error {
|
||||||
|
if err := m.lxd.DeleteNetwork(ctx, name); err != nil && !errors.Is(err, lxd.ErrNotFound) {
|
||||||
|
return fmt.Errorf("Manager.deleteNetwork - delete %s: %w", name, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
// Package reaper runs the periodic work that makes lab deletion
|
||||||
|
// guaranteed: it ends labs at their timers, retries unfinished deletions,
|
||||||
|
// and removes LXD objects that no lab record owns.
|
||||||
|
package reaper
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"log/slog"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Target is the lab manager.
|
||||||
|
type Target interface {
|
||||||
|
// Sweep ends expired labs and retries pending deletions.
|
||||||
|
Sweep(ctx context.Context)
|
||||||
|
// Reconcile deletes orphaned LXD objects.
|
||||||
|
Reconcile(ctx context.Context) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Config holds the intervals of the reaper.
|
||||||
|
type Config struct {
|
||||||
|
SweepInterval time.Duration
|
||||||
|
ReconcileInterval time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run sweeps every SweepInterval and reconciles every ReconcileInterval until
|
||||||
|
// ctx ends. The first sweep runs at once; the caller reconciles once before
|
||||||
|
// it serves. A failed reconciliation is logged and retried on schedule;
|
||||||
|
// reconciled reports each outcome, for readiness.
|
||||||
|
func Run(ctx context.Context, target Target, cfg Config, reconciled func(error), logger *slog.Logger) {
|
||||||
|
sweep := time.NewTicker(cfg.SweepInterval)
|
||||||
|
defer sweep.Stop()
|
||||||
|
reconcile := time.NewTicker(cfg.ReconcileInterval)
|
||||||
|
defer reconcile.Stop()
|
||||||
|
target.Sweep(ctx)
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-sweep.C:
|
||||||
|
target.Sweep(ctx)
|
||||||
|
case <-reconcile.C:
|
||||||
|
err := target.Reconcile(ctx)
|
||||||
|
if err != nil && ctx.Err() == nil {
|
||||||
|
logger.WarnContext(ctx, "lab reconciliation failed; retrying on schedule", slog.String("error", err.Error()))
|
||||||
|
}
|
||||||
|
reconciled(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package reaper_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"log/slog"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"lincodex/labd/internal/reaper"
|
||||||
|
)
|
||||||
|
|
||||||
|
type target struct {
|
||||||
|
sweeps atomic.Int32
|
||||||
|
reconciles atomic.Int32
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *target) Sweep(context.Context) { t.sweeps.Add(1) }
|
||||||
|
|
||||||
|
func (t *target) Reconcile(context.Context) error {
|
||||||
|
t.reconciles.Add(1)
|
||||||
|
return errors.New("lxd unreachable")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunSweepsAndReconcilesUntilCancelled(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
work := &target{}
|
||||||
|
var failures atomic.Int32
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
defer close(done)
|
||||||
|
reaper.Run(ctx, work, reaper.Config{SweepInterval: time.Millisecond, ReconcileInterval: 2 * time.Millisecond},
|
||||||
|
func(err error) {
|
||||||
|
if err != nil {
|
||||||
|
failures.Add(1)
|
||||||
|
}
|
||||||
|
}, slog.New(slog.DiscardHandler))
|
||||||
|
}()
|
||||||
|
deadline := time.Now().Add(5 * time.Second)
|
||||||
|
for work.sweeps.Load() < 3 || failures.Load() < 2 {
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatalf("sweeps %d, failed reconciliations %d", work.sweeps.Load(), failures.Load())
|
||||||
|
}
|
||||||
|
time.Sleep(time.Millisecond)
|
||||||
|
}
|
||||||
|
cancel()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("Run() did not return after cancellation")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
// Package server implements the labd HTTP API on the generated ogen server.
|
||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"math"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
ogenerrors "github.com/ogen-go/ogen/ogenerrors"
|
||||||
|
|
||||||
|
"lincodex/labd/internal/api"
|
||||||
|
"lincodex/labd/internal/lab"
|
||||||
|
"lincodex/labd/internal/pool"
|
||||||
|
"lincodex/labd/internal/template"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Labs is the lab manager; pool.Manager implements it.
|
||||||
|
type Labs interface {
|
||||||
|
Create(id uuid.UUID, request pool.CreateRequest) (lab.Lab, bool, error)
|
||||||
|
Get(id uuid.UUID) (lab.Lab, error)
|
||||||
|
Delete(id uuid.UUID) (lab.Lab, bool, error)
|
||||||
|
ConsoleToken(id uuid.UUID, node string) (string, time.Time, error)
|
||||||
|
Check(ctx context.Context, id uuid.UUID) (pool.CheckResult, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handler implements the generated api.Handler.
|
||||||
|
type Handler struct {
|
||||||
|
labs Labs
|
||||||
|
ready func() bool
|
||||||
|
retryAfter time.Duration
|
||||||
|
logger *slog.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ api.Handler = (*Handler)(nil)
|
||||||
|
|
||||||
|
// NewHandler returns the API handler.
|
||||||
|
func NewHandler(labs Labs, ready func() bool, retryAfter time.Duration, logger *slog.Logger) *Handler {
|
||||||
|
return &Handler{labs: labs, ready: ready, retryAfter: retryAfter, logger: logger}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLabdHealthz reports that the process responds.
|
||||||
|
func (h *Handler) GetLabdHealthz(context.Context) (*api.LabdHealthResponse, error) {
|
||||||
|
return &api.LabdHealthResponse{Status: api.LabdHealthResponseStatusOk}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLabdReadyz reports whether labs can be created and deleted.
|
||||||
|
func (h *Handler) GetLabdReadyz(context.Context) (api.GetLabdReadyzRes, error) {
|
||||||
|
if h.ready() {
|
||||||
|
return &api.GetLabdReadyzOK{Status: api.LabdReadinessResponseStatusReady}, nil
|
||||||
|
}
|
||||||
|
return &api.GetLabdReadyzServiceUnavailable{Status: api.LabdReadinessResponseStatusNotReady}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateLab admits a lab or returns the lab with the same ID and payload.
|
||||||
|
func (h *Handler) CreateLab(_ context.Context, req *api.LabCreateRequest, params api.CreateLabParams) (api.CreateLabRes, error) {
|
||||||
|
seed, err := hex.DecodeString(req.Seed)
|
||||||
|
if err != nil || len(seed) != template.SeedBytes {
|
||||||
|
return nil, problemError(http.StatusBadRequest, api.ProblemCodeValidationFailed, "One or more request fields are invalid.",
|
||||||
|
invalidField(api.ProblemFieldLocationBody, "/seed"))
|
||||||
|
}
|
||||||
|
record, created, err := h.labs.Create(params.LabID, pool.CreateRequest{
|
||||||
|
TemplateID: string(req.TemplateID),
|
||||||
|
TemplateVersion: int(req.TemplateVersion),
|
||||||
|
Seed: [template.SeedBytes]byte(seed),
|
||||||
|
Lifetime: time.Duration(req.TTLSeconds) * time.Second,
|
||||||
|
})
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, pool.ErrBusy):
|
||||||
|
return &api.LabPoolBusyHeaders{
|
||||||
|
RetryAfter: int32(min(math.Ceil(h.retryAfter.Seconds()), math.MaxInt32)),
|
||||||
|
Response: newProblem(http.StatusServiceUnavailable, api.ProblemCodeLabPoolBusy, "No capacity for another lab. Retry later with the same lab ID."),
|
||||||
|
}, nil
|
||||||
|
case errors.Is(err, pool.ErrUnknownTemplate):
|
||||||
|
return nil, problemError(http.StatusBadRequest, api.ProblemCodeValidationFailed, "The template or its version is unknown.",
|
||||||
|
invalidField(api.ProblemFieldLocationBody, "/template_id"), invalidField(api.ProblemFieldLocationBody, "/template_version"))
|
||||||
|
case errors.Is(err, pool.ErrLifetimeTooLong):
|
||||||
|
return nil, problemError(http.StatusBadRequest, api.ProblemCodeValidationFailed, "The lifetime exceeds the maximum.",
|
||||||
|
invalidField(api.ProblemFieldLocationBody, "/ttl_seconds"))
|
||||||
|
case errors.Is(err, pool.ErrPayloadMismatch):
|
||||||
|
return nil, problemError(http.StatusUnprocessableEntity, api.ProblemCodeIdempotencyKeyReused, "A lab with this ID exists with a different payload.")
|
||||||
|
case errors.Is(err, pool.ErrIDCollision):
|
||||||
|
return nil, problemError(http.StatusConflict, api.ProblemCodeStateConflict, "The lab ID collides with another lab. Use another lab ID.")
|
||||||
|
case err != nil:
|
||||||
|
return nil, fmt.Errorf("server.Handler.CreateLab - create: %w", err)
|
||||||
|
}
|
||||||
|
status := toLabStatus(record)
|
||||||
|
if created {
|
||||||
|
accepted := api.CreateLabAccepted(status)
|
||||||
|
return &accepted, nil
|
||||||
|
}
|
||||||
|
existing := api.CreateLabOK(status)
|
||||||
|
return &existing, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLab returns the state of a lab.
|
||||||
|
func (h *Handler) GetLab(_ context.Context, params api.GetLabParams) (*api.LabStatus, error) {
|
||||||
|
record, err := h.labs.Get(params.LabID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, h.labError("GetLab", err)
|
||||||
|
}
|
||||||
|
status := toLabStatus(record)
|
||||||
|
return &status, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteLab ends a lab before its timer.
|
||||||
|
func (h *Handler) DeleteLab(_ context.Context, params api.DeleteLabParams) (api.DeleteLabRes, error) {
|
||||||
|
record, changed, err := h.labs.Delete(params.LabID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, h.labError("DeleteLab", err)
|
||||||
|
}
|
||||||
|
status := toLabStatus(record)
|
||||||
|
if changed {
|
||||||
|
accepted := api.DeleteLabAccepted(status)
|
||||||
|
return &accepted, nil
|
||||||
|
}
|
||||||
|
existing := api.DeleteLabOK(status)
|
||||||
|
return &existing, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateLabConsoleToken issues a console token for one node.
|
||||||
|
func (h *Handler) CreateLabConsoleToken(_ context.Context, req *api.ConsoleTokenRequest, params api.CreateLabConsoleTokenParams) (*api.ConsoleTokenHeaders, error) {
|
||||||
|
token, expiresAt, err := h.labs.ConsoleToken(params.LabID, string(req.Node))
|
||||||
|
if errors.Is(err, pool.ErrUnknownNode) {
|
||||||
|
return nil, problemError(http.StatusBadRequest, api.ProblemCodeValidationFailed, "The lab has no such node.",
|
||||||
|
invalidField(api.ProblemFieldLocationBody, "/node"))
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, h.labError("CreateLabConsoleToken", err)
|
||||||
|
}
|
||||||
|
return &api.ConsoleTokenHeaders{
|
||||||
|
CacheControl: api.CreateLabConsoleTokenCreatedCacheControlNoStore,
|
||||||
|
Response: api.ConsoleToken{
|
||||||
|
Token: token, Node: req.Node, ExpiresAt: expiresAt,
|
||||||
|
AttachPath: "/v1/labs/" + params.LabID.String() + "/console",
|
||||||
|
},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckLab runs the checker of the template against a ready lab.
|
||||||
|
func (h *Handler) CheckLab(ctx context.Context, params api.CheckLabParams) (*api.LabCheckResult, error) {
|
||||||
|
result, err := h.labs.Check(ctx, params.LabID)
|
||||||
|
if errors.Is(err, pool.ErrCheckUnavailable) {
|
||||||
|
h.logger.WarnContext(ctx, "lab check unavailable", slog.String("lab_id", params.LabID.String()), slog.String("error", err.Error()))
|
||||||
|
return nil, problemError(http.StatusServiceUnavailable, api.ProblemCodeLabUnavailable, "The lab could not be evaluated. Nothing was checked.")
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, h.labError("CheckLab", err)
|
||||||
|
}
|
||||||
|
converted := api.LabCheckResult{LabID: params.LabID, CheckedAt: result.CheckedAt, Criteria: make([]api.CriterionResult, 0, len(result.Criteria))}
|
||||||
|
for _, criterion := range result.Criteria {
|
||||||
|
converted.Criteria = append(converted.Criteria, api.CriterionResult{ID: api.CriterionId(criterion.ID), Passed: criterion.Passed})
|
||||||
|
if criterion.Passed {
|
||||||
|
converted.Score++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
converted.MaxScore = int32(len(result.Criteria)) //nolint:gosec // Criteria are bounded by the template package.
|
||||||
|
return &converted, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// labError maps the errors that several operations share.
|
||||||
|
func (h *Handler) labError(operation string, err error) error {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, pool.ErrNotFound):
|
||||||
|
return problemError(http.StatusNotFound, api.ProblemCodeNotFound, "The provisioner holds no lab with this ID.")
|
||||||
|
case errors.Is(err, pool.ErrNotReady):
|
||||||
|
return problemError(http.StatusConflict, api.ProblemCodeStateConflict, "The lab is not ready.")
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("server.Handler.%s: %w", operation, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewError maps errors of handlers and of the security check to problems.
|
||||||
|
func (h *Handler) NewError(ctx context.Context, err error) *api.ProblemStatusCode {
|
||||||
|
var securityErr *ogenerrors.SecurityError
|
||||||
|
if errors.As(err, &securityErr) {
|
||||||
|
return problemError(http.StatusUnauthorized, api.ProblemCodeUnauthenticated, "Send a valid bearer token.")
|
||||||
|
}
|
||||||
|
h.logger.ErrorContext(ctx, "request failed", slog.String("error_type", fmt.Sprintf("%T", err)))
|
||||||
|
return problemError(http.StatusInternalServerError, api.ProblemCodeInternal, "The server could not complete the request.")
|
||||||
|
}
|
||||||
|
|
||||||
|
// toLabStatus converts a record. It copies only the fields of the contract:
|
||||||
|
// no address, instance, bridge, or seed leaves labd.
|
||||||
|
func toLabStatus(record lab.Lab) api.LabStatus {
|
||||||
|
status := api.LabStatus{
|
||||||
|
LabID: record.ID,
|
||||||
|
State: api.LabState(record.State),
|
||||||
|
TemplateID: api.TemplateId(record.TemplateID),
|
||||||
|
TemplateVersion: int32(record.TemplateVersion), //nolint:gosec // Template versions are at most 10000.
|
||||||
|
CreatedAt: record.CreatedAt,
|
||||||
|
ExpiresAt: record.ExpiresAt,
|
||||||
|
Nodes: make([]api.LabNode, 0, len(record.Nodes)),
|
||||||
|
}
|
||||||
|
if !record.ReadyAt.IsZero() {
|
||||||
|
status.ReadyAt = api.NewOptDateTime(record.ReadyAt)
|
||||||
|
}
|
||||||
|
if !record.DeletedAt.IsZero() {
|
||||||
|
status.DeletedAt = api.NewOptDateTime(record.DeletedAt)
|
||||||
|
}
|
||||||
|
if record.FailureReason != "" {
|
||||||
|
status.FailureReason = api.NewOptLabFailureReason(api.LabFailureReason(record.FailureReason))
|
||||||
|
}
|
||||||
|
for _, node := range record.Nodes {
|
||||||
|
status.Nodes = append(status.Nodes, api.LabNode{Name: api.NodeName(node.Name), Kind: api.NodeKind(node.Kind)})
|
||||||
|
}
|
||||||
|
return status
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/go-faster/jx"
|
||||||
|
ogenerrors "github.com/ogen-go/ogen/ogenerrors"
|
||||||
|
"github.com/ogen-go/ogen/validate"
|
||||||
|
|
||||||
|
"lincodex/labd/internal/api"
|
||||||
|
)
|
||||||
|
|
||||||
|
const problemTypePrefix = "urn:lincodex:problem:"
|
||||||
|
|
||||||
|
// problemTitles are the fixed titles of the lab provisioner problem codes.
|
||||||
|
var problemTitles = map[api.ProblemCode]string{
|
||||||
|
api.ProblemCodeValidationFailed: "Request validation failed",
|
||||||
|
api.ProblemCodeUnauthenticated: "Authentication required",
|
||||||
|
api.ProblemCodeNotFound: "Not found",
|
||||||
|
api.ProblemCodeMethodNotAllowed: "Method not allowed",
|
||||||
|
api.ProblemCodeStateConflict: "State conflict",
|
||||||
|
api.ProblemCodePayloadTooLarge: "Payload too large",
|
||||||
|
api.ProblemCodeUnsupportedMediaType: "Unsupported media type",
|
||||||
|
api.ProblemCodeIdempotencyKeyReused: "Lab ID reused with a different payload",
|
||||||
|
api.ProblemCodeInternal: "Internal server error",
|
||||||
|
api.ProblemCodeNotImplemented: "Not implemented",
|
||||||
|
api.ProblemCodeLabPoolBusy: "Lab pool busy",
|
||||||
|
api.ProblemCodeLabUnavailable: "Lab unavailable",
|
||||||
|
}
|
||||||
|
|
||||||
|
const invalidFieldMessage = "The value does not match the contract."
|
||||||
|
|
||||||
|
func newProblem(status int, code api.ProblemCode, detail string, fieldErrors ...api.ProblemFieldError) api.Problem {
|
||||||
|
problem := api.Problem{
|
||||||
|
Type: problemTypePrefix + string(code),
|
||||||
|
Title: problemTitles[code],
|
||||||
|
Status: int32(status), //nolint:gosec // HTTP status codes fit in int32.
|
||||||
|
Code: code,
|
||||||
|
Errors: fieldErrors,
|
||||||
|
}
|
||||||
|
if detail != "" {
|
||||||
|
problem.Detail = api.NewOptString(detail)
|
||||||
|
}
|
||||||
|
return problem
|
||||||
|
}
|
||||||
|
|
||||||
|
func problemError(status int, code api.ProblemCode, detail string, fieldErrors ...api.ProblemFieldError) *api.ProblemStatusCode {
|
||||||
|
return &api.ProblemStatusCode{StatusCode: status, Response: newProblem(status, code, detail, fieldErrors...)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func invalidField(in api.ProblemFieldLocation, pointer string) api.ProblemFieldError {
|
||||||
|
return api.ProblemFieldError{In: in, Pointer: pointer, Code: "invalid", Message: invalidFieldMessage}
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeProblem writes a problem outside the generated handlers.
|
||||||
|
func writeProblem(w http.ResponseWriter, problem api.Problem) {
|
||||||
|
encoder := jx.GetEncoder()
|
||||||
|
defer jx.PutEncoder(encoder)
|
||||||
|
problem.Encode(encoder)
|
||||||
|
w.Header().Set("Content-Type", "application/problem+json")
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
w.WriteHeader(int(problem.Status))
|
||||||
|
_, _ = w.Write(encoder.Bytes()) // The client may have gone away.
|
||||||
|
}
|
||||||
|
|
||||||
|
// errorHandler answers request decoding errors of the generated server.
|
||||||
|
func errorHandler(logger *slog.Logger) ogenerrors.ErrorHandler {
|
||||||
|
return func(ctx context.Context, w http.ResponseWriter, _ *http.Request, err error) {
|
||||||
|
writeProblem(w, decodeProblem(ctx, logger, err))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeProblem(ctx context.Context, logger *slog.Logger, err error) api.Problem {
|
||||||
|
var tooLarge *http.MaxBytesError
|
||||||
|
var contentType *validate.InvalidContentTypeError
|
||||||
|
var paramsErr *ogenerrors.DecodeParamsError
|
||||||
|
var requestErr *ogenerrors.DecodeRequestError
|
||||||
|
switch {
|
||||||
|
case errors.As(err, &tooLarge):
|
||||||
|
return newProblem(http.StatusRequestEntityTooLarge, api.ProblemCodePayloadTooLarge, "The request body exceeds the limit.")
|
||||||
|
case errors.As(err, &contentType):
|
||||||
|
return newProblem(http.StatusUnsupportedMediaType, api.ProblemCodeUnsupportedMediaType, "Send the body as application/json.")
|
||||||
|
case errors.As(err, ¶msErr):
|
||||||
|
return newProblem(http.StatusBadRequest, api.ProblemCodeValidationFailed, "One or more request fields are invalid.",
|
||||||
|
invalidField(api.ProblemFieldLocationPath, "/lab_id"))
|
||||||
|
case errors.As(err, &requestErr):
|
||||||
|
return newProblem(http.StatusBadRequest, api.ProblemCodeValidationFailed, "One or more request fields are invalid.",
|
||||||
|
invalidField(api.ProblemFieldLocationBody, ""))
|
||||||
|
default:
|
||||||
|
// The error text may describe internals; only its type is logged.
|
||||||
|
logger.ErrorContext(ctx, "request handling failed", slog.String("error_type", fmt.Sprintf("%T", err)))
|
||||||
|
return newProblem(http.StatusInternalServerError, api.ProblemCodeInternal, "The server could not complete the request.")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
package server
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/subtle"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"net/netip"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"lincodex/labd/internal/api"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
errInvalidToken = errors.New("invalid bearer token")
|
||||||
|
// consoleAttachPath is the planned WebSocket attach of a console token.
|
||||||
|
consoleAttachPath = regexp.MustCompile(`^/v1/labs/[^/]+/console$`)
|
||||||
|
)
|
||||||
|
|
||||||
|
// tokenAuth checks the shared service token. Comparing SHA-256 digests in
|
||||||
|
// constant time hides both the content and the length of the token.
|
||||||
|
type tokenAuth struct {
|
||||||
|
digest [sha256.Size]byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a tokenAuth) HandleBearerAuth(ctx context.Context, _ api.OperationName, token api.BearerAuth) (context.Context, error) {
|
||||||
|
if !a.valid(token.Token) {
|
||||||
|
return ctx, errInvalidToken
|
||||||
|
}
|
||||||
|
return ctx, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a tokenAuth) valid(token string) bool {
|
||||||
|
digest := sha256.Sum256([]byte(token))
|
||||||
|
return subtle.ConstantTimeCompare(digest[:], a.digest[:]) == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// Options configure the HTTP handler.
|
||||||
|
type Options struct {
|
||||||
|
Token string
|
||||||
|
MaxRequestBytes int64
|
||||||
|
// AllowedClients are the networks requests may come from.
|
||||||
|
AllowedClients []netip.Prefix
|
||||||
|
}
|
||||||
|
|
||||||
|
// New returns the HTTP handler of the labd API.
|
||||||
|
func New(handler *Handler, options Options, logger *slog.Logger) (http.Handler, error) {
|
||||||
|
if options.Token == "" {
|
||||||
|
return nil, errors.New("server.New - empty service token")
|
||||||
|
}
|
||||||
|
if len(options.AllowedClients) == 0 {
|
||||||
|
return nil, errors.New("server.New - no allowed client network")
|
||||||
|
}
|
||||||
|
auth := tokenAuth{digest: sha256.Sum256([]byte(options.Token))}
|
||||||
|
generated, err := api.NewServer(handler, auth,
|
||||||
|
api.WithErrorHandler(errorHandler(logger)),
|
||||||
|
api.WithNotFound(func(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
writeProblem(w, newProblem(http.StatusNotFound, api.ProblemCodeNotFound, "The route does not exist."))
|
||||||
|
}),
|
||||||
|
api.WithMethodNotAllowed(func(w http.ResponseWriter, _ *http.Request, allowed string) {
|
||||||
|
w.Header().Set("Allow", allowed)
|
||||||
|
writeProblem(w, newProblem(http.StatusMethodNotAllowed, api.ProblemCodeMethodNotAllowed, "The route does not support this method."))
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("server.New - generated server: %w", err)
|
||||||
|
}
|
||||||
|
routes := consoleAttach(auth, limitBody(options.MaxRequestBytes, generated))
|
||||||
|
return accessLog(generated, logger, recoverPanics(logger, allowClients(options.AllowedClients, logger, routes))), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// allowClients refuses requests from outside the allowed networks before
|
||||||
|
// any other check, as if the token were wrong, so the answer tells such a
|
||||||
|
// caller nothing.
|
||||||
|
func allowClients(allowed []netip.Prefix, logger *slog.Logger, next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
address, err := netip.ParseAddrPort(r.RemoteAddr)
|
||||||
|
if err != nil || !contains(allowed, address.Addr().Unmap()) {
|
||||||
|
logger.WarnContext(r.Context(), "request from a network outside LABD_ALLOWED_CLIENTS refused", slog.String("remote", r.RemoteAddr))
|
||||||
|
writeProblem(w, newProblem(http.StatusUnauthorized, api.ProblemCodeUnauthenticated, "Send a valid bearer token."))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func contains(prefixes []netip.Prefix, address netip.Addr) bool {
|
||||||
|
for _, prefix := range prefixes {
|
||||||
|
if prefix.Contains(address) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// consoleAttach answers the planned WebSocket attach of a console token. It
|
||||||
|
// checks the service token like every operation and then reports the attach
|
||||||
|
// as not implemented.
|
||||||
|
func consoleAttach(auth tokenAuth, next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !consoleAttachPath.MatchString(r.URL.Path) {
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
token, found := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||||
|
if !found || !auth.valid(token) {
|
||||||
|
writeProblem(w, newProblem(http.StatusUnauthorized, api.ProblemCodeUnauthenticated, "Send a valid bearer token."))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeProblem(w, newProblem(http.StatusNotImplemented, api.ProblemCodeNotImplemented, "The console attach is not implemented yet."))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// limitBody refuses bodies above the limit before they are read.
|
||||||
|
func limitBody(limit int64, next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.ContentLength > limit {
|
||||||
|
writeProblem(w, newProblem(http.StatusRequestEntityTooLarge, api.ProblemCodePayloadTooLarge, "The request body exceeds the limit."))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r.Body = http.MaxBytesReader(w, r.Body, limit)
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func recoverPanics(logger *slog.Logger, next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ctx := r.Context()
|
||||||
|
defer func() {
|
||||||
|
if recovered := recover(); recovered != nil {
|
||||||
|
// The panic value may hold request data; only its type is logged.
|
||||||
|
logger.ErrorContext(ctx, "request panicked", slog.String("panic_type", fmt.Sprintf("%T", recovered)))
|
||||||
|
writeProblem(w, newProblem(http.StatusInternalServerError, api.ProblemCodeInternal, "The server could not complete the request."))
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// accessLog writes one line per request with the operation, status, and
|
||||||
|
// duration. Bodies, headers, and query strings are never logged.
|
||||||
|
func accessLog(router *api.Server, logger *slog.Logger, next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
started := time.Now()
|
||||||
|
recorder := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||||
|
next.ServeHTTP(recorder, r)
|
||||||
|
operation := "unknown"
|
||||||
|
if route, ok := router.FindPath(r.Method, r.URL); ok {
|
||||||
|
operation = route.OperationID()
|
||||||
|
}
|
||||||
|
logger.InfoContext(r.Context(), "request",
|
||||||
|
slog.String("method", r.Method),
|
||||||
|
slog.String("operation", operation),
|
||||||
|
slog.Int("status", recorder.status),
|
||||||
|
slog.Int64("duration_ms", time.Since(started).Milliseconds()),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type statusRecorder struct {
|
||||||
|
http.ResponseWriter
|
||||||
|
|
||||||
|
status int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *statusRecorder) WriteHeader(status int) {
|
||||||
|
r.status = status
|
||||||
|
r.ResponseWriter.WriteHeader(status)
|
||||||
|
}
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
package server_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/netip"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"lincodex/labd/internal/lxd/lxdfake"
|
||||||
|
"lincodex/labd/internal/pool"
|
||||||
|
"lincodex/labd/internal/server"
|
||||||
|
"lincodex/labd/internal/store"
|
||||||
|
"lincodex/labd/internal/template"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
serviceToken = "0123456789abcdef0123456789abcdef"
|
||||||
|
nodeMemory = 768 << 20
|
||||||
|
seedHex = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
|
||||||
|
)
|
||||||
|
|
||||||
|
type reachable struct{}
|
||||||
|
|
||||||
|
func (reachable) Probe(context.Context, netip.AddrPort) error { return nil }
|
||||||
|
|
||||||
|
func oneNodeTemplate() template.Template {
|
||||||
|
return template.Template{
|
||||||
|
ID: "ubuntu-dns", Version: 1,
|
||||||
|
Nodes: []template.Node{{Name: "srv", Kind: template.Ubuntu, Profile: "lincodex-lab-small", Source: "tpl-ubuntu/base", MemoryBytes: nodeMemory}},
|
||||||
|
Links: []template.Link{{Name: "lan", Nodes: []string{"srv"}}},
|
||||||
|
Render: func(template.Variant) (map[string]template.Bootstrap, error) {
|
||||||
|
return map[string]template.Bootstrap{}, nil
|
||||||
|
},
|
||||||
|
Check: func(context.Context, template.Variant, []template.NodeAccess) ([]template.Criterion, error) {
|
||||||
|
return []template.Criterion{{ID: "dns", Passed: true}, {ID: "zone", Passed: false}}, nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// newServer starts the API with a real manager on the fake LXD; the budget
|
||||||
|
// fits two labs.
|
||||||
|
func newServer(t *testing.T, allowed string) (*httptest.Server, *pool.Manager) {
|
||||||
|
t.Helper()
|
||||||
|
registry, err := template.NewRegistry(oneNodeTemplate())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
states, err := store.New(filepath.Join(t.TempDir(), "labs.json"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
logger := slog.New(slog.DiscardHandler)
|
||||||
|
manager, err := pool.New(pool.Config{
|
||||||
|
MemoryBudgetBytes: 2 * nodeMemory, MaxLifetime: 2 * time.Hour, ProvisionTimeout: 5 * time.Second,
|
||||||
|
ProbeInterval: time.Millisecond, DeletedRetention: time.Hour, ConsoleTokenTTL: time.Minute, CheckTimeout: time.Second,
|
||||||
|
ManagementNetwork: "lxdbr-labmgmt", ManagementPrefix: netip.MustParsePrefix("10.81.0.0/24"),
|
||||||
|
ManagementHost: netip.MustParseAddr("10.81.0.1"), ManagementFirst: netip.MustParseAddr("10.81.0.16"),
|
||||||
|
}, lxdfake.New([]string{"tpl-ubuntu/base"}, "lxdbr-labmgmt"), states, registry, reachable{}, time.Now, logger)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := manager.Start(context.Background()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = manager.Close(context.Background()) }) // Test teardown.
|
||||||
|
handler := server.NewHandler(manager, manager.Ready, 30*time.Second, logger)
|
||||||
|
httpHandler, err := server.New(handler, server.Options{
|
||||||
|
Token: serviceToken, MaxRequestBytes: 64 << 10, AllowedClients: []netip.Prefix{netip.MustParsePrefix(allowed)},
|
||||||
|
}, logger)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
httpServer := httptest.NewServer(httpHandler)
|
||||||
|
t.Cleanup(httpServer.Close)
|
||||||
|
return httpServer, manager
|
||||||
|
}
|
||||||
|
|
||||||
|
// reply is the status and headers of a response whose body was read.
|
||||||
|
type reply struct {
|
||||||
|
StatusCode int
|
||||||
|
Header http.Header
|
||||||
|
}
|
||||||
|
|
||||||
|
func call(t *testing.T, base, method, path, token string, body any) (reply, map[string]any) {
|
||||||
|
t.Helper()
|
||||||
|
var reader io.Reader = http.NoBody
|
||||||
|
if body != nil {
|
||||||
|
encoded, err := json.Marshal(body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
reader = bytes.NewReader(encoded)
|
||||||
|
}
|
||||||
|
request, err := http.NewRequestWithContext(context.Background(), method, base+path, reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if body != nil {
|
||||||
|
request.Header.Set("Content-Type", "application/json")
|
||||||
|
}
|
||||||
|
if token != "" {
|
||||||
|
request.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
}
|
||||||
|
response, err := http.DefaultClient.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer func() { _ = response.Body.Close() }()
|
||||||
|
var decoded map[string]any
|
||||||
|
_ = json.NewDecoder(response.Body).Decode(&decoded) // Some answers have no JSON body.
|
||||||
|
return reply{StatusCode: response.StatusCode, Header: response.Header}, decoded
|
||||||
|
}
|
||||||
|
|
||||||
|
func createBody(seed string) map[string]any {
|
||||||
|
return map[string]any{"template_id": "ubuntu-dns", "template_version": 1, "seed": seed, "ttl_seconds": 600}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLabOperationsNeedTheServiceToken(t *testing.T) {
|
||||||
|
httpServer, _ := newServer(t, "127.0.0.0/8")
|
||||||
|
id := uuid.NewString()
|
||||||
|
for _, token := range []string{"", "wrong-token-wrong-token-wrong-token"} {
|
||||||
|
response, body := call(t, httpServer.URL, http.MethodPut, "/v1/labs/"+id, token, createBody(seedHex))
|
||||||
|
if response.StatusCode != http.StatusUnauthorized || body["code"] != "unauthenticated" {
|
||||||
|
t.Fatalf("PUT with token %q = %d %v", token, response.StatusCode, body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
response, _ := call(t, httpServer.URL, http.MethodGet, "/healthz", "", nil)
|
||||||
|
if response.StatusCode != http.StatusOK {
|
||||||
|
t.Fatalf("healthz = %d", response.StatusCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequestsFromOtherNetworksAreRefused(t *testing.T) {
|
||||||
|
httpServer, _ := newServer(t, "172.29.79.0/24")
|
||||||
|
response, body := call(t, httpServer.URL, http.MethodGet, "/v1/labs/"+uuid.NewString(), serviceToken, nil)
|
||||||
|
if response.StatusCode != http.StatusUnauthorized || body["code"] != "unauthenticated" {
|
||||||
|
t.Fatalf("GET from loopback = %d %v", response.StatusCode, body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateIsIdempotentAndTheExtraLabIsBusy(t *testing.T) {
|
||||||
|
httpServer, manager := newServer(t, "127.0.0.0/8")
|
||||||
|
first, second := uuid.NewString(), uuid.NewString()
|
||||||
|
|
||||||
|
response, body := call(t, httpServer.URL, http.MethodPut, "/v1/labs/"+first, serviceToken, createBody(seedHex))
|
||||||
|
if response.StatusCode != http.StatusAccepted || body["state"] != "provisioning" {
|
||||||
|
t.Fatalf("first PUT = %d %v", response.StatusCode, body)
|
||||||
|
}
|
||||||
|
assertNoInfrastructure(t, body)
|
||||||
|
response, _ = call(t, httpServer.URL, http.MethodPut, "/v1/labs/"+first, serviceToken, createBody(seedHex))
|
||||||
|
if response.StatusCode != http.StatusOK {
|
||||||
|
t.Fatalf("repeated PUT = %d", response.StatusCode)
|
||||||
|
}
|
||||||
|
response, body = call(t, httpServer.URL, http.MethodPut, "/v1/labs/"+first, serviceToken, createBody(strings.Repeat("0", 63)+"1"))
|
||||||
|
if response.StatusCode != http.StatusUnprocessableEntity || body["code"] != "idempotency_key_reused" {
|
||||||
|
t.Fatalf("PUT with another seed = %d %v", response.StatusCode, body)
|
||||||
|
}
|
||||||
|
if response, _ = call(t, httpServer.URL, http.MethodPut, "/v1/labs/"+second, serviceToken, createBody(seedHex)); response.StatusCode != http.StatusAccepted {
|
||||||
|
t.Fatalf("second lab = %d", response.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
extra := uuid.NewString()
|
||||||
|
response, body = call(t, httpServer.URL, http.MethodPut, "/v1/labs/"+extra, serviceToken, createBody(seedHex))
|
||||||
|
if response.StatusCode != http.StatusServiceUnavailable || body["code"] != "lab_pool_busy" || response.Header.Get("Retry-After") != "30" {
|
||||||
|
t.Fatalf("PUT beyond the budget = %d %v Retry-After %q", response.StatusCode, body, response.Header.Get("Retry-After"))
|
||||||
|
}
|
||||||
|
response, body = call(t, httpServer.URL, http.MethodGet, "/v1/labs/"+extra, serviceToken, nil)
|
||||||
|
if response.StatusCode != http.StatusNotFound || body["code"] != "not_found" {
|
||||||
|
t.Fatalf("a busy lab was stored: %d %v", response.StatusCode, body)
|
||||||
|
}
|
||||||
|
if _, count := manager.Usage(); count != 2 {
|
||||||
|
t.Fatalf("labs holding capacity = %d, want 2", count)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReadyLabIssuesConsoleTokensAndChecks(t *testing.T) {
|
||||||
|
httpServer, manager := newServer(t, "127.0.0.0/8")
|
||||||
|
id := uuid.New()
|
||||||
|
if response, _ := call(t, httpServer.URL, http.MethodPut, "/v1/labs/"+id.String(), serviceToken, createBody(seedHex)); response.StatusCode != http.StatusAccepted {
|
||||||
|
t.Fatalf("PUT = %d", response.StatusCode)
|
||||||
|
}
|
||||||
|
deadline := time.Now().Add(5 * time.Second)
|
||||||
|
for {
|
||||||
|
record, err := manager.Get(id)
|
||||||
|
if err == nil && record.State == "ready" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatalf("lab did not become ready: %+v %v", record, err)
|
||||||
|
}
|
||||||
|
time.Sleep(2 * time.Millisecond)
|
||||||
|
}
|
||||||
|
response, body := call(t, httpServer.URL, http.MethodGet, "/v1/labs/"+id.String(), serviceToken, nil)
|
||||||
|
if response.StatusCode != http.StatusOK || body["ready_at"] == nil {
|
||||||
|
t.Fatalf("GET = %d %v", response.StatusCode, body)
|
||||||
|
}
|
||||||
|
assertNoInfrastructure(t, body)
|
||||||
|
|
||||||
|
response, body = call(t, httpServer.URL, http.MethodPost, "/v1/labs/"+id.String()+"/console-tokens", serviceToken, map[string]any{"node": "srv"})
|
||||||
|
if response.StatusCode != http.StatusCreated || response.Header.Get("Cache-Control") != "no-store" ||
|
||||||
|
body["attach_path"] != "/v1/labs/"+id.String()+"/console" || len(body["token"].(string)) != 43 {
|
||||||
|
t.Fatalf("console token = %d %v", response.StatusCode, body)
|
||||||
|
}
|
||||||
|
response, body = call(t, httpServer.URL, http.MethodPost, "/v1/labs/"+id.String()+"/console-tokens", serviceToken, map[string]any{"node": "r9"})
|
||||||
|
if response.StatusCode != http.StatusBadRequest || body["code"] != "validation_failed" {
|
||||||
|
t.Fatalf("console token for an unknown node = %d %v", response.StatusCode, body)
|
||||||
|
}
|
||||||
|
response, body = call(t, httpServer.URL, http.MethodGet, "/v1/labs/"+id.String()+"/console", serviceToken, nil)
|
||||||
|
if response.StatusCode != http.StatusNotImplemented || body["code"] != "not_implemented" {
|
||||||
|
t.Fatalf("console attach = %d %v", response.StatusCode, body)
|
||||||
|
}
|
||||||
|
if response, _ = call(t, httpServer.URL, http.MethodGet, "/v1/labs/"+id.String()+"/console", "", nil); response.StatusCode != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("console attach without a token = %d", response.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
response, body = call(t, httpServer.URL, http.MethodPost, "/v1/labs/"+id.String()+"/check", serviceToken, nil)
|
||||||
|
if response.StatusCode != http.StatusOK || body["score"] != 1.0 || body["max_score"] != 2.0 {
|
||||||
|
t.Fatalf("check = %d %v", response.StatusCode, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
response, body = call(t, httpServer.URL, http.MethodDelete, "/v1/labs/"+id.String(), serviceToken, nil)
|
||||||
|
if response.StatusCode != http.StatusAccepted || body["state"] != "deleting" {
|
||||||
|
t.Fatalf("DELETE = %d %v", response.StatusCode, body)
|
||||||
|
}
|
||||||
|
response, body = call(t, httpServer.URL, http.MethodPost, "/v1/labs/"+id.String()+"/check", serviceToken, nil)
|
||||||
|
if response.StatusCode != http.StatusConflict || body["code"] != "state_conflict" {
|
||||||
|
t.Fatalf("check of a deleting lab = %d %v", response.StatusCode, body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnknownTemplateIsAValidationFailure(t *testing.T) {
|
||||||
|
httpServer, _ := newServer(t, "127.0.0.0/8")
|
||||||
|
body := createBody(seedHex)
|
||||||
|
body["template_id"] = "mikrotik-bgp"
|
||||||
|
response, decoded := call(t, httpServer.URL, http.MethodPut, "/v1/labs/"+uuid.NewString(), serviceToken, body)
|
||||||
|
if response.StatusCode != http.StatusBadRequest || decoded["code"] != "validation_failed" {
|
||||||
|
t.Fatalf("PUT with an unknown template = %d %v", response.StatusCode, decoded)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// assertNoInfrastructure fails when a lab status names an address, an LXD
|
||||||
|
// object, or the seed.
|
||||||
|
func assertNoInfrastructure(t *testing.T, body map[string]any) {
|
||||||
|
t.Helper()
|
||||||
|
encoded, err := json.Marshal(body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
text := string(encoded)
|
||||||
|
for _, forbidden := range []string{"10.81.", "lcxl-", "lxl", "address", "instance", "bridge", seedHex} {
|
||||||
|
if strings.Contains(text, forbidden) {
|
||||||
|
t.Fatalf("lab status contains %q: %s", forbidden, text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
// Package store keeps the lab records in one JSON file.
|
||||||
|
//
|
||||||
|
// labd holds a few dozen labs at most, so the whole file is rewritten on
|
||||||
|
// every change: the new content goes to a temporary file in the same
|
||||||
|
// directory, which is synced, renamed over the old file, and followed by a
|
||||||
|
// sync of the directory. A crash leaves either the old or the new file,
|
||||||
|
// never a mix. This needs no database engine, no cgo, and no extra
|
||||||
|
// dependency, and an operator can read the file during an incident. The file
|
||||||
|
// holds variant seeds, so it is created with mode 0600 in a directory that
|
||||||
|
// only the labd user can read.
|
||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"lincodex/labd/internal/lab"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
fileVersion = 1
|
||||||
|
fileMode = 0o600
|
||||||
|
// maxFileBytes refuses a state file that cannot come from labd.
|
||||||
|
maxFileBytes = 16 << 20
|
||||||
|
)
|
||||||
|
|
||||||
|
type document struct {
|
||||||
|
Version int `json:"version"`
|
||||||
|
Labs []lab.Lab `json:"labs"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store reads and writes the state file.
|
||||||
|
type Store struct {
|
||||||
|
path string
|
||||||
|
mu sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
// New returns a store for the state file at path. The directory must exist.
|
||||||
|
func New(path string) (*Store, error) {
|
||||||
|
if !filepath.IsAbs(path) {
|
||||||
|
return nil, errors.New("store.New - the state file path must be absolute")
|
||||||
|
}
|
||||||
|
info, err := os.Stat(filepath.Dir(path))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("store.New - state directory: %w", err)
|
||||||
|
}
|
||||||
|
if !info.IsDir() {
|
||||||
|
return nil, errors.New("store.New - the parent of the state file is not a directory")
|
||||||
|
}
|
||||||
|
return &Store{path: path}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load returns the stored labs. A missing file is an empty store; a file
|
||||||
|
// that cannot be decoded is an error, because labd must not forget labs whose
|
||||||
|
// LXD objects may still exist.
|
||||||
|
func (s *Store) Load() ([]lab.Lab, error) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
content, err := os.ReadFile(s.path)
|
||||||
|
if errors.Is(err, fs.ErrNotExist) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("Store.Load - read: %w", err)
|
||||||
|
}
|
||||||
|
if len(content) > maxFileBytes {
|
||||||
|
return nil, errors.New("Store.Load - the state file is too large")
|
||||||
|
}
|
||||||
|
var decoded document
|
||||||
|
if err := json.Unmarshal(content, &decoded); err != nil {
|
||||||
|
return nil, fmt.Errorf("Store.Load - decode: %w", err)
|
||||||
|
}
|
||||||
|
if decoded.Version != fileVersion {
|
||||||
|
return nil, fmt.Errorf("Store.Load - unsupported state file version %d", decoded.Version)
|
||||||
|
}
|
||||||
|
return decoded.Labs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save replaces the stored labs atomically and durably.
|
||||||
|
func (s *Store) Save(labs []lab.Lab) error {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
if labs == nil {
|
||||||
|
labs = []lab.Lab{}
|
||||||
|
}
|
||||||
|
content, err := json.MarshalIndent(document{Version: fileVersion, Labs: labs}, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Store.Save - encode: %w", err)
|
||||||
|
}
|
||||||
|
directory := filepath.Dir(s.path)
|
||||||
|
temporary, err := os.CreateTemp(directory, ".labs-*.json")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Store.Save - create temporary file: %w", err)
|
||||||
|
}
|
||||||
|
name := temporary.Name()
|
||||||
|
committed := false
|
||||||
|
defer func() {
|
||||||
|
if !committed {
|
||||||
|
_ = temporary.Close() // Already closed on the success path.
|
||||||
|
_ = os.Remove(name) // Best effort; a stale temporary file is harmless.
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
if err := temporary.Chmod(fileMode); err != nil {
|
||||||
|
return fmt.Errorf("Store.Save - chmod: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := temporary.Write(append(content, '\n')); err != nil {
|
||||||
|
return fmt.Errorf("Store.Save - write: %w", err)
|
||||||
|
}
|
||||||
|
if err := temporary.Sync(); err != nil {
|
||||||
|
return fmt.Errorf("Store.Save - sync file: %w", err)
|
||||||
|
}
|
||||||
|
if err := temporary.Close(); err != nil {
|
||||||
|
return fmt.Errorf("Store.Save - close: %w", err)
|
||||||
|
}
|
||||||
|
if err := os.Rename(name, s.path); err != nil {
|
||||||
|
return fmt.Errorf("Store.Save - rename: %w", err)
|
||||||
|
}
|
||||||
|
committed = true
|
||||||
|
return syncDirectory(directory)
|
||||||
|
}
|
||||||
|
|
||||||
|
// syncDirectory makes the rename durable.
|
||||||
|
func syncDirectory(path string) error {
|
||||||
|
directory, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("store.syncDirectory - open: %w", err)
|
||||||
|
}
|
||||||
|
defer func() { _ = directory.Close() }() // Read-only handle.
|
||||||
|
if err := directory.Sync(); err != nil {
|
||||||
|
return fmt.Errorf("store.syncDirectory - sync: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
package store_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/netip"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"lincodex/labd/internal/lab"
|
||||||
|
"lincodex/labd/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSaveAndLoadKeepEveryField(t *testing.T) {
|
||||||
|
directory := t.TempDir()
|
||||||
|
path := filepath.Join(directory, "labs.json")
|
||||||
|
labs, err := mustStore(t, path).Load()
|
||||||
|
if err != nil || len(labs) != 0 {
|
||||||
|
t.Fatalf("Load() of a missing file = %v, %v; want empty", labs, err)
|
||||||
|
}
|
||||||
|
created := time.Date(2026, 10, 11, 9, 0, 0, 0, time.UTC)
|
||||||
|
record := lab.Lab{
|
||||||
|
ID: uuid.New(), TemplateID: "ubuntu-dns", TemplateVersion: 2, Seed: "ab", Fingerprint: "f",
|
||||||
|
State: lab.Failed, FailureReason: lab.FailureTimedOut, CreatedAt: created, ExpiresAt: created.Add(time.Hour),
|
||||||
|
MemoryBytes: 768 << 20,
|
||||||
|
Nodes: []lab.Node{{
|
||||||
|
Name: "srv", Kind: "ubuntu", Instance: "lcxl-0102030405-srv",
|
||||||
|
ManagementAddress: netip.MustParseAddr("10.81.0.16"), ManagementPort: 22,
|
||||||
|
}},
|
||||||
|
Bridges: []string{"lxl010203040500"},
|
||||||
|
}
|
||||||
|
if err := mustStore(t, path).Save([]lab.Lab{record}); err != nil {
|
||||||
|
t.Fatalf("Save() error = %v", err)
|
||||||
|
}
|
||||||
|
loaded, err := mustStore(t, path).Load()
|
||||||
|
if err != nil || len(loaded) != 1 {
|
||||||
|
t.Fatalf("Load() = %v, %v", loaded, err)
|
||||||
|
}
|
||||||
|
got := loaded[0]
|
||||||
|
if got.ID != record.ID || got.State != record.State || got.FailureReason != record.FailureReason ||
|
||||||
|
!got.ExpiresAt.Equal(record.ExpiresAt) || !got.ReadyAt.IsZero() || got.Nodes[0] != record.Nodes[0] ||
|
||||||
|
got.Bridges[0] != record.Bridges[0] || got.MemoryBytes != record.MemoryBytes {
|
||||||
|
t.Fatalf("Load() = %+v, want %+v", got, record)
|
||||||
|
}
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if mode := info.Mode().Perm(); mode != 0o600 {
|
||||||
|
t.Fatalf("state file mode = %o, want 600", mode)
|
||||||
|
}
|
||||||
|
entries, err := os.ReadDir(directory)
|
||||||
|
if err != nil || len(entries) != 1 {
|
||||||
|
t.Fatalf("directory holds %d entries, want only the state file", len(entries))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadRefusesACorruptFile(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "labs.json")
|
||||||
|
if err := os.WriteFile(path, []byte("{\"version\":1,\"labs\":["), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := mustStore(t, path).Load(); err == nil {
|
||||||
|
t.Fatal("Load() accepted a truncated file; labd would forget its labs")
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, []byte(`{"version":9,"labs":[]}`), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := mustStore(t, path).Load(); err == nil {
|
||||||
|
t.Fatal("Load() accepted an unknown version")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewRefusesARelativePath(t *testing.T) {
|
||||||
|
if _, err := store.New("labs.json"); err == nil {
|
||||||
|
t.Fatal("New() accepted a relative path")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustStore(t *testing.T, path string) *store.Store {
|
||||||
|
t.Helper()
|
||||||
|
s, err := store.New(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("New() error = %v", err)
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package template
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
type registryKey struct {
|
||||||
|
id string
|
||||||
|
version int
|
||||||
|
}
|
||||||
|
|
||||||
|
// Registry holds the templates of the labd build by ID and version.
|
||||||
|
type Registry struct {
|
||||||
|
templates map[registryKey]Template
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRegistry validates the templates and indexes them. A duplicate ID and
|
||||||
|
// version is a build error.
|
||||||
|
func NewRegistry(templates ...Template) (*Registry, error) {
|
||||||
|
registry := &Registry{templates: make(map[registryKey]Template, len(templates))}
|
||||||
|
for _, template := range templates {
|
||||||
|
if err := template.Validate(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
key := registryKey{id: template.ID, version: template.Version}
|
||||||
|
if _, duplicate := registry.templates[key]; duplicate {
|
||||||
|
return nil, fmt.Errorf("template.NewRegistry - duplicate template %s version %d", template.ID, template.Version)
|
||||||
|
}
|
||||||
|
registry.templates[key] = template
|
||||||
|
}
|
||||||
|
return registry, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lookup returns the template with the given ID and version.
|
||||||
|
func (r *Registry) Lookup(id string, version int) (Template, bool) {
|
||||||
|
template, ok := r.templates[registryKey{id: id, version: version}]
|
||||||
|
return template, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// All returns every template in no particular order.
|
||||||
|
func (r *Registry) All() []Template {
|
||||||
|
all := make([]Template, 0, len(r.templates))
|
||||||
|
for _, template := range r.templates {
|
||||||
|
all = append(all, template)
|
||||||
|
}
|
||||||
|
return all
|
||||||
|
}
|
||||||
|
|
||||||
|
// Builtin returns the templates of this build. Real templates and their
|
||||||
|
// prepared images arrive with the MikroTik and Ubuntu lab images; until then
|
||||||
|
// the registry is empty and every CreateLab answers validation_failed.
|
||||||
|
func Builtin() []Template {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package template
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// UbuntuNetworkConfig renders a cloud-init network configuration (version 2)
|
||||||
|
// for an Ubuntu node: the management NIC with its static address and no
|
||||||
|
// gateway or DNS, and every data NIC renamed to its device name without an
|
||||||
|
// address. A template adds the addresses of its variant to the data NICs
|
||||||
|
// itself. Interfaces are matched by MAC, because a VM names its NICs by PCI
|
||||||
|
// slot.
|
||||||
|
func UbuntuNetworkConfig(node PlannedNode) string {
|
||||||
|
var text strings.Builder
|
||||||
|
text.WriteString("version: 2\nethernets:\n")
|
||||||
|
fmt.Fprintf(&text, " eth0:\n match:\n macaddress: %q\n set-name: eth0\n dhcp4: false\n dhcp6: false\n accept-ra: false\n addresses:\n - %s\n",
|
||||||
|
node.ManagementMAC, node.Management.String())
|
||||||
|
for _, nic := range node.Interfaces {
|
||||||
|
fmt.Fprintf(&text, " %s:\n match:\n macaddress: %q\n set-name: %s\n dhcp4: false\n dhcp6: false\n accept-ra: false\n",
|
||||||
|
nic.Device, nic.MAC, nic.Device)
|
||||||
|
}
|
||||||
|
return text.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// RouterOSManagementScript renders the RouterOS commands that give a
|
||||||
|
// MikroTik node its management address and restrict the API services to the
|
||||||
|
// host side of the management bridge. A template appends its variant
|
||||||
|
// configuration. RouterOS matches interfaces by MAC in upper case.
|
||||||
|
func RouterOSManagementScript(node PlannedNode) string {
|
||||||
|
var text strings.Builder
|
||||||
|
fmt.Fprintf(&text, "/interface ethernet set [find mac-address=%q] name=mgmt\n", strings.ToUpper(node.ManagementMAC))
|
||||||
|
for _, nic := range node.Interfaces {
|
||||||
|
fmt.Fprintf(&text, "/interface ethernet set [find mac-address=%q] name=%s\n", strings.ToUpper(nic.MAC), nic.Device)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(&text, "/ip address add address=%s interface=mgmt comment=lincodex-management\n", node.Management.String())
|
||||||
|
host := node.ManagementHost.String() + "/32"
|
||||||
|
fmt.Fprintf(&text, "/ip service set api address=%s\n/ip service set api-ssl address=%s\n/ip service set ssh address=%s\n", host, host, host)
|
||||||
|
text.WriteString("/ip service set telnet disabled=yes\n/ip service set ftp disabled=yes\n/ip service set www disabled=yes\n/ip service set www-ssl disabled=yes\n/ip service set winbox disabled=yes\n")
|
||||||
|
return text.String()
|
||||||
|
}
|
||||||
@@ -0,0 +1,338 @@
|
|||||||
|
// Package template describes lab templates: their nodes, their L2 links,
|
||||||
|
// and the hooks that render the variant configuration of every node from a
|
||||||
|
// seed and check a variant on running nodes.
|
||||||
|
//
|
||||||
|
// A template is code in the labd build, never request data. The prepared
|
||||||
|
// base images and snapshots it names, and its real renderers and checkers,
|
||||||
|
// belong to the template itself; this package fixes the model and the
|
||||||
|
// rendering helpers.
|
||||||
|
package template
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/hmac"
|
||||||
|
"crypto/sha256"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"math/rand/v2"
|
||||||
|
"net/netip"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Kind is the guest system of a node.
|
||||||
|
type Kind string
|
||||||
|
|
||||||
|
const (
|
||||||
|
MikroTik Kind = "mikrotik"
|
||||||
|
Ubuntu Kind = "ubuntu"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Bounds of a template.
|
||||||
|
const (
|
||||||
|
MaxNodes = 8
|
||||||
|
// MaxInterfaces bounds the NICs of a node, management included, so that
|
||||||
|
// device names eth0..eth7 keep their PCI order in a VM.
|
||||||
|
MaxInterfaces = 8
|
||||||
|
MaxLinks = 16
|
||||||
|
MaxCriteria = 50
|
||||||
|
// MaxBootstrapBytes bounds each rendered cloud-init document.
|
||||||
|
MaxBootstrapBytes = 64 << 10
|
||||||
|
// SeedBytes is the size of a variant seed.
|
||||||
|
SeedBytes = 32
|
||||||
|
|
||||||
|
ubuntuManagementPort = 22
|
||||||
|
mikroTikManagementPort = 8728
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
idPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,47}$`)
|
||||||
|
nodeNamePattern = regexp.MustCompile(`^[a-z][a-z0-9-]{0,14}$`)
|
||||||
|
criterionPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,31}$`)
|
||||||
|
// sourcePattern is an LXD snapshot reference: instance/snapshot.
|
||||||
|
sourcePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}/[A-Za-z0-9][A-Za-z0-9._-]{0,62}$`)
|
||||||
|
profilePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Node is a node of a template.
|
||||||
|
type Node struct {
|
||||||
|
// Name is the name the task statement uses, such as r1.
|
||||||
|
Name string
|
||||||
|
Kind Kind
|
||||||
|
// Profile is the LXD profile with the CPU, memory, and disk limits, such
|
||||||
|
// as lincodex-lab-small.
|
||||||
|
Profile string
|
||||||
|
// Source is the prepared snapshot the node is copied from, as
|
||||||
|
// instance/snapshot. On the btrfs pool a copy is a subvolume snapshot
|
||||||
|
// and takes seconds.
|
||||||
|
Source string
|
||||||
|
// MemoryBytes is the guest memory of the profile. labd admits a lab only
|
||||||
|
// when the memory of all its nodes fits the host budget.
|
||||||
|
MemoryBytes int64
|
||||||
|
// ManagementPort is the TCP port labd probes for readiness and the
|
||||||
|
// checker uses; zero selects 22 for ubuntu and 8728 for mikrotik.
|
||||||
|
ManagementPort uint16
|
||||||
|
}
|
||||||
|
|
||||||
|
// Port returns the management port of the node.
|
||||||
|
func (n Node) Port() uint16 {
|
||||||
|
switch {
|
||||||
|
case n.ManagementPort != 0:
|
||||||
|
return n.ManagementPort
|
||||||
|
case n.Kind == MikroTik:
|
||||||
|
return mikroTikManagementPort
|
||||||
|
default:
|
||||||
|
return ubuntuManagementPort
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Link is an L2 segment between nodes. Every link becomes its own bridge
|
||||||
|
// without an address on the host, so lab traffic never reaches the host,
|
||||||
|
// another lab, or the internet.
|
||||||
|
type Link struct {
|
||||||
|
Name string
|
||||||
|
Nodes []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Interface is a data NIC of a planned node.
|
||||||
|
type Interface struct {
|
||||||
|
// Device is the LXD device and the guest interface name, eth1 and up.
|
||||||
|
Device string
|
||||||
|
// Link is the name of the template link.
|
||||||
|
Link string
|
||||||
|
MAC string
|
||||||
|
}
|
||||||
|
|
||||||
|
// PlannedNode is a node with its management address and data NICs.
|
||||||
|
type PlannedNode struct {
|
||||||
|
Name string
|
||||||
|
Kind Kind
|
||||||
|
Management netip.Prefix
|
||||||
|
ManagementHost netip.Addr
|
||||||
|
ManagementMAC string
|
||||||
|
Interfaces []Interface
|
||||||
|
}
|
||||||
|
|
||||||
|
// Variant is one lab of a template: the seed and the plan of every node.
|
||||||
|
type Variant struct {
|
||||||
|
Seed [SeedBytes]byte
|
||||||
|
Nodes []PlannedNode
|
||||||
|
}
|
||||||
|
|
||||||
|
// Node returns the planned node with the given name.
|
||||||
|
func (v Variant) Node(name string) (PlannedNode, bool) {
|
||||||
|
for _, node := range v.Nodes {
|
||||||
|
if node.Name == name {
|
||||||
|
return node, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return PlannedNode{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rand returns a deterministic random stream for one purpose of the variant,
|
||||||
|
// such as "addresses" or "faults". The same seed and label always give the
|
||||||
|
// same stream, so the renderer and the checker agree on the variant.
|
||||||
|
func (v Variant) Rand(label string) *rand.Rand {
|
||||||
|
mac := hmac.New(sha256.New, v.Seed[:])
|
||||||
|
_, _ = mac.Write([]byte(label)) // A hash never fails to write.
|
||||||
|
var key [32]byte
|
||||||
|
copy(key[:], mac.Sum(nil))
|
||||||
|
return rand.New(rand.NewChaCha8(key)) //nolint:gosec // Deterministic variant choice, not a secret.
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bootstrap is the first-boot configuration of a node. LXD passes it to the
|
||||||
|
// guest as cloud-init data; for a MikroTik node UserData holds the RouterOS
|
||||||
|
// script that the image applies on first boot.
|
||||||
|
type Bootstrap struct {
|
||||||
|
UserData string
|
||||||
|
NetworkConfig string
|
||||||
|
}
|
||||||
|
|
||||||
|
// NodeAccess is how the checker reaches a node: its management address on
|
||||||
|
// the lab management bridge. It never leaves labd.
|
||||||
|
type NodeAccess struct {
|
||||||
|
Name string
|
||||||
|
Kind Kind
|
||||||
|
Address netip.AddrPort
|
||||||
|
}
|
||||||
|
|
||||||
|
// Criterion is the result of one checker criterion.
|
||||||
|
type Criterion struct {
|
||||||
|
ID string
|
||||||
|
Passed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// RenderFunc renders the bootstrap of every node of a variant by node name.
|
||||||
|
type RenderFunc func(variant Variant) (map[string]Bootstrap, error)
|
||||||
|
|
||||||
|
// CheckFunc evaluates the criteria of a variant on running nodes. It reads
|
||||||
|
// node state only. An error means that nothing was evaluated, never a failed
|
||||||
|
// criterion.
|
||||||
|
type CheckFunc func(ctx context.Context, variant Variant, nodes []NodeAccess) ([]Criterion, error)
|
||||||
|
|
||||||
|
// Template is a lab template of one version.
|
||||||
|
type Template struct {
|
||||||
|
ID string
|
||||||
|
Version int
|
||||||
|
Nodes []Node
|
||||||
|
Links []Link
|
||||||
|
Render RenderFunc
|
||||||
|
Check CheckFunc
|
||||||
|
}
|
||||||
|
|
||||||
|
// MemoryBytes returns the memory of all nodes.
|
||||||
|
func (t Template) MemoryBytes() int64 {
|
||||||
|
var total int64
|
||||||
|
for _, node := range t.Nodes {
|
||||||
|
total += node.MemoryBytes
|
||||||
|
}
|
||||||
|
return total
|
||||||
|
}
|
||||||
|
|
||||||
|
// Node returns the node with the given name.
|
||||||
|
func (t Template) Node(name string) (Node, bool) {
|
||||||
|
for _, node := range t.Nodes {
|
||||||
|
if node.Name == name {
|
||||||
|
return node, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Node{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate reports a template that labd cannot provision.
|
||||||
|
func (t Template) Validate() error {
|
||||||
|
if !idPattern.MatchString(t.ID) || t.Version < 1 || t.Version > 10000 {
|
||||||
|
return errors.New("template.Validate - ID or version is outside the contract")
|
||||||
|
}
|
||||||
|
if t.Render == nil || t.Check == nil {
|
||||||
|
return fmt.Errorf("template.Validate - %s needs a renderer and a checker", t.ID)
|
||||||
|
}
|
||||||
|
if len(t.Nodes) < 1 || len(t.Nodes) > MaxNodes || len(t.Links) > MaxLinks {
|
||||||
|
return fmt.Errorf("template.Validate - %s must have 1 to %d nodes and at most %d links", t.ID, MaxNodes, MaxLinks)
|
||||||
|
}
|
||||||
|
if err := t.validateGraph(); err != nil {
|
||||||
|
return fmt.Errorf("template.Validate - %s: %w", t.ID, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// validateGraph checks the nodes and the links between them.
|
||||||
|
func (t Template) validateGraph() error {
|
||||||
|
nics := make(map[string]int, len(t.Nodes))
|
||||||
|
for _, node := range t.Nodes {
|
||||||
|
if err := node.validate(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, duplicate := nics[node.Name]; duplicate {
|
||||||
|
return fmt.Errorf("Template.validateGraph - duplicate node %s", node.Name)
|
||||||
|
}
|
||||||
|
// Every node starts with its management NIC.
|
||||||
|
nics[node.Name] = 1
|
||||||
|
}
|
||||||
|
links := make(map[string]struct{}, len(t.Links))
|
||||||
|
for _, link := range t.Links {
|
||||||
|
if _, duplicate := links[link.Name]; duplicate || !nodeNamePattern.MatchString(link.Name) {
|
||||||
|
return fmt.Errorf("Template.validateGraph - link names must be unique and match %s", nodeNamePattern)
|
||||||
|
}
|
||||||
|
links[link.Name] = struct{}{}
|
||||||
|
if len(link.Nodes) < 1 {
|
||||||
|
return fmt.Errorf("Template.validateGraph - link %s has no node", link.Name)
|
||||||
|
}
|
||||||
|
for _, name := range link.Nodes {
|
||||||
|
count, known := nics[name]
|
||||||
|
if !known {
|
||||||
|
return fmt.Errorf("Template.validateGraph - link %s names unknown node %s", link.Name, name)
|
||||||
|
}
|
||||||
|
if count+1 > MaxInterfaces {
|
||||||
|
return fmt.Errorf("Template.validateGraph - node %s has more than %d interfaces", name, MaxInterfaces)
|
||||||
|
}
|
||||||
|
nics[name] = count + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (n Node) validate() error {
|
||||||
|
switch {
|
||||||
|
case !nodeNamePattern.MatchString(n.Name):
|
||||||
|
return fmt.Errorf("Node.validate - node name %q must match %s", n.Name, nodeNamePattern)
|
||||||
|
case n.Kind != MikroTik && n.Kind != Ubuntu:
|
||||||
|
return fmt.Errorf("Node.validate - node %s has unknown kind %q", n.Name, n.Kind)
|
||||||
|
case !profilePattern.MatchString(n.Profile):
|
||||||
|
return fmt.Errorf("Node.validate - node %s needs an LXD profile", n.Name)
|
||||||
|
case !sourcePattern.MatchString(n.Source):
|
||||||
|
return fmt.Errorf("Node.validate - node %s needs a source snapshot as instance/snapshot", n.Name)
|
||||||
|
case n.MemoryBytes <= 0:
|
||||||
|
return fmt.Errorf("Node.validate - node %s needs its guest memory", n.Name)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Plan returns the variant of a lab: management addresses in node order and
|
||||||
|
// one data NIC per link membership, numbered from eth1 in link order. MAC
|
||||||
|
// addresses are locally administered: a management MAC encodes the unique
|
||||||
|
// management address, and a data MAC needs to be unique only inside its
|
||||||
|
// own lab bridge.
|
||||||
|
func (t Template) Plan(seed [SeedBytes]byte, addresses []netip.Addr, prefixBits int, host netip.Addr) (Variant, error) {
|
||||||
|
if len(addresses) != len(t.Nodes) {
|
||||||
|
return Variant{}, errors.New("template.Plan - one management address per node is required")
|
||||||
|
}
|
||||||
|
variant := Variant{Seed: seed, Nodes: make([]PlannedNode, 0, len(t.Nodes))}
|
||||||
|
for index, node := range t.Nodes {
|
||||||
|
address := addresses[index]
|
||||||
|
if !address.Is4() {
|
||||||
|
return Variant{}, errors.New("template.Plan - management addresses must be IPv4")
|
||||||
|
}
|
||||||
|
octets := address.As4()
|
||||||
|
variant.Nodes = append(variant.Nodes, PlannedNode{
|
||||||
|
Name: node.Name,
|
||||||
|
Kind: node.Kind,
|
||||||
|
Management: netip.PrefixFrom(address, prefixBits),
|
||||||
|
ManagementHost: host,
|
||||||
|
ManagementMAC: fmt.Sprintf("02:4c:00:%02x:%02x:%02x", octets[1], octets[2], octets[3]),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
for _, link := range t.Links {
|
||||||
|
for _, name := range link.Nodes {
|
||||||
|
for index := range variant.Nodes {
|
||||||
|
planned := &variant.Nodes[index]
|
||||||
|
if planned.Name != name {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
nic := len(planned.Interfaces) + 1
|
||||||
|
planned.Interfaces = append(planned.Interfaces, Interface{
|
||||||
|
Device: fmt.Sprintf("eth%d", nic),
|
||||||
|
Link: link.Name,
|
||||||
|
MAC: fmt.Sprintf("02:4c:01:%02x:%02x:00", index, nic),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return variant, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateCriteria reports checker output that cannot be a result.
|
||||||
|
func ValidateCriteria(criteria []Criterion) error {
|
||||||
|
if len(criteria) < 1 || len(criteria) > MaxCriteria {
|
||||||
|
return fmt.Errorf("template.ValidateCriteria - a check must have 1 to %d criteria", MaxCriteria)
|
||||||
|
}
|
||||||
|
seen := make(map[string]struct{}, len(criteria))
|
||||||
|
for _, criterion := range criteria {
|
||||||
|
if _, duplicate := seen[criterion.ID]; duplicate || !criterionPattern.MatchString(criterion.ID) {
|
||||||
|
return errors.New("template.ValidateCriteria - criterion IDs must be unique and match the contract")
|
||||||
|
}
|
||||||
|
seen[criterion.ID] = struct{}{}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateBootstrap reports a rendered bootstrap that LXD would not take.
|
||||||
|
func ValidateBootstrap(bootstrap Bootstrap) error {
|
||||||
|
if len(bootstrap.UserData) > MaxBootstrapBytes || len(bootstrap.NetworkConfig) > MaxBootstrapBytes {
|
||||||
|
return fmt.Errorf("template.ValidateBootstrap - cloud-init documents must have at most %d bytes", MaxBootstrapBytes)
|
||||||
|
}
|
||||||
|
if strings.ContainsRune(bootstrap.UserData, 0) || strings.ContainsRune(bootstrap.NetworkConfig, 0) {
|
||||||
|
return errors.New("template.ValidateBootstrap - cloud-init documents must not contain NUL")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package template_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/netip"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"lincodex/labd/internal/template"
|
||||||
|
)
|
||||||
|
|
||||||
|
func pair() template.Template {
|
||||||
|
return template.Template{
|
||||||
|
ID: "mikrotik-pair", Version: 1,
|
||||||
|
Nodes: []template.Node{
|
||||||
|
{Name: "r1", Kind: template.MikroTik, Profile: "lincodex-lab-small", Source: "tpl-chr/base", MemoryBytes: 768 << 20},
|
||||||
|
{Name: "srv", Kind: template.Ubuntu, Profile: "lincodex-lab-small", Source: "tpl-ubuntu/base", MemoryBytes: 768 << 20},
|
||||||
|
},
|
||||||
|
Links: []template.Link{{Name: "lan", Nodes: []string{"r1", "srv"}}, {Name: "wan", Nodes: []string{"r1"}}},
|
||||||
|
Render: func(template.Variant) (map[string]template.Bootstrap, error) { return nil, nil },
|
||||||
|
Check: func(context.Context, template.Variant, []template.NodeAccess) ([]template.Criterion, error) {
|
||||||
|
return nil, nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateRejectsTemplatesLabdCannotProvision(t *testing.T) {
|
||||||
|
if err := pair().Validate(); err != nil {
|
||||||
|
t.Fatalf("Validate() error = %v", err)
|
||||||
|
}
|
||||||
|
tests := map[string]func(*template.Template){
|
||||||
|
"no checker": func(t *template.Template) { t.Check = nil },
|
||||||
|
"no nodes": func(t *template.Template) { t.Nodes = nil },
|
||||||
|
"duplicate node": func(t *template.Template) { t.Nodes[1].Name = "r1" },
|
||||||
|
"unknown kind": func(t *template.Template) { t.Nodes[0].Kind = "cisco" },
|
||||||
|
"source not a snap": func(t *template.Template) { t.Nodes[0].Source = "tpl-chr" },
|
||||||
|
"no memory": func(t *template.Template) { t.Nodes[0].MemoryBytes = 0 },
|
||||||
|
"link to no node": func(t *template.Template) { t.Links[0].Nodes = []string{"r9"} },
|
||||||
|
"duplicate link": func(t *template.Template) { t.Links[1].Name = "lan" },
|
||||||
|
"too many NICs on r1": func(t *template.Template) {
|
||||||
|
for index := range 8 {
|
||||||
|
t.Links = append(t.Links, template.Link{Name: "x" + string(rune('a'+index)), Nodes: []string{"r1"}})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for name, change := range tests {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
candidate := pair()
|
||||||
|
candidate.Nodes = append([]template.Node(nil), candidate.Nodes...)
|
||||||
|
candidate.Links = append([]template.Link(nil), candidate.Links...)
|
||||||
|
change(&candidate)
|
||||||
|
if err := candidate.Validate(); err == nil {
|
||||||
|
t.Fatal("Validate() accepted the template")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if _, err := template.NewRegistry(pair(), pair()); err == nil {
|
||||||
|
t.Fatal("NewRegistry() accepted a duplicate template version")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlanNumbersInterfacesAndKeepsTheVariantStable(t *testing.T) {
|
||||||
|
addresses := []netip.Addr{netip.MustParseAddr("10.81.0.16"), netip.MustParseAddr("10.81.0.17")}
|
||||||
|
variant, err := pair().Plan([32]byte{7}, addresses, 24, netip.MustParseAddr("10.81.0.1"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r1, _ := variant.Node("r1")
|
||||||
|
srv, _ := variant.Node("srv")
|
||||||
|
if r1.Management.String() != "10.81.0.16/24" || r1.ManagementMAC != "02:4c:00:51:00:10" ||
|
||||||
|
len(r1.Interfaces) != 2 || r1.Interfaces[1].Device != "eth2" || r1.Interfaces[1].Link != "wan" ||
|
||||||
|
len(srv.Interfaces) != 1 || srv.Interfaces[0].MAC == r1.Interfaces[0].MAC {
|
||||||
|
t.Fatalf("plan: r1 %+v, srv %+v", r1, srv)
|
||||||
|
}
|
||||||
|
again, _ := pair().Plan([32]byte{7}, addresses, 24, netip.MustParseAddr("10.81.0.1"))
|
||||||
|
if variant.Rand("faults").Uint64() != again.Rand("faults").Uint64() {
|
||||||
|
t.Fatal("the same seed gave another variant")
|
||||||
|
}
|
||||||
|
other, _ := pair().Plan([32]byte{8}, addresses, 24, netip.MustParseAddr("10.81.0.1"))
|
||||||
|
if variant.Rand("faults").Uint64() == other.Rand("faults").Uint64() {
|
||||||
|
t.Fatal("another seed gave the same variant")
|
||||||
|
}
|
||||||
|
|
||||||
|
network := template.UbuntuNetworkConfig(srv)
|
||||||
|
if !strings.Contains(network, "10.81.0.17/24") || strings.Contains(network, "gateway") ||
|
||||||
|
!strings.Contains(network, `macaddress: "02:4c:00:51:00:11"`) || !strings.Contains(network, "set-name: eth1") {
|
||||||
|
t.Fatalf("network config:\n%s", network)
|
||||||
|
}
|
||||||
|
script := template.RouterOSManagementScript(r1)
|
||||||
|
if !strings.Contains(script, "address=10.81.0.16/24 interface=mgmt") || !strings.Contains(script, "api address=10.81.0.1/32") ||
|
||||||
|
!strings.Contains(script, `mac-address="02:4C:00:51:00:10"`) {
|
||||||
|
t.Fatalf("RouterOS script:\n%s", script)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateCriteria(t *testing.T) {
|
||||||
|
if err := template.ValidateCriteria([]template.Criterion{{ID: "ospf"}, {ID: "ping", Passed: true}}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, criteria := range [][]template.Criterion{nil, {{ID: "a"}, {ID: "a"}}, {{ID: "Bad ID"}}} {
|
||||||
|
if err := template.ValidateCriteria(criteria); err == nil {
|
||||||
|
t.Fatalf("ValidateCriteria(%v) accepted", criteria)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,6 +19,7 @@ GENERATED_PREFIXES = (
|
|||||||
"frontend/src/shared/api/endpoints/",
|
"frontend/src/shared/api/endpoints/",
|
||||||
"frontend/src/shared/api/schemas/",
|
"frontend/src/shared/api/schemas/",
|
||||||
"runner/internal/api/",
|
"runner/internal/api/",
|
||||||
|
"labd/internal/api/",
|
||||||
)
|
)
|
||||||
GENERATED_BASENAMES = {"wire_gen.go"}
|
GENERATED_BASENAMES = {"wire_gen.go"}
|
||||||
GENERATED_FILES = {
|
GENERATED_FILES = {
|
||||||
|
|||||||
Reference in new issue
Block a user