Compare commits

..

10 commits

Author SHA1 Message Date
ef7392f09b
labctl: dépôt autonome — module git.g3e.fr/syonad/labctl, exemple evpn-2hv, LABCTL_BIN, licence, README, CI
Some checks failed
Tests / test (push) Successful in 4m12s
Release Pipeline / set-release-target (push) Successful in 2s
Release Pipeline / upload-assets (lab-host.sh, scripts/lab-host.sh) (push) Successful in 7s
Release Pipeline / build (push) Successful in 1m31s
Release Pipeline / build (amd64, linux) (push) Successful in 0s
Release Pipeline / build (arm64, darwin) (push) Successful in 0s
Release Pipeline / checksums (push) Successful in 6s
Release Pipeline / release (push) Failing after 22s
Release Pipeline / publish (push) Failing after 0s
Signed-off-by: GnomeZworc <nicolas.boufidjeline@g3e.fr>
2026-10-12 16:33:02 +02:00
070faec37a
f-55: lab: l'outil devient labctl, noms et chemins neutres #55
Signed-off-by: GnomeZworc <nicolas.boufidjeline@g3e.fr>
2026-10-12 16:18:50 +02:00
9f1e8fb10f
f-55: lab: fichiers des nœuds sur un ISO dédié, envoi des binaires compilés en local #55
Signed-off-by: GnomeZworc <nicolas.boufidjeline@g3e.fr>
2026-10-12 15:50:54 +02:00
2cb7c05d88
f-55: lab: provision générique des nœuds, rôle host, two installé par test/e2e #55
Signed-off-by: GnomeZworc <nicolas.boufidjeline@g3e.fr>
2026-10-12 15:44:07 +02:00
01d43875fe
Merge branch 'feature-41' 2026-10-12 15:07:10 +02:00
3e71a3c14c
f-41: lab-host: une zone en erreur ne masque plus les autres #41
Signed-off-by: GnomeZworc <nicolas.boufidjeline@g3e.fr>
2026-10-12 13:05:19 +02:00
ac36868159
f-41: lab-host: offre EM-B420E-NVME, zone libre, CPU x86-64-v3 exigé #41
Signed-off-by: GnomeZworc <nicolas.boufidjeline@g3e.fr>
2026-10-11 23:41:51 +02:00
6c0e05e1e7
f-41: lab: FRR après deploy.sh puis redémarrage de l'agent, base BGP par l'agent #41
Signed-off-by: GnomeZworc <nicolas.boufidjeline@g3e.fr>
2026-10-11 23:41:49 +02:00
ee77d65f28
f-50: lab: scénarios et topologies déplacés sous test/e2e #50
Signed-off-by: GnomeZworc <nicolas.boufidjeline@g3e.fr>
2026-10-05 20:55:51 +02:00
1a645169bb
f-50: lab: scénarios E5, configuration de l'agent par hyperviseur, release 0.2.0rc003 #50
Signed-off-by: GnomeZworc <nicolas.boufidjeline@g3e.fr>
2026-10-04 20:43:53 +02:00
38 changed files with 1519 additions and 370 deletions

View file

@ -0,0 +1,43 @@
on:
workflow_call:
inputs:
tag:
required: true
type: string
goos:
required: true
type: string
goarch:
required: true
type: string
binari:
required: true
type: string
jobs:
build:
runs-on: docker
env:
RELEASE_CIBLE: ${{ inputs.tag }}
GOOS: ${{ inputs.goos }}
GOARCH: ${{ inputs.goarch }}
BINARI: ${{ inputs.binari }}
CGO_ENABLED: 0
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v5
with:
go-version: "1.25.14"
- name: Build du projet
run: |
echo "Building for ${BINARI}/${GOOS}/${GOARCH} (release: ${RELEASE_CIBLE})"
go env GOOS GOARCH
mkdir -p dist/
go build -o dist/${BINARI}_${GOOS}_${GOARCH} ./cmd/${BINARI}
echo "artifact pour ${RELEASE_CIBLE} ${BINARI} ${GOOS} ${GOARCH}" > dist/${BINARI}-${GOOS}-${GOARCH}.txt
ls -l ./dist
- name: Upload artifact
uses: actions/upload-artifact@v3
with:
name: ${{ env.BINARI }}-${{ env.RELEASE_CIBLE }}-${{ env.GOOS }}-${{ env.GOARCH }}
path: dist/${{ env.BINARI }}_${{ env.GOOS }}_${{ env.GOARCH }}

View file

@ -0,0 +1,119 @@
name: Release Pipeline
on:
push:
tags:
- '[0-9]*.[0-9]*.[0-9]*'
jobs:
set-release-target:
runs-on: docker
outputs:
release_cible: ${{ steps.setvar.outputs.release_cible }}
prerelease: ${{ steps.setvar.outputs.prerelease }}
steps:
- name: Déterminer la release cible
id: setvar
run: |
TAG="${GITHUB_REF#refs/tags/}"
# Formes acceptées, et rien d'autre :
# X.Y.Z release finale → prerelease=false, notes obligatoires
# X.Y.ZrcNNN préversion → prerelease=true, notes optionnelles
#
# Le nombre de chiffres de rc est fixé à 3 (rc016, pas rc16) pour que
# le tri lexicographique des tags suive l'ordre chronologique.
if [[ "${TAG}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]
then
PRERELEASE=false
elif [[ "${TAG}" =~ ^[0-9]+\.[0-9]+\.[0-9]+rc[0-9]{3}$ ]]
then
PRERELEASE=true
else
echo "tag hors convention : ${TAG}" >&2
echo "formes acceptées : X.Y.Z (release) ou X.Y.ZrcNNN (préversion, rc sur 3 chiffres)" >&2
exit 1
fi
echo "release_cible=${TAG}" >> $GITHUB_OUTPUT
echo "prerelease=${PRERELEASE}" >> $GITHUB_OUTPUT
- name: Afficher la variable
run: |
echo "Release cible = ${{ steps.setvar.outputs.release_cible }}"
echo "Prerelease = ${{ steps.setvar.outputs.prerelease }}"
build:
needs: [set-release-target]
strategy:
matrix:
include:
- goos: linux
goarch: amd64
- goos: darwin
goarch: arm64
uses: ./.forgejo/workflows/build.yml
with:
tag: ${{ needs.set-release-target.outputs.release_cible }}
goos: ${{ matrix.goos }}
goarch: ${{ matrix.goarch }}
binari: labctl
secrets: inherit
# Scripts publiés comme assets de release, à côté des binaires.
upload-assets:
runs-on: docker
needs: [set-release-target]
strategy:
matrix:
include:
- path: scripts/lab-host.sh
name: lab-host.sh
steps:
- uses: actions/checkout@v3
- name: Move asset
run: |
mkdir -p "dist"
cp "${{ matrix.path }}" dist/
- name: Upload asset
uses: actions/upload-artifact@v3
with:
name: ${{ matrix.name }}-${{ needs.set-release-target.outputs.release_cible }}
path: dist/${{ matrix.name }}
# Manifeste des sommes de contrôle de tous les artefacts, au format sha256sum.
# Dépend de tous les jobs qui produisent des artefacts : ajouter un producteur
# sans l'ajouter ici donnerait un manifeste incomplet, donc une vérification qui
# refuse des assets légitimes.
checksums:
runs-on: docker
needs: [set-release-target, build, upload-assets]
steps:
- name: Download all artifacts
uses: actions/download-artifact@v3
with:
path: artifacts/
- name: Générer SHA256SUMS
run: |
mkdir -p dist
# download-artifact place chaque artefact dans son propre
# sous-répertoire : on aplatit pour que le manifeste porte les noms
# d'assets, tels qu'on les télécharge.
find artifacts/ -type f -exec cp {} dist/ \;
# Généré depuis dist/ pour que les noms soient nus, et hors de dist/
# pour que le manifeste ne se liste pas lui-même.
( cd dist && sha256sum * ) > SHA256SUMS
cat SHA256SUMS
- name: Upload SHA256SUMS
uses: actions/upload-artifact@v3
with:
name: SHA256SUMS-${{ needs.set-release-target.outputs.release_cible }}
path: SHA256SUMS
publish:
# Tous les producteurs d'artefacts sont dans les needs : sans ça, le job
# release peut appeler download-artifact avant la fin des uploads et publier
# une release incomplète (assets ou manifeste manquants de façon non
# déterministe).
needs: [set-release-target, build, upload-assets, checksums]
uses: ./.forgejo/workflows/release.yml
with:
tag: ${{ needs.set-release-target.outputs.release_cible }}
prerelease: ${{ needs.set-release-target.outputs.prerelease }}
secrets: inherit

View file

@ -0,0 +1,112 @@
on:
workflow_call:
inputs:
tag:
required: true
type: string
prerelease:
required: true
type: string
jobs:
release:
runs-on: docker
env:
TOKEN: ${{ secrets.RELEASE }}
TAG: ${{ inputs.tag }}
PRERELEASE: ${{ inputs.prerelease }}
steps:
- uses: actions/checkout@v3
- name: Download all build artifacts
uses: actions/download-artifact@v3
with:
path: dist/
- name: Publier tous les binaires
run: ls -lR dist/
- name: Install jq
run: |
apt-get update
apt-get install -y jq
- name: Préparer les notes de version
run: |
NOTES="release_notes/${TAG}.md"
# Titre par défaut : le tag seul. Un H1 en première ligne des notes le
# remplace par « <tag> — <nom de version> ».
RELEASE_NAME="${TAG}"
if [[ -f "${NOTES}" ]]
then
echo "notes trouvées : ${NOTES}"
FIRST_LINE=$(head -1 "${NOTES}")
if [[ "${FIRST_LINE}" =~ ^\#[[:space:]]+(.+)$ ]]
then
RELEASE_NAME="${TAG} — ${BASH_REMATCH[1]}"
# H1 retiré du corps : Forgejo affiche déjà le titre au-dessus, le
# garder l'afficherait deux fois. `/./,$!d` mange les lignes vides
# laissées en tête.
tail -n +2 "${NOTES}" | sed '/./,$!d' > body.md
else
cp "${NOTES}" body.md
fi
elif [[ "${PRERELEASE}" == "true" ]]
then
echo "aucune note pour ${TAG}, texte générique (préversion)"
echo "Prerelease automatique générée par la CI" > body.md
else
echo "release finale ${TAG} sans notes de version" >&2
echo "créer ${NOTES} avant de pousser le tag" >&2
exit 1
fi
echo "RELEASE_NAME=${RELEASE_NAME}" >> "${GITHUB_ENV}"
echo "--- titre --- ${RELEASE_NAME}"
echo "--- body ---"; cat body.md
- name: Create release
run: |
jq -n \
--arg tag "${TAG}" \
--arg name "${RELEASE_NAME}" \
--rawfile body body.md \
--argjson prerelease "${PRERELEASE}" \
'{
tag_name: $tag,
name: $name,
body: $body,
draft: false,
prerelease: $prerelease,
hide_archive_links: true
}' > payload.json
cat payload.json | jq -c '.body |= (.[0:60] + "…")'
# Code HTTP vérifié explicitement plutôt qu'avec --fail-with-body, qui
# exige curl >= 7.76 : sans ça un échec (409 tag déjà publié, 401 token
# invalide) passerait inaperçu et la release resterait sans assets.
HTTP=$(curl -sS -o resp.json -w '%{http_code}' -X POST \
-H "Authorization: token ${TOKEN}" \
-H "Content-Type: application/json" \
"https://git.g3e.fr/api/v1/repos/${{ github.repository }}/releases" \
-d @payload.json)
echo "HTTP ${HTTP}"
cat resp.json; echo
[[ "${HTTP}" == 2* ]] || { echo "création de la release échouée" >&2; exit 1; }
- name: Upload asset
run: |
RELEASE_ID=$(curl -s \
-H "Authorization: token ${TOKEN}" \
https://git.g3e.fr/api/v1/repos/${{ github.repository }}/releases/tags/${TAG} \
| jq -r .id)
echo ${RELEASE_ID}
# Sans ce garde-fou, un id absent (null) enverrait chaque asset sur
# .../releases/null/assets : une cascade de 404 silencieux et une
# release publiée sans aucun binaire.
[[ "${RELEASE_ID}" =~ ^[0-9]+$ ]] || { echo "id de release introuvable pour ${TAG}" >&2; exit 1; }
ls dist | while read tmp
do
FILE=$(ls "./dist/${tmp}")
echo ${FILE}
curl -X POST \
-H "Authorization: token ${TOKEN}" \
-H "Content-Type: application/octet-stream" \
--data-binary @dist/${tmp}/${FILE} \
"https://git.g3e.fr/api/v1/repos/${{ github.repository }}/releases/${RELEASE_ID}/assets?name=${FILE}"
done

View file

@ -0,0 +1,25 @@
name: Tests
on:
push:
branches: ['**']
pull_request:
jobs:
test:
runs-on: docker
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v5
with:
go-version: "1.25.14"
- name: Outils des tests de lab-host.sh
run: |
apt-get update
apt-get install -y jq python3
- name: go vet
run: go vet ./...
- name: go test
run: go test ./...
- name: lab-host.sh
run: bash scripts/lab-host_test.sh

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
/dist/
/labctl

131
LICENSE Normal file
View file

@ -0,0 +1,131 @@
# PolyForm Noncommercial License 1.0.0
<https://polyformproject.org/licenses/noncommercial/1.0.0>
## Acceptance
In order to get any license under these terms, you must agree
to them as both strict obligations and conditions to all
your licenses.
## Copyright License
The licensor grants you a copyright license for the
software to do everything you might do with the software
that would otherwise infringe the licensor's copyright
in it for any permitted purpose. However, you may
only distribute the software according to [Distribution
License](#distribution-license) and make changes or new works
based on the software according to [Changes and New Works
License](#changes-and-new-works-license).
## Distribution License
The licensor grants you an additional copyright license
to distribute copies of the software. Your license
to distribute covers distributing the software with
changes and new works permitted by [Changes and New Works
License](#changes-and-new-works-license).
## Notices
You must ensure that anyone who gets a copy of any part of
the software from you also gets a copy of these terms or the
URL for them above, as well as copies of any plain-text lines
beginning with `Required Notice:` that the licensor provided
with the software. For example:
> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
## Changes and New Works License
The licensor grants you an additional copyright license to
make changes and new works based on the software for any
permitted purpose.
## Patent License
The licensor grants you a patent license for the software that
covers patent claims the licensor can license, or becomes able
to license, that you would infringe by using the software.
## Noncommercial Purposes
Any noncommercial purpose is a permitted purpose.
## Personal Uses
Personal use for research, experiment, and testing for
the benefit of public knowledge, personal study, private
entertainment, hobby projects, amateur pursuits, or religious
observance, without any anticipated commercial application,
is use for a permitted purpose.
## Noncommercial Organizations
Use by any charitable organization, educational institution,
public research organization, public safety or health
organization, environmental protection organization,
or government institution is use for a permitted purpose
regardless of the source of funding or obligations resulting
from the funding.
## Fair Use
You may have "fair use" rights for the software under the
law. These terms do not limit them.
## No Other Rights
These terms do not allow you to sublicense or transfer any of
your licenses to anyone else, or prevent the licensor from
granting licenses to anyone else. These terms do not imply
any other licenses.
## Patent Defense
If you make any written claim that the software infringes or
contributes to infringement of any patent, your patent license
for the software granted under these terms ends immediately. If
your company makes such a claim, your patent license ends
immediately for work on behalf of your company.
## Violations
The first time you are notified in writing that you have
violated any of these terms, or done anything with the software
not covered by your licenses, your licenses can nonetheless
continue if you come into full compliance with these terms,
and take practical steps to correct past violations, within
32 days of receiving notice. Otherwise, all your licenses
end immediately.
## No Liability
***As far as the law allows, the software comes as is, without
any warranty or condition, and the licensor will not be liable
to you for any damages arising out of these terms or the use
or nature of the software, under any kind of legal claim.***
## Definitions
The **licensor** is the individual or entity offering these
terms, and the **software** is the software the licensor makes
available under these terms.
**You** refers to the individual or entity agreeing to these
terms.
**Your company** is any legal entity, sole proprietorship,
or other kind of organization that you work for, plus all
organizations that have control over, are under the control of,
or are under common control with that organization. **Control**
means ownership of substantially all the assets of an entity,
or the power to direct its management and policies by vote,
contract, or otherwise. Control can be direct or indirect.
**Your licenses** are all the licenses granted to you for the
software under these terms.
**Use** means anything you do with the software requiring one
of your licenses.

106
README.md Normal file
View file

@ -0,0 +1,106 @@
# labctl
Monte un **lab réseau virtuel** à partir d'une topologie YAML : des VM QEMU/KVM reliées par des
segments L2, des switchs qui font passerelle et NAT, FRR installé et configuré sur les nœuds qui
le demandent, et une provision libre (scripts, fichiers, services à vérifier) pour installer ce
que l'on veut tester. Le plan est **déterministe** : même fichier, mêmes adresses, MAC et ports.
`labctl` tourne sur tout hôte Linux avec KVM (virtualisation imbriquée si l'hôte est lui-même une
VM). `scripts/lab-host.sh` loue et prépare un tel hôte à l'heure chez Scaleway (Elastic Metal) ;
c'est un exemple de fournisseur, pas une dépendance.
## Installer
Depuis une release : télécharger `labctl_linux_amd64` (et `lab-host.sh` si besoin) **et vérifier**
leur somme dans `SHA256SUMS`. Ou compiler :
```
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o labctl ./cmd/labctl
```
Sur l'hôte : `qemu-system-x86_64`, `qemu-img`, `genisoimage`, `ssh-keygen`, et `/dev/kvm`.
## Commandes
```
labctl plan <topologie.yml> valide et affiche le plan, sans rien lancer
labctl render -key <clé.pub> <topologie.yml> <rép> écrit les arguments QEMU et les seeds cloud-init
labctl up [-run rép] [-cache rép] [-timeout durée] <topologie.yml>
labctl status | down | ssh <nœud> [commande] [-run rép]
```
Par défaut : `-run ~/lab-run`, `-cache ~/.cache/labctl`, `-timeout 20m`. `up` télécharge et vérifie
les images (`SHA512SUMS`), crée des disques neufs, démarre les nœuds (switchs d'abord), attend la
fin de cloud-init puis vérifie les services de chaque nœud. Un fichier invalide est refusé avec
toutes ses erreurs et un code de sortie 1.
## Topologie
Voir `examples/evpn-2hv/` : un switch, un route reflector et deux hôtes en EVPN.
- `images` : `url` et `sums` (HTTPS).
- `segments` : `switch`, `cidr` IPv4 (/8 à /30), `mtu` (9000 par défaut). Nom ≤ 12 caractères.
- `nodes` : `role` (`switch`, `rr` ou `host`), `image`, `cpus`, `memory` (Mio), `segments`,
`addresses` (adresse fixée par segment). Champs facultatifs :
- `secondary` — adresses supplémentaires hors du CIDR du segment ;
- `loopback` — adresse sur une interface `dummy` `lo1` ;
- `frr` — un `frr.conf` déposé tel quel ; FRR est installé au premier démarrage (`bgpd`, et
`bfdd` sur `switch` et `rr`) ;
- `provision` / `post_provision` — scripts exécutés **avant** / **après** FRR ;
- `files` — `{<nom>: <chemin>}`, fichiers **ou répertoires** gravés dans un ISO propre au nœud et
recopiés dans `/etc/lab/files/<nom>` avant les scripts (aucune limite de taille cloud-init) ;
- `services` — unités systemd que `up` vérifie actives.
Les chemins sont relatifs au fichier de topologie. Les scripts reçoivent `LAB_NODE`,
`LAB_UPLINK` (interface du premier segment, qui porte la route par défaut) et `LAB_FILES`.
Ordre au premier démarrage : script du switch ou de la loopback, `provision`, FRR,
`post_provision` — dans un seul script en `set -eu`, la première étape en échec met cloud-init en
erreur.
Déduit de façon déterministe : passerelle d'un segment = première adresse (portée par le switch) ;
adresses suivantes dans l'ordre de déclaration des nœuds ; MAC `02:4c:<nœud>:<nœud>:<segment>:<côté>` ;
SSH d'administration sur `127.0.0.1:<2200 + rang>`. **Réordonner les nœuds change les adresses.**
## Hôte loué chez Scaleway : `scripts/lab-host.sh`
```
lab-host.sh plan | up | status | ssh [cmd] | prepare | push <topologie> | down | session [cmd]
```
`plan` et `status` sont gratuits ; `up` et `session` **créent un serveur facturé à l'heure**
(chaque heure entamée est due). Toujours commencer par `plan`. `push` dépose `labctl` (compilé
depuis ce dépôt, ou celui de `LABCTL_BIN`) et le répertoire de la topologie ; ensuite
`lab-host.sh ssh './labctl up topology/<topologie>'`.
Prérequis : un projet Scaleway **dédié** (`down` supprime tous les serveurs portant le tag
`labctl`), une clé d'API limitée à ce projet, des clés SSH publiques enregistrées dans le projet.
Fichiers locaux : `~/.config/labctl/scaleway.env` (0600, `SCW_SECRET_KEY`,
`SCW_DEFAULT_PROJECT_ID`), `~/.config/labctl/ssh/lab_ed25519` (clé dédiée facultative), état sous
`~/.cache/labctl/`. Tout se surcharge par variable d'environnement (`lab-host.sh` sans argument).
Garanties : jamais d'offre mensuelle ni de frais de mise en service, pas de second serveur,
suppression réessayée et vérifiée jusqu'au 404, échec signalé par `SERVEUR(S) DE LAB TOUJOURS
FACTURÉ(S)`. Pas de garantie face à un `SIGKILL` ou une coupure du poste : en cas de doute,
`status` puis `down`.
## Sécurité
- La clé secrète Scaleway n'apparaît ni dans les arguments de processus, ni dans les journaux, ni
dans l'environnement de `ssh`. **Ne jamais lancer `lab-host.sh` sous `bash -x`.**
- La clé SSH des VM est générée sur l'hôte et ne le quitte pas ; les VM n'écoutent qu'en boucle
locale. Leurs clés d'hôte ne sont pas vérifiées (`known_hosts` jetable).
- Les images sont vérifiées par `SHA512SUMS`, servi par la même origine : cela protège de la
corruption, pas d'une origine compromise.
## Tests
```
go test ./...
bash scripts/lab-host_test.sh
```
Sans réseau : `curl` et `ssh` sont remplacés par de faux clients (API Scaleway dans le pire cas).
## Licence
PolyForm Noncommercial 1.0.0 — voir `LICENSE`.

View file

@ -13,8 +13,8 @@ import (
"syscall"
"time"
"git.g3e.fr/syonad/two/internal/lab/machine"
"git.g3e.fr/syonad/two/internal/lab/provision"
"git.g3e.fr/syonad/labctl/internal/machine"
"git.g3e.fr/syonad/labctl/internal/provision"
)
const (
@ -46,7 +46,7 @@ func flags(name string, stderr io.Writer) (*flag.FlagSet, *string) {
func lab(runDir string, plan string, stdout, stderr io.Writer) (machine.Lab, bool) {
dir, err := filepath.Abs(runDir)
if err != nil {
fmt.Fprintf(stderr, "lab: %v\n", err)
fmt.Fprintf(stderr, "labctl: %v\n", err)
return machine.Lab{}, false
}
p, ok := load(plan, stderr)
@ -67,7 +67,7 @@ func lab(runDir string, plan string, stdout, stderr io.Writer) (machine.Lab, boo
func current(runDir string, stdout, stderr io.Writer) (machine.Lab, bool) {
saved := filepath.Join(runDir, topologyFile)
if _, err := os.Stat(saved); err != nil {
fmt.Fprintf(stderr, "lab: no lab in %s: %v\n", runDir, err)
fmt.Fprintf(stderr, "labctl: no lab in %s: %v\n", runDir, err)
return machine.Lab{}, false
}
return lab(runDir, saved, stdout, stderr)
@ -75,7 +75,7 @@ func current(runDir string, stdout, stderr io.Writer) (machine.Lab, bool) {
func upCmd(args []string, stdout, stderr io.Writer) int {
fs, runDir := flags("up", stderr)
cacheDir := fs.String("cache", defaultDir(".cache", "two-lab"), "image cache directory")
cacheDir := fs.String("cache", defaultDir(".cache", "labctl"), "image cache directory")
timeout := fs.Duration("timeout", 20*time.Minute, "how long to wait for the nodes to be ready")
if err := fs.Parse(args); err != nil || fs.NArg() != 1 {
fs.Usage()
@ -83,7 +83,7 @@ func upCmd(args []string, stdout, stderr io.Writer) int {
}
cache, err := filepath.Abs(*cacheDir)
if err != nil {
fmt.Fprintf(stderr, "lab: %v\n", err)
fmt.Fprintf(stderr, "labctl: %v\n", err)
return 1
}
@ -94,11 +94,11 @@ func upCmd(args []string, stdout, stderr io.Writer) int {
}
running, err := previous.Running()
if err != nil {
fmt.Fprintf(stderr, "lab: %v\n", err)
fmt.Fprintf(stderr, "labctl: %v\n", err)
return 1
}
if len(running) > 0 {
fmt.Fprintf(stderr, "lab: lab %s is still running in %s: 'lab down' first\n", previous.Plan.Name, previous.RunDir)
fmt.Fprintf(stderr, "labctl: lab %s is still running in %s: 'lab down' first\n", previous.Plan.Name, previous.RunDir)
return 1
}
}
@ -109,15 +109,15 @@ func upCmd(args []string, stdout, stderr io.Writer) int {
}
source, err := os.ReadFile(fs.Arg(0))
if err != nil {
fmt.Fprintf(stderr, "lab: %v\n", err)
fmt.Fprintf(stderr, "labctl: %v\n", err)
return 1
}
if err := os.MkdirAll(l.RunDir, 0o700); err != nil {
fmt.Fprintf(stderr, "lab: %v\n", err)
fmt.Fprintf(stderr, "labctl: %v\n", err)
return 1
}
if err := os.WriteFile(filepath.Join(l.RunDir, topologyFile), source, 0o600); err != nil {
fmt.Fprintf(stderr, "lab: %v\n", err)
fmt.Fprintf(stderr, "labctl: %v\n", err)
return 1
}
@ -125,7 +125,7 @@ func upCmd(args []string, stdout, stderr io.Writer) int {
defer stop()
fetcher := provision.Fetcher{Client: &http.Client{}, CacheDir: cache}
if err := l.Up(ctx, fetcher, *timeout); err != nil {
fmt.Fprintf(stderr, "lab: %v\nlab: started nodes keep running: 'lab status', 'lab down'\n", err)
fmt.Fprintf(stderr, "labctl: %v\nlab: started nodes keep running: 'lab status', 'lab down'\n", err)
return 1
}
return 0
@ -142,7 +142,7 @@ func statusCmd(args []string, stdout, stderr io.Writer) int {
return 1
}
if err := l.Status(stdout); err != nil {
fmt.Fprintf(stderr, "lab: %v\n", err)
fmt.Fprintf(stderr, "labctl: %v\n", err)
return 1
}
return 0
@ -159,7 +159,7 @@ func downCmd(args []string, stdout, stderr io.Writer) int {
return 1
}
if err := l.Down(context.Background()); err != nil {
fmt.Fprintf(stderr, "lab: %v\n", err)
fmt.Fprintf(stderr, "labctl: %v\n", err)
return 1
}
return 0
@ -177,16 +177,16 @@ func sshCmd(args []string, stdout, stderr io.Writer) int {
}
argv, err := l.SSH(fs.Arg(0), isTerminal(os.Stdin), fs.Args()[1:])
if err != nil {
fmt.Fprintf(stderr, "lab: %v\n", err)
fmt.Fprintf(stderr, "labctl: %v\n", err)
return 1
}
path, err := exec.LookPath(argv[0])
if err != nil {
fmt.Fprintf(stderr, "lab: %v\n", err)
fmt.Fprintf(stderr, "labctl: %v\n", err)
return 1
}
if err := execve(path, argv, os.Environ()); err != nil {
fmt.Fprintf(stderr, "lab: %v\n", err)
fmt.Fprintf(stderr, "labctl: %v\n", err)
return 1
}
return 0

View file

@ -8,12 +8,12 @@ import (
"path/filepath"
"strings"
"git.g3e.fr/syonad/two/internal/lab/provision"
"git.g3e.fr/syonad/two/internal/lab/render"
"git.g3e.fr/syonad/two/internal/lab/topology"
"git.g3e.fr/syonad/labctl/internal/provision"
"git.g3e.fr/syonad/labctl/internal/render"
"git.g3e.fr/syonad/labctl/internal/topology"
)
const usage = `usage: lab <command> [options] <topology.yml> [dir]
const usage = `usage: labctl <command> [options] <topology.yml> [dir]
plan <topology.yml>
validate the topology and print the deterministic plan: addresses, cables, ports
@ -36,7 +36,7 @@ const usage = `usage: lab <command> [options] <topology.yml> [dir]
ssh [-run dir] <node> [command...]
open a shell on a node, or run a command on it, with the key generated by up
defaults: -run $HOME/lab-run, -cache $HOME/.cache/two-lab, -timeout 20m
defaults: -run $HOME/lab-run, -cache $HOME/.cache/labctl, -timeout 20m
`
type keyFiles []string
@ -79,12 +79,12 @@ func run(args []string, stdout, stderr io.Writer) int {
func load(path string, stderr io.Writer) (*topology.Plan, bool) {
t, err := topology.Load(path)
if err != nil {
fmt.Fprintf(stderr, "lab: %v\n", err)
fmt.Fprintf(stderr, "labctl: %v\n", err)
return nil, false
}
p, err := topology.Compute(t)
if err != nil {
fmt.Fprintf(stderr, "lab: %s:\n%v\n", path, err)
fmt.Fprintf(stderr, "labctl: %s:\n%v\n", path, err)
return nil, false
}
return p, true
@ -96,7 +96,7 @@ func plan(path string, stdout, stderr io.Writer) int {
return 1
}
if err := p.Write(stdout); err != nil {
fmt.Fprintf(stderr, "lab: %v\n", err)
fmt.Fprintf(stderr, "labctl: %v\n", err)
return 1
}
return 0
@ -122,27 +122,27 @@ func renderCmd(args []string, stdout, stderr io.Writer) int {
}
dir, err := filepath.Abs(fs.Arg(1))
if err != nil {
fmt.Fprintf(stderr, "lab: %v\n", err)
fmt.Fprintf(stderr, "labctl: %v\n", err)
return 1
}
authorized, err := readKeys(keys)
if err != nil {
fmt.Fprintf(stderr, "lab: %v\n", err)
fmt.Fprintf(stderr, "labctl: %v\n", err)
return 1
}
frr, err := provision.ReadFRR(p)
if err != nil {
fmt.Fprintf(stderr, "lab: %v\n", err)
opts := render.Options{RunDir: dir, AuthorizedKeys: authorized}
if err := provision.ReadInputs(p, &opts); err != nil {
fmt.Fprintf(stderr, "labctl: %v\n", err)
return 1
}
nodes, err := render.Render(p, render.Options{RunDir: dir, AuthorizedKeys: authorized, FRR: frr})
nodes, err := render.Render(p, opts)
if err != nil {
fmt.Fprintf(stderr, "lab: %v\n", err)
fmt.Fprintf(stderr, "labctl: %v\n", err)
return 1
}
for _, n := range nodes {
if err := provision.WriteFiles(n); err != nil {
fmt.Fprintf(stderr, "lab: %v\n", err)
fmt.Fprintf(stderr, "labctl: %v\n", err)
return 1
}
fmt.Fprintf(stdout, "%s\n", n.Dir)

View file

@ -27,7 +27,7 @@ func TestRun_UsageOnMissingArguments(t *testing.T) {
}
func TestRun_PlanOfTheShippedExampleTopology(t *testing.T) {
code, stdout, stderr := runLab("plan", filepath.Join("..", "..", "conf", "lab", "evpn-2hv.yml"))
code, stdout, stderr := runLab("plan", filepath.Join("..", "..", "examples", "evpn-2hv", "topology.yml"))
if code != 0 {
t.Fatalf("code %d, stderr %s", code, stderr)
}
@ -78,11 +78,11 @@ func TestRun_MissingFile(t *testing.T) {
func TestRun_RenderWritesEveryNodeFiles(t *testing.T) {
dir := t.TempDir()
key := filepath.Join(dir, "lab.pub")
if err := os.WriteFile(key, []byte("# lab key\n\nssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFG/JMmjfko96WkJV8DiL6rip/H/q/R++y8s27Z+Cj6O two-lab-automation\n"), 0o600); err != nil {
if err := os.WriteFile(key, []byte("# lab key\n\nssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFG/JMmjfko96WkJV8DiL6rip/H/q/R++y8s27Z+Cj6O lab-automation\n"), 0o600); err != nil {
t.Fatal(err)
}
out := filepath.Join(dir, "run")
code, stdout, stderr := runLab("render", "-key", key, filepath.Join("..", "..", "conf", "lab", "evpn-2hv.yml"), out)
code, stdout, stderr := runLab("render", "-key", key, filepath.Join("..", "..", "examples", "evpn-2hv", "topology.yml"), out)
if code != 0 {
t.Fatalf("code %d, stderr %s", code, stderr)
}
@ -112,13 +112,13 @@ func TestRun_RenderWritesEveryNodeFiles(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(userData), "two-lab-automation") || strings.Contains(string(userData), "# lab key") {
if !strings.Contains(string(userData), "lab-automation") || strings.Contains(string(userData), "# lab key") {
t.Errorf("keys not read as an authorized_keys file:\n%s", userData)
}
}
func TestRun_RenderRefusesMissingKeyFile(t *testing.T) {
code, _, stderr := runLab("render", "-key", filepath.Join(t.TempDir(), "absent.pub"), filepath.Join("..", "..", "conf", "lab", "evpn-2hv.yml"), t.TempDir())
code, _, stderr := runLab("render", "-key", filepath.Join(t.TempDir(), "absent.pub"), filepath.Join("..", "..", "examples", "evpn-2hv", "topology.yml"), t.TempDir())
if code != 1 || !strings.Contains(stderr, "absent.pub") {
t.Errorf("code %d, stderr %q", code, stderr)
}
@ -130,7 +130,7 @@ func savedLab(t *testing.T) string {
if err := os.MkdirAll(run, 0o700); err != nil {
t.Fatal(err)
}
example, err := os.ReadFile(filepath.Join("..", "..", "conf", "lab", "evpn-2hv.yml"))
example, err := os.ReadFile(filepath.Join("..", "..", "examples", "evpn-2hv", "topology.yml"))
if err != nil {
t.Fatal(err)
}
@ -157,7 +157,7 @@ func TestRun_CommandsWithoutALabInTheRunDir(t *testing.T) {
args = append(args, "hv1")
}
code, _, stderr := runLab(args...)
if code != 1 || !strings.Contains(stderr, "lab: no lab in "+run) {
if code != 1 || !strings.Contains(stderr, "labctl: no lab in "+run) {
t.Errorf("%s: code %d, stderr %q", cmd, code, stderr)
}
}
@ -168,8 +168,8 @@ func TestRun_StatusOfAStoppedLab(t *testing.T) {
want := `node role state pid ssh
sw1 switch stopped - 127.0.0.1:2200
rr1 rr stopped - 127.0.0.1:2201
hv1 hypervisor stopped - 127.0.0.1:2202
hv2 hypervisor stopped - 127.0.0.1:2203
hv1 host stopped - 127.0.0.1:2202
hv2 host stopped - 127.0.0.1:2203
`
if code != 0 || stdout != want {
t.Errorf("code %d, stderr %q, stdout:\n%s", code, stderr, stdout)
@ -304,29 +304,49 @@ func TestRun_UpRefusesToReplaceARunningLab(t *testing.T) {
func TestRun_RenderShipsTheExampleFRRConfigs(t *testing.T) {
dir := t.TempDir()
key := filepath.Join(dir, "lab.pub")
if err := os.WriteFile(key, []byte("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFG/JMmjfko96WkJV8DiL6rip/H/q/R++y8s27Z+Cj6O two-lab-automation\n"), 0o600); err != nil {
if err := os.WriteFile(key, []byte("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFG/JMmjfko96WkJV8DiL6rip/H/q/R++y8s27Z+Cj6O lab-automation\n"), 0o600); err != nil {
t.Fatal(err)
}
out := filepath.Join(dir, "run")
code, _, stderr := runLab("render", "-key", key, filepath.Join("..", "..", "conf", "lab", "evpn-2hv.yml"), out)
code, _, stderr := runLab("render", "-key", key, filepath.Join("..", "..", "examples", "evpn-2hv", "topology.yml"), out)
if code != 0 {
t.Fatalf("code %d, stderr %s", code, stderr)
}
for node, want := range map[string]string{
"sw1": "router bgp 65100",
"rr1": "bgp listen range 192.168.14.0/24 peer-group fabric",
"hv1": "bgp router-id 192.168.14.11",
"hv2": "bgp router-id 192.168.14.12",
for node, wants := range map[string][]string{
"sw1": {"router bgp 65100"},
"rr1": {"bgp listen range 192.168.14.0/24 peer-group fabric"},
"hv1": {"hostname hv1", "neighbor 10.255.255.1 peer-group fabric"},
"hv2": {"hostname hv2", "neighbor 10.255.255.1 peer-group fabric"},
} {
data, err := os.ReadFile(filepath.Join(out, node, "user-data"))
if err != nil {
t.Fatal(err)
}
for _, want := range wants {
if !strings.Contains(string(data), want) {
t.Errorf("%s user-data does not carry %q", node, want)
}
}
}
for _, node := range []string{"hv1", "hv2"} {
data, err := os.ReadFile(filepath.Join(out, node, "user-data"))
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(data), "mount -o ro LABEL=LABFILES /run/lab-files") {
t.Errorf("%s user-data does not mount its files", node)
}
}
for _, node := range []string{"hv1", "hv2"} {
data, err := os.ReadFile(filepath.Join(out, node, "user-data"))
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(data), "LAB_NODE="+node+" LAB_UPLINK=underlay LAB_FILES=/etc/lab/files /usr/local/sbin/lab-node-provision") {
t.Errorf("%s user-data does not run the example provision", node)
}
}
}
func TestRun_RenderReportsAMissingFRRConfig(t *testing.T) {
dir := t.TempDir()
@ -342,7 +362,7 @@ segments:
underlay: { switch: sw1, cidr: 10.1.0.0/24 }
nodes:
sw1: { role: switch, image: deb, cpus: 1, memory: 512, frr: frr/absent.conf }
hv1: { role: hypervisor, image: deb, cpus: 1, memory: 512, segments: [underlay], release: 0.2.0rc002 }
hv1: { role: host, image: deb, cpus: 1, memory: 512, segments: [underlay] }
`
if err := os.WriteFile(topo, []byte(doc), 0o600); err != nil {
t.Fatal(err)

View file

@ -0,0 +1,18 @@
frr defaults traditional
hostname hv1
log syslog informational
!
router bgp 64600
bgp router-id 192.168.14.11
no bgp default ipv4-unicast
neighbor fabric peer-group
neighbor fabric remote-as 64600
neighbor fabric update-source 192.168.14.11
neighbor 10.255.255.1 peer-group fabric
!
address-family l2vpn evpn
neighbor fabric activate
advertise-all-vni
exit-address-family
exit
!

View file

@ -0,0 +1,18 @@
frr defaults traditional
hostname hv2
log syslog informational
!
router bgp 64600
bgp router-id 192.168.14.12
no bgp default ipv4-unicast
neighbor fabric peer-group
neighbor fabric remote-as 64600
neighbor fabric update-source 192.168.14.12
neighbor 10.255.255.1 peer-group fabric
!
address-family l2vpn evpn
neighbor fabric activate
advertise-all-vni
exit-address-family
exit
!

View file

@ -0,0 +1,43 @@
frr defaults traditional
hostname rr1
log syslog informational
!
ip prefix-list RR-LOOPBACK-OUT seq 10 permit 10.255.255.1/32
!
route-map NO-IN deny 999
description deny
exit
!
router bgp 65000
no bgp default ipv4-unicast
bgp router-id 10.255.255.1
bgp cluster-id 10.255.255.1
neighbor CLUSTER peer-group
neighbor CLUSTER remote-as 65100
neighbor CLUSTER bfd
neighbor 169.254.0.1 peer-group CLUSTER
neighbor 169.254.0.1 description router-1
neighbor 169.254.0.2 peer-group CLUSTER
neighbor 169.254.0.2 description router-2
neighbor fabric peer-group
neighbor fabric remote-as 64600
neighbor fabric local-as 64600 no-prepend replace-as
neighbor fabric capability extended-nexthop
neighbor fabric update-source 10.255.255.1
bgp listen range 192.168.14.0/24 peer-group fabric
bgp listen limit 200
!
address-family ipv4 unicast
network 10.255.255.1/32
neighbor CLUSTER activate
neighbor CLUSTER prefix-list RR-LOOPBACK-OUT out
neighbor CLUSTER route-map NO-IN in
exit-address-family
!
address-family l2vpn evpn
neighbor fabric activate
neighbor fabric route-reflector-client
exit-address-family
!
exit
!

View file

@ -0,0 +1,28 @@
frr defaults traditional
hostname sw1
log syslog informational
!
ip prefix-list RR-LOOPBACK-IN seq 10 permit 10.255.255.1/32
!
route-map RR-IN permit 10
match ip address prefix-list RR-LOOPBACK-IN
exit
!
route-map NO-OUT deny 999
exit
!
router bgp 65100
no bgp default ipv4-unicast
bgp router-id 169.254.0.1
neighbor 169.254.0.3 remote-as 65000
neighbor 169.254.0.3 description rr1
neighbor 169.254.0.3 bfd
!
address-family ipv4 unicast
neighbor 169.254.0.3 activate
neighbor 169.254.0.3 route-map RR-IN in
neighbor 169.254.0.3 route-map NO-OUT out
exit-address-family
!
exit
!

1
examples/evpn-2hv/motd Normal file
View file

@ -0,0 +1 @@
labctl example host

View file

@ -0,0 +1,4 @@
#!/bin/sh
set -eu
install -m 0644 "${LAB_FILES}/motd" /etc/motd
echo "${LAB_NODE}: uplink ${LAB_UPLINK}" >> /etc/motd

View file

@ -0,0 +1,29 @@
name: evpn-2hv
images:
debian12:
url: https://cloud.debian.org/images/cloud/bookworm/latest/debian-12-generic-amd64.qcow2
sums: https://cloud.debian.org/images/cloud/bookworm/latest/SHA512SUMS
segments:
underlay:
switch: sw1
cidr: 192.168.14.0/24
mtu: 9000
nodes:
sw1:
{ role: switch, image: debian12, cpus: 2, memory: 1024,
secondary: { underlay: [169.254.0.1/28] }, frr: frr/sw1.conf }
rr1:
{ role: rr, image: debian12, cpus: 1, memory: 1024, segments: [underlay],
addresses: { underlay: 192.168.14.2 }, secondary: { underlay: [169.254.0.3/28] },
loopback: 10.255.255.1/32, frr: frr/rr1.conf }
hv1:
{ role: host, image: debian12, cpus: 2, memory: 2048, segments: [underlay],
addresses: { underlay: 192.168.14.11 }, frr: frr/hv1.conf, provision: provision/host.sh,
files: { motd: motd } }
hv2:
{ role: host, image: debian12, cpus: 2, memory: 2048, segments: [underlay],
addresses: { underlay: 192.168.14.12 }, frr: frr/hv2.conf, provision: provision/host.sh,
files: { motd: motd } }

10
go.mod Normal file
View file

@ -0,0 +1,10 @@
module git.g3e.fr/syonad/labctl
go 1.25.0
toolchain go1.25.14
require (
go.yaml.in/yaml/v3 v3.0.4
golang.org/x/sys v0.45.0
)

6
go.sum Normal file
View file

@ -0,0 +1,6 @@
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=

View file

@ -14,9 +14,9 @@ import (
"text/tabwriter"
"time"
"git.g3e.fr/syonad/two/internal/lab/provision"
"git.g3e.fr/syonad/two/internal/lab/render"
"git.g3e.fr/syonad/two/internal/lab/topology"
"git.g3e.fr/syonad/labctl/internal/provision"
"git.g3e.fr/syonad/labctl/internal/render"
"git.g3e.fr/syonad/labctl/internal/topology"
)
const (
@ -168,10 +168,7 @@ func (l Lab) waitReady(ctx context.Context, n topology.NodePlan) error {
}
func services(n topology.NodePlan) []string {
var units []string
if n.Role == topology.RoleHypervisor {
units = append(units, "agent.service")
}
units := append([]string(nil), n.Services...)
if n.FRR != "" {
units = append(units, "frr.service")
}

View file

@ -20,11 +20,11 @@ import (
"testing"
"time"
"git.g3e.fr/syonad/two/internal/lab/provision"
"git.g3e.fr/syonad/two/internal/lab/topology"
"git.g3e.fr/syonad/labctl/internal/provision"
"git.g3e.fr/syonad/labctl/internal/topology"
)
const labKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFG/JMmjfko96WkJV8DiL6rip/H/q/R++y8s27Z+Cj6O two-lab"
const labKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFG/JMmjfko96WkJV8DiL6rip/H/q/R++y8s27Z+Cj6O labctl"
type exitErr int
@ -128,7 +128,7 @@ nodes:
}
const switchLast = ` rr1: { role: rr, image: deb, cpus: 1, memory: 1024, segments: [underlay] }
hv1: { role: hypervisor, image: deb, cpus: 4, memory: 16384, segments: [underlay], release: 0.2.0rc002 }
hv1: { role: host, image: deb, cpus: 4, memory: 16384, segments: [underlay], services: [agent.service] }
sw1: { role: switch, image: deb, cpus: 2, memory: 1024 }
`
@ -280,7 +280,7 @@ func TestStatus(t *testing.T) {
}
want := fmt.Sprintf("node role state %-*s ssh\n", w, "pid") +
fmt.Sprintf("rr1 rr stopped %-*s 127.0.0.1:2200\n", w, "-") +
fmt.Sprintf("hv1 hypervisor running %-*s 127.0.0.1:2201\n", w, pid) +
fmt.Sprintf("hv1 host running %-*s 127.0.0.1:2201\n", w, pid) +
fmt.Sprintf("sw1 switch stopped %-*s 127.0.0.1:2202\n", w, "-")
if out.String() != want {
t.Errorf("status:\n%s\nwant:\n%s", out.String(), want)

View file

@ -17,7 +17,7 @@ import (
"regexp"
"strings"
"git.g3e.fr/syonad/two/internal/lab/topology"
"git.g3e.fr/syonad/labctl/internal/topology"
)
const maxSumsSize = 1 << 20

View file

@ -12,7 +12,7 @@ import (
"sync"
"testing"
"git.g3e.fr/syonad/two/internal/lab/topology"
"git.g3e.fr/syonad/labctl/internal/topology"
)
const imageName = "debian-12-generic-amd64.qcow2"

View file

@ -7,15 +7,16 @@ import (
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"git.g3e.fr/syonad/two/internal/lab/render"
"git.g3e.fr/syonad/two/internal/lab/topology"
"git.g3e.fr/syonad/labctl/internal/render"
"git.g3e.fr/syonad/labctl/internal/topology"
)
const (
KeyFile = "lab_ed25519"
KeyLabel = "two-lab"
KeyLabel = "labctl"
DiskSize = "20G"
SeedLabel = "cidata"
@ -72,11 +73,11 @@ func Prepare(ctx context.Context, p *topology.Plan, o Options) ([]render.Node, e
if err != nil {
return nil, err
}
frr, err := ReadFRR(p)
if err != nil {
opts := render.Options{RunDir: o.RunDir, AuthorizedKeys: []string{key}}
if err := ReadInputs(p, &opts); err != nil {
return nil, err
}
nodes, err := render.Render(p, render.Options{RunDir: o.RunDir, AuthorizedKeys: []string{key}, FRR: frr})
nodes, err := render.Render(p, opts)
if err != nil {
return nil, err
}
@ -88,19 +89,40 @@ func Prepare(ctx context.Context, p *topology.Plan, o Options) ([]render.Node, e
return nodes, nil
}
func ReadFRR(p *topology.Plan) (map[string]string, error) {
configs := map[string]string{}
func ReadInputs(p *topology.Plan, o *render.Options) error {
var err error
if o.FRR, err = readNodeFiles(p, func(n topology.NodePlan) string { return n.FRR }); err != nil {
return err
}
if o.Provision, err = readNodeFiles(p, func(n topology.NodePlan) string { return n.Provision }); err != nil {
return err
}
if o.PostProvision, err = readNodeFiles(p, func(n topology.NodePlan) string { return n.PostProvision }); err != nil {
return err
}
for _, n := range p.Nodes {
if n.FRR == "" {
for name, src := range n.Files {
if _, err := os.Stat(src); err != nil {
return fmt.Errorf("node %s: file %s: %w", n.Name, name, err)
}
}
}
return nil
}
func readNodeFiles(p *topology.Plan, path func(topology.NodePlan) string) (map[string]string, error) {
files := map[string]string{}
for _, n := range p.Nodes {
if path(n) == "" {
continue
}
data, err := os.ReadFile(n.FRR)
data, err := os.ReadFile(path(n))
if err != nil {
return nil, fmt.Errorf("node %s: %w", n.Name, err)
}
configs[n.Name] = string(data)
files[n.Name] = string(data)
}
return configs, nil
return files, nil
}
func EnsureKey(ctx context.Context, r Runner, dir string) (string, error) {
@ -157,6 +179,21 @@ func Stage(ctx context.Context, r Runner, n render.Node, base string) error {
for _, f := range SeedFiles {
args = append(args, filepath.Join(n.Dir, f))
}
if err := r.Run(ctx, "genisoimage", args...); err != nil {
return err
}
if len(n.Files) == 0 {
return nil
}
names := make([]string, 0, len(n.Files))
for name := range n.Files {
names = append(names, name)
}
sort.Strings(names)
args = []string{"-quiet", "-output", filepath.Join(n.Dir, render.FilesISO), "-volid", render.FilesLabel, "-joliet", "-rock", "-graft-points"}
for _, name := range names {
args = append(args, name+"="+n.Files[name])
}
return r.Run(ctx, "genisoimage", args...)
}

View file

@ -11,11 +11,11 @@ import (
"go.yaml.in/yaml/v3"
"git.g3e.fr/syonad/two/internal/lab/render"
"git.g3e.fr/syonad/two/internal/lab/topology"
"git.g3e.fr/syonad/labctl/internal/render"
"git.g3e.fr/syonad/labctl/internal/topology"
)
const generatedKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFG/JMmjfko96WkJV8DiL6rip/H/q/R++y8s27Z+Cj6O two-lab"
const generatedKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFG/JMmjfko96WkJV8DiL6rip/H/q/R++y8s27Z+Cj6O labctl"
type fakeRunner struct {
calls [][]string
@ -60,8 +60,8 @@ segments:
nodes:
sw1: { role: switch, image: debian12, cpus: 2, memory: 1024 }
rr1: { role: rr, image: debian12, cpus: 1, memory: 1024, segments: [underlay] }
hv1: { role: hypervisor, image: debian12, cpus: 4, memory: 16384, segments: [underlay], release: 0.2.0rc002 }
hv2: { role: hypervisor, image: debian12, cpus: 4, memory: 16384, segments: [underlay], release: 0.2.0rc002 }
hv1: { role: host, image: debian12, cpus: 4, memory: 16384, segments: [underlay] }
hv2: { role: host, image: debian12, cpus: 4, memory: 16384, segments: [underlay] }
`
topo, err := topology.Parse([]byte(doc))
if err != nil {
@ -98,7 +98,7 @@ func TestPrepare_StagesEveryNode(t *testing.T) {
base := filepath.Join(cache, "debian12", "debian-12-generic-amd64.qcow2")
want := [][]string{
{"ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "two-lab", "-f", filepath.Join(run, "lab_ed25519")},
{"ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "labctl", "-f", filepath.Join(run, "lab_ed25519")},
}
for _, n := range []string{"sw1", "rr1", "hv1", "hv2"} {
dir := filepath.Join(run, n)
@ -280,6 +280,31 @@ func TestEnsureKey_ReportsAFailedGeneration(t *testing.T) {
}
}
func TestStage_BurnsTheNodeFilesIntoTheirOwnISO(t *testing.T) {
runner := &fakeRunner{}
dir := t.TempDir()
n := render.Node{Name: "hv1", Dir: dir, Files: map[string]string{"bin": "/src/bin", "agent.yml": "/src/two.yml"}}
if err := Stage(context.Background(), runner, n, "/cache/deb.qcow2"); err != nil {
t.Fatalf("Stage: %v", err)
}
isos := runner.commands("genisoimage")
want := []string{"genisoimage", "-quiet", "-output", filepath.Join(dir, "files.iso"), "-volid", "LABFILES", "-joliet", "-rock", "-graft-points",
"agent.yml=/src/two.yml", "bin=/src/bin"}
if len(isos) != 2 || !reflect.DeepEqual(isos[1], want) {
t.Errorf("genisoimage calls:\n%q\nwant second:\n%q", isos, want)
}
}
func TestStage_NoFilesNoFilesISO(t *testing.T) {
runner := &fakeRunner{}
if err := Stage(context.Background(), runner, render.Node{Name: "rr1", Dir: t.TempDir()}, "/cache/deb.qcow2"); err != nil {
t.Fatalf("Stage: %v", err)
}
if n := len(runner.commands("genisoimage")); n != 1 {
t.Errorf("genisoimage ran %d times, want only the seed", n)
}
}
func TestStage_RefusesARelativeBaseImage(t *testing.T) {
runner := &fakeRunner{}
err := Stage(context.Background(), runner, render.Node{Name: "hv1", Dir: t.TempDir()}, "debian.qcow2")
@ -307,7 +332,7 @@ func TestEnsureKey_WithTheRealSSHKeygen(t *testing.T) {
if err != nil {
t.Fatalf("EnsureKey: %v", err)
}
if !strings.HasPrefix(key, "ssh-ed25519 ") || !strings.HasSuffix(key, " two-lab") {
if !strings.HasPrefix(key, "ssh-ed25519 ") || !strings.HasSuffix(key, " labctl") {
t.Errorf("key = %q", key)
}
info, err := os.Stat(filepath.Join(dir, "lab_ed25519"))
@ -316,7 +341,7 @@ func TestEnsureKey_WithTheRealSSHKeygen(t *testing.T) {
}
}
func TestReadFRR_ReadsOnlyTheNodesThatDeclareOne(t *testing.T) {
func TestReadInputs_ReadsOnlyTheFRRConfigsDeclared(t *testing.T) {
dir := t.TempDir()
conf := filepath.Join(dir, "rr1.conf")
if err := os.WriteFile(conf, []byte("hostname rr1\n"), 0o600); err != nil {
@ -326,19 +351,20 @@ func TestReadFRR_ReadsOnlyTheNodesThatDeclareOne(t *testing.T) {
p := labPlan(t, m)
p.Nodes[1].FRR = conf
got, err := ReadFRR(p)
var o render.Options
err := ReadInputs(p, &o)
if err != nil || !reflect.DeepEqual(got, map[string]string{"rr1": "hostname rr1\n"}) {
t.Errorf("ReadFRR = %q, %v", got, err)
if err != nil || !reflect.DeepEqual(o.FRR, map[string]string{"rr1": "hostname rr1\n"}) {
t.Errorf("FRR = %q, %v", o.FRR, err)
}
}
func TestReadFRR_NamesTheNodeOfAMissingFile(t *testing.T) {
func TestReadInputs_NamesTheNodeOfAMissingFRRConfig(t *testing.T) {
m := newMirror(t)
p := labPlan(t, m)
p.Nodes[2].FRR = filepath.Join(t.TempDir(), "absent.conf")
if _, err := ReadFRR(p); err == nil || !strings.Contains(err.Error(), "node hv1: ") || !strings.Contains(err.Error(), "absent.conf") {
if err := ReadInputs(p, &render.Options{}); err == nil || !strings.Contains(err.Error(), "node hv1: ") || !strings.Contains(err.Error(), "absent.conf") {
t.Errorf("error = %v", err)
}
}
@ -385,3 +411,40 @@ func TestPrepare_PutsTheFRRConfigIntoTheSeed(t *testing.T) {
}
t.Errorf("hv1 user-data has no /etc/lab/frr.conf:\n%s", data)
}
func TestReadInputs_ReadsTheScriptsAndChecksTheFiles(t *testing.T) {
dir := t.TempDir()
write := func(name, content string) string {
path := filepath.Join(dir, name)
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
return path
}
m := newMirror(t)
p := labPlan(t, m)
p.Nodes[2].Provision = write("hv.sh", "#!/bin/sh\necho provision\n")
p.Nodes[2].PostProvision = write("hv-post.sh", "#!/bin/sh\necho post\n")
p.Nodes[2].Files = map[string]string{"agent.yml": write("two.yml", "dhcp:\n backend: two\n")}
if err := os.Mkdir(filepath.Join(dir, "bin"), 0o700); err != nil {
t.Fatal(err)
}
p.Nodes[2].Files["bin"] = filepath.Join(dir, "bin")
var o render.Options
if err := ReadInputs(p, &o); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(o.Provision, map[string]string{"hv1": "#!/bin/sh\necho provision\n"}) {
t.Errorf("provision = %q", o.Provision)
}
if !reflect.DeepEqual(o.PostProvision, map[string]string{"hv1": "#!/bin/sh\necho post\n"}) {
t.Errorf("post_provision = %q", o.PostProvision)
}
p.Nodes[3].Files = map[string]string{"agent.yml": filepath.Join(dir, "absent.yml")}
if err := ReadInputs(p, &render.Options{}); err == nil || !strings.Contains(err.Error(), "node hv2: file agent.yml: ") {
t.Errorf("error = %v", err)
}
}

View file

@ -5,7 +5,7 @@ import (
"path/filepath"
"strconv"
"git.g3e.fr/syonad/two/internal/lab/topology"
"git.g3e.fr/syonad/labctl/internal/topology"
)
const loopback = "127.0.0.1"
@ -26,6 +26,9 @@ func qemuArgs(p *topology.Plan, n topology.NodePlan, index int, dir string) []st
"-drive", "file=" + filepath.Join(dir, DiskFile) + ",if=virtio,format=qcow2",
"-drive", "file=" + filepath.Join(dir, SeedFile) + ",media=cdrom,readonly=on",
}
if len(n.Files) > 0 {
args = append(args, "-drive", "file="+filepath.Join(dir, FilesISO)+",media=cdrom,readonly=on")
}
restrict := "on"
if n.Role == topology.RoleSwitch {

View file

@ -7,7 +7,7 @@ import (
"path/filepath"
"strings"
"git.g3e.fr/syonad/two/internal/lab/topology"
"git.g3e.fr/syonad/labctl/internal/topology"
)
const (
@ -20,6 +20,8 @@ const (
DiskFile = "disk.qcow2"
SeedFile = "seed.iso"
FilesISO = "files.iso"
FilesLabel = "LABFILES"
ConsoleFile = "console.log"
QMPFile = "qmp.sock"
PIDFile = "qemu.pid"
@ -31,11 +33,14 @@ type Options struct {
RunDir string
AuthorizedKeys []string
FRR map[string]string
Provision map[string]string
PostProvision map[string]string
}
type Node struct {
Name string
Dir string
Files map[string]string
QEMU []string
MetaData []byte
UserData []byte
@ -50,6 +55,12 @@ func Render(p *topology.Plan, o Options) ([]Node, error) {
if _, ok := o.FRR[n.Name]; n.FRR != "" && !ok {
return nil, fmt.Errorf("node %s: frr configuration %s was not read", n.Name, n.FRR)
}
if _, ok := o.Provision[n.Name]; n.Provision != "" && !ok {
return nil, fmt.Errorf("node %s: provision script %s was not read", n.Name, n.Provision)
}
if _, ok := o.PostProvision[n.Name]; n.PostProvision != "" && !ok {
return nil, fmt.Errorf("node %s: post_provision script %s was not read", n.Name, n.PostProvision)
}
}
var nodes []Node
for index, n := range p.Nodes {
@ -69,6 +80,7 @@ func Render(p *topology.Plan, o Options) ([]Node, error) {
nodes = append(nodes, Node{
Name: n.Name,
Dir: dir,
Files: n.Files,
QEMU: qemuArgs(p, n, index, dir),
MetaData: meta,
UserData: user,

View file

@ -7,10 +7,10 @@ import (
"go.yaml.in/yaml/v3"
"git.g3e.fr/syonad/two/internal/lab/topology"
"git.g3e.fr/syonad/labctl/internal/topology"
)
const labKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFG/JMmjfko96WkJV8DiL6rip/H/q/R++y8s27Z+Cj6O two-lab-automation"
const labKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFG/JMmjfko96WkJV8DiL6rip/H/q/R++y8s27Z+Cj6O lab-automation"
const twoHypervisors = `name: evpn-2hv
images:
@ -22,8 +22,8 @@ segments:
nodes:
sw1: { role: switch, image: deb, cpus: 2, memory: 1024 }
rr1: { role: rr, image: deb, cpus: 1, memory: 1024, segments: [underlay] }
hv1: { role: hypervisor, image: deb, cpus: 4, memory: 16384, segments: [underlay], release: 0.2.0rc002 }
hv2: { role: hypervisor, image: deb, cpus: 4, memory: 16384, segments: [underlay], release: 0.2.0rc002 }
hv1: { role: host, image: deb, cpus: 4, memory: 16384, segments: [underlay] }
hv2: { role: host, image: deb, cpus: 4, memory: 16384, segments: [underlay] }
`
const twoSegments = `name: two-seg
@ -36,7 +36,7 @@ segments:
blue: { switch: sw, cidr: 10.2.0.0/24, mtu: 1500 }
nodes:
sw: { role: switch, image: deb, cpus: 1, memory: 512 }
hv: { role: hypervisor, image: deb, cpus: 1, memory: 512, segments: [blue, red], release: 0.2.0rc002 }
hv: { role: host, image: deb, cpus: 1, memory: 512, segments: [blue, red] }
`
func plan(t *testing.T, doc string) *topology.Plan {
@ -315,9 +315,9 @@ func TestNetworkConfig_DefaultRouteOnlyOnFirstSegment(t *testing.T) {
}
}
func TestUserData_Hypervisor(t *testing.T) {
func TestUserData_HostWithoutProvision(t *testing.T) {
cfg := user(t, nodeNamed(t, renderAll(t, twoHypervisors), "hv1"))
if cfg.Hostname != "hv1" || !cfg.DisableRoot || len(cfg.Packages) != 0 || !reflect.DeepEqual(cfg.Runcmd, [][]string{{"/usr/local/sbin/lab-provision"}}) {
if cfg.Hostname != "hv1" || !cfg.DisableRoot || len(cfg.Packages) != 0 || cfg.Runcmd != nil || len(cfg.WriteFiles) != 0 {
t.Errorf("hv1 user-data = %+v", cfg)
}
if !reflect.DeepEqual(cfg.SSHAuthorizedKeys, []string{labKey}) {

View file

@ -1,11 +1,9 @@
package render
import (
"bytes"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"os"
"reflect"
"strings"
"testing"
@ -21,8 +19,8 @@ segments:
nodes:
sw1: { role: switch, image: deb, cpus: 2, memory: 1024, secondary: { underlay: [169.254.0.1/28] }, frr: sw1.conf }
rr1: { role: rr, image: deb, cpus: 1, memory: 1024, segments: [underlay], secondary: { underlay: [169.254.0.3/28] }, loopback: 10.255.255.1/32, frr: rr1.conf }
hv1: { role: hypervisor, image: deb, cpus: 4, memory: 16384, segments: [underlay], frr: hv1.conf, release: 0.2.0rc002 }
hv2: { role: hypervisor, image: deb, cpus: 4, memory: 16384, segments: [underlay], release: 0.2.0rc002 }
hv1: { role: host, image: deb, cpus: 4, memory: 16384, segments: [underlay], frr: hv1.conf, provision: hv.sh, post_provision: hv-post.sh, files: { agent.yml: two.yml }, services: [agent.service] }
hv2: { role: host, image: deb, cpus: 4, memory: 16384, segments: [underlay] }
`
var frrConfigs = map[string]string{
@ -31,9 +29,19 @@ var frrConfigs = map[string]string{
"hv1": "hostname hv1\nrouter bgp 64600\n",
}
func roleOptions() Options {
return Options{
RunDir: "/srv/lab",
AuthorizedKeys: []string{labKey},
FRR: frrConfigs,
Provision: map[string]string{"hv1": "#!/bin/sh\necho provision\n"},
PostProvision: map[string]string{"hv1": "#!/bin/sh\necho post\n"},
}
}
func renderRoles(t *testing.T) map[string]Node {
t.Helper()
nodes, err := Render(plan(t, withRoles), Options{RunDir: "/srv/lab", AuthorizedKeys: []string{labKey}, FRR: frrConfigs})
nodes, err := Render(plan(t, withRoles), roleOptions())
if err != nil {
t.Fatalf("Render: %v", err)
}
@ -145,10 +153,11 @@ func TestRoles_FRRKeyIsThePinnedRepositoryKey(t *testing.T) {
func TestRoles_ProvisioningIsOneScriptThatStopsAtTheFirstFailure(t *testing.T) {
nodes := renderRoles(t)
env := "LAB_NODE=hv1 LAB_UPLINK=underlay LAB_FILES=/etc/lab/files "
files := "mkdir -p /etc/lab/files /run/lab-files\nmount -o ro LABEL=LABFILES /run/lab-files\ncp -R /run/lab-files/. /etc/lab/files/\numount /run/lab-files\n"
for name, steps := range map[string]string{
"sw1": "systemctl daemon-reload\nsystemctl enable --now lab-switch.service\n/usr/local/sbin/lab-frr\n",
"hv1": "/usr/local/sbin/lab-deploy\n/usr/local/sbin/lab-frr\n",
"hv2": "/usr/local/sbin/lab-deploy\n",
"hv1": files + env + "/usr/local/sbin/lab-node-provision\n/usr/local/sbin/lab-frr\n" + env + "/usr/local/sbin/lab-node-post-provision\n",
} {
cfg := user(t, nodeNamed(t, nodes, name))
if !reflect.DeepEqual(cfg.Runcmd, [][]string{{"/usr/local/sbin/lab-provision"}}) {
@ -159,47 +168,55 @@ func TestRoles_ProvisioningIsOneScriptThatStopsAtTheFirstFailure(t *testing.T) {
t.Errorf("%s lab-provision (%s):\n%s", name, f.Permissions, f.Content)
}
}
if cfg := user(t, nodeNamed(t, nodes, "hv2")); cfg.Runcmd != nil {
t.Errorf("hv2 has nothing to provision, runcmd = %q", cfg.Runcmd)
}
}
func TestRoles_HypervisorDeploysTheReleaseThroughTheRepositoryScripts(t *testing.T) {
func TestRoles_FilesTravelOnASecondCDROM(t *testing.T) {
nodes := renderRoles(t)
hv1 := nodeNamed(t, nodes, "hv1")
if !reflect.DeepEqual(hv1.Files, map[string]string{"agent.yml": "two.yml"}) {
t.Errorf("hv1 files = %v", hv1.Files)
}
drive := "file=/srv/lab/hv1/files.iso,media=cdrom,readonly=on"
if !strings.Contains(strings.Join(hv1.QEMU, " "), "-drive "+drive) {
t.Errorf("hv1 qemu lacks %s:\n%s", drive, strings.Join(hv1.QEMU, "\n"))
}
for _, f := range user(t, hv1).WriteFiles {
if strings.HasPrefix(f.Path, "/etc/lab/files/") {
t.Errorf("hv1 user-data carries %s, files belong to the ISO", f.Path)
}
}
for _, name := range []string{"sw1", "rr1", "hv2"} {
if n := nodeNamed(t, nodes, name); strings.Contains(strings.Join(n.QEMU, " "), "files.iso") || n.Files != nil {
t.Errorf("%s gets a files ISO", name)
}
}
}
func TestRoles_HostReceivesItsScripts(t *testing.T) {
cfg := user(t, nodeNamed(t, renderRoles(t), "hv1"))
f := fileAt(t, cfg, "/usr/local/sbin/lab-deploy")
want := `#!/bin/sh
set -eu
n=0
until curl -fsS -o /dev/null https://git.g3e.fr/; do
n=$((n + 1))
[ "$n" -lt 30 ] || exit 1
sleep 10
done
cd /opt/two/scripts
bash ./deploy.sh --noup_script -i -u underlay -t 0.2.0rc002
`
if f.Content != want || f.Permissions != "0755" {
t.Errorf("lab-deploy (%s):\n%s\nwant:\n%s", f.Permissions, f.Content, want)
}
for path, source := range map[string]string{
"/opt/two/scripts/deploy.sh": "../../../scripts/deploy.sh",
"/opt/two/scripts/bootstrap_kvm.sh": "../../../scripts/bootstrap_kvm.sh",
for path, want := range map[string]struct {
content string
permissions string
}{
"/usr/local/sbin/lab-node-provision": {"#!/bin/sh\necho provision\n", "0755"},
"/usr/local/sbin/lab-node-post-provision": {"#!/bin/sh\necho post\n", "0755"},
} {
f := fileAt(t, cfg, path)
got, err := base64.StdEncoding.DecodeString(f.Content)
if err != nil {
t.Fatal(err)
}
repo, err := os.ReadFile(source)
if err != nil {
t.Fatal(err)
}
if f.Encoding != "b64" || f.Permissions != "0755" || !bytes.Equal(got, repo) {
t.Errorf("%s: encoding %q, permissions %q, identical to %s: %v", path, f.Encoding, f.Permissions, source, bytes.Equal(got, repo))
if f.Encoding != "b64" || f.Permissions != want.permissions || string(got) != want.content {
t.Errorf("%s: encoding %q, permissions %q, content %q", path, f.Encoding, f.Permissions, got)
}
}
}
func TestRoles_UplinkIsTheInterfaceCarryingTheDefaultRoute(t *testing.T) {
p := plan(t, twoSegments)
hv := nodeNamed(t, renderAll(t, twoSegments), "hv")
var withDefault []string
for name, e := range network(t, hv).Ethernets {
@ -212,22 +229,36 @@ func TestRoles_UplinkIsTheInterfaceCarryingTheDefaultRoute(t *testing.T) {
if !reflect.DeepEqual(withDefault, []string{"red"}) {
t.Fatalf("default route on %v, want [red]", withDefault)
}
if got := fileAt(t, user(t, hv), "/usr/local/sbin/lab-deploy").Content; !strings.HasSuffix(got, "bash ./deploy.sh --noup_script -i -u red -t 0.2.0rc002\n") {
t.Errorf("lab-deploy:\n%s", got)
for _, n := range p.Nodes {
if n.Name == "hv" {
if got := provisionEnv(p, n); got != "LAB_NODE=hv LAB_UPLINK=red LAB_FILES=/etc/lab/files " {
t.Errorf("provision environment = %q", got)
}
}
}
}
func TestRoles_OnlyHypervisorsDeployTwo(t *testing.T) {
func TestRoles_NodesWithoutProvisionReceiveNoProvisionFiles(t *testing.T) {
nodes := renderRoles(t)
for _, name := range []string{"sw1", "rr1"} {
for _, name := range []string{"sw1", "rr1", "hv2"} {
for _, f := range user(t, nodeNamed(t, nodes, name)).WriteFiles {
if strings.HasPrefix(f.Path, "/opt/two/") || f.Path == "/usr/local/sbin/lab-deploy" {
if strings.HasPrefix(f.Path, "/etc/lab/files/") || strings.HasPrefix(f.Path, "/usr/local/sbin/lab-node-") {
t.Errorf("%s receives %s", name, f.Path)
}
}
}
}
func TestRoles_FRRDaemons(t *testing.T) {
p := plan(t, withRoles)
want := map[string][]string{"sw1": {"bgpd", "bfdd"}, "rr1": {"bgpd", "bfdd"}, "hv1": {"bgpd"}}
for _, n := range p.Nodes {
if w, ok := want[n.Name]; ok && !reflect.DeepEqual(frrDaemons(n), w) {
t.Errorf("%s daemons = %v, want %v", n.Name, frrDaemons(n), w)
}
}
}
func TestRoles_NodeWithoutRoleFieldsGetsNoFRR(t *testing.T) {
for _, f := range user(t, nodeNamed(t, renderRoles(t), "hv2")).WriteFiles {
if strings.Contains(f.Path, "frr") {
@ -246,7 +277,7 @@ func TestRoles_RefusesAnUnreadFRRConfig(t *testing.T) {
func TestRoles_SwitchLoopbackIsCreatedByTheSwitchScript(t *testing.T) {
doc := strings.Replace(withRoles, "secondary: { underlay: [169.254.0.1/28] }, frr: sw1.conf", "secondary: { underlay: [169.254.0.1/28] }, loopback: 10.255.254.1/32, frr: sw1.conf", 1)
nodes, err := Render(plan(t, doc), Options{RunDir: "/srv/lab", AuthorizedKeys: []string{labKey}, FRR: frrConfigs})
nodes, err := Render(plan(t, doc), roleOptions())
if err != nil {
t.Fatalf("Render: %v", err)
}
@ -262,3 +293,20 @@ func TestRoles_SwitchLoopbackIsCreatedByTheSwitchScript(t *testing.T) {
t.Errorf("lab-switch:\n%s\ndoes not end with:\n%s", script, want)
}
}
func TestRoles_RefusesUnreadProvisionInputs(t *testing.T) {
cases := map[string]struct {
mutate func(*Options)
want string
}{
"provision": {func(o *Options) { o.Provision = nil }, "node hv1: provision script hv.sh was not read"},
"post": {func(o *Options) { o.PostProvision = nil }, "node hv1: post_provision script hv-post.sh was not read"},
}
for name, c := range cases {
o := roleOptions()
c.mutate(&o)
if _, err := Render(plan(t, withRoles), o); err == nil || err.Error() != c.want {
t.Errorf("%s: error = %v, want %q", name, err, c.want)
}
}
}

View file

@ -8,8 +8,7 @@ import (
"go.yaml.in/yaml/v3"
"git.g3e.fr/syonad/two/internal/lab/topology"
"git.g3e.fr/syonad/two/scripts"
"git.g3e.fr/syonad/labctl/internal/topology"
)
const (
@ -28,9 +27,10 @@ const (
FRRPackages = "frr frr-pythontools"
ProvisionScript = "/usr/local/sbin/lab-provision"
DeployScript = "/usr/local/sbin/lab-deploy"
TwoScriptsDir = "/opt/two/scripts"
TwoGitServer = "https://git.g3e.fr/"
NodeProvision = "/usr/local/sbin/lab-node-provision"
NodePostProvision = "/usr/local/sbin/lab-node-post-provision"
FilesDir = "/etc/lab/files"
FilesMount = "/run/lab-files"
)
//go:embed frrouting.gpg
@ -114,13 +114,17 @@ func userData(p *topology.Plan, n topology.NodePlan, o Options) ([]byte, error)
}
steps = append(steps, "systemctl daemon-reload", "systemctl enable --now lab-node.service")
}
if n.Role == topology.RoleHypervisor {
cfg.WriteFiles = append(cfg.WriteFiles,
writeFile{Path: TwoScriptsDir + "/deploy.sh", Permissions: "0755", Encoding: "b64", Content: base64.StdEncoding.EncodeToString(scripts.Deploy)},
writeFile{Path: TwoScriptsDir + "/bootstrap_kvm.sh", Permissions: "0755", Encoding: "b64", Content: base64.StdEncoding.EncodeToString(scripts.BootstrapKVM)},
writeFile{Path: DeployScript, Permissions: "0755", Content: deployScript(p, n)},
if len(n.Files) > 0 {
steps = append(steps,
"mkdir -p "+FilesDir+" "+FilesMount,
"mount -o ro LABEL="+FilesLabel+" "+FilesMount,
"cp -R "+FilesMount+"/. "+FilesDir+"/",
"umount "+FilesMount,
)
steps = append(steps, DeployScript)
}
if n.Provision != "" {
cfg.WriteFiles = append(cfg.WriteFiles, writeFile{Path: NodeProvision, Permissions: "0755", Encoding: "b64", Content: base64.StdEncoding.EncodeToString([]byte(o.Provision[n.Name]))})
steps = append(steps, provisionEnv(p, n)+NodeProvision)
}
if n.FRR != "" {
cfg.WriteFiles = append(cfg.WriteFiles,
@ -130,6 +134,10 @@ func userData(p *topology.Plan, n topology.NodePlan, o Options) ([]byte, error)
)
steps = append(steps, FRRScript)
}
if n.PostProvision != "" {
cfg.WriteFiles = append(cfg.WriteFiles, writeFile{Path: NodePostProvision, Permissions: "0755", Encoding: "b64", Content: base64.StdEncoding.EncodeToString([]byte(o.PostProvision[n.Name]))})
steps = append(steps, provisionEnv(p, n)+NodePostProvision)
}
if len(steps) > 0 {
cfg.WriteFiles = append(cfg.WriteFiles,
writeFile{Path: ProvisionScript, Permissions: "0755", Content: "#!/bin/sh\nset -eu\n" + strings.Join(steps, "\n") + "\n"},
@ -147,16 +155,16 @@ func retry(command string) string {
return "n=0\nuntil " + command + "; do\n n=$((n + 1))\n [ \"$n\" -lt 30 ] || exit 1\n sleep 10\ndone\n"
}
func deployScript(p *topology.Plan, n topology.NodePlan) string {
uplink := nodeCables(p, n.Name)[0].NodeInterface
return "#!/bin/sh\nset -eu\n" +
retry("curl -fsS -o /dev/null "+TwoGitServer) +
"cd " + TwoScriptsDir + "\n" +
fmt.Sprintf("bash ./deploy.sh --noup_script -i -u %s -t %s\n", uplink, n.Release)
func provisionEnv(p *topology.Plan, n topology.NodePlan) string {
uplink := ""
if cables := nodeCables(p, n.Name); len(cables) > 0 {
uplink = cables[0].NodeInterface
}
return fmt.Sprintf("LAB_NODE=%s LAB_UPLINK=%s LAB_FILES=%s ", n.Name, uplink, FilesDir)
}
func frrDaemons(n topology.NodePlan) []string {
if n.Role == topology.RoleHypervisor {
if n.Role == topology.RoleHost {
return []string{"bgpd"}
}
return []string{"bgpd", "bfdd"}

View file

@ -22,15 +22,17 @@ func (p *Plan) Write(w io.Writer) error {
var extras []NodePlan
for _, n := range p.Nodes {
if len(n.Secondary) > 0 || n.Loopback.IsValid() || n.FRR != "" || n.Release != "" {
if len(n.Secondary) > 0 || n.Loopback.IsValid() || n.FRR != "" || n.Provision != "" || n.PostProvision != "" || len(n.Files) > 0 || len(n.Services) > 0 {
extras = append(extras, n)
}
}
if len(extras) > 0 {
fmt.Fprintf(tw, "\nroles\n")
fmt.Fprintf(tw, " name\tloopback\tsecondary\tfrr\trelease\n")
fmt.Fprintf(tw, " name\tloopback\tsecondary\tfrr\tprovision\tpost_provision\tfiles\tservices\n")
for _, n := range extras {
fmt.Fprintf(tw, " %s\t%s\t%s\t%s\t%s\n", n.Name, orDash(loopback(n)), orDash(secondary(n)), orDash(filepath.Base(n.FRR)), orDash(n.Release))
fmt.Fprintf(tw, " %s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", n.Name, orDash(loopback(n)), orDash(secondary(n)),
orDash(filepath.Base(n.FRR)), orDash(filepath.Base(n.Provision)), orDash(filepath.Base(n.PostProvision)),
orDash(strings.Join(sortedKeys(n.Files), ",")), orDash(strings.Join(n.Services, ",")))
}
}

View file

@ -43,7 +43,10 @@ type NodePlan struct {
Secondary map[string][]netip.Prefix
Loopback netip.Prefix
FRR string
Release string
Provision string
PostProvision string
Files map[string]string
Services []string
}
type Cable struct {
@ -77,7 +80,10 @@ func Compute(t *Topology) (*Plan, error) {
Memory: n.Memory,
SSHPort: SSHBasePort + i,
FRR: n.FRR,
Release: n.Release,
Provision: n.Provision,
PostProvision: n.PostProvision,
Files: n.Files,
Services: n.Services,
}
for segment, raws := range n.Secondary {
for _, raw := range raws {

View file

@ -55,8 +55,8 @@ segments:
nodes:
sw1: { role: switch, image: deb, cpus: 2, memory: 1024 }
rr1: { role: rr, image: deb, cpus: 1, memory: 1024, segments: [underlay] }
hv1: { role: hypervisor, image: deb, cpus: 4, memory: 16384, segments: [underlay], release: 0.2.0rc002 }
hv2: { role: hypervisor, image: deb, cpus: 4, memory: 16384, segments: [underlay], release: 0.2.0rc002 }
hv1: { role: host, image: deb, cpus: 4, memory: 16384, segments: [underlay] }
hv2: { role: host, image: deb, cpus: 4, memory: 16384, segments: [underlay] }
`
func TestCompute_TwoHypervisorsPlan(t *testing.T) {
@ -102,7 +102,7 @@ func TestCompute_TwoHypervisorsPlan(t *testing.T) {
t.Errorf("%s ssh port = %d, want %d", name, got, port)
}
}
if hv := nodeOf(t, p, "hv1"); hv.Role != "hypervisor" || hv.CPUs != 4 || hv.Memory != 16384 || hv.Image != "deb" {
if hv := nodeOf(t, p, "hv1"); hv.Role != "host" || hv.CPUs != 4 || hv.Memory != 16384 || hv.Image != "deb" {
t.Errorf("hv1 = %+v", hv)
}
}
@ -165,7 +165,7 @@ segments:
blue: { switch: sw, cidr: 10.2.0.0/24, mtu: 1500 }
nodes:
sw: { role: switch, image: deb, cpus: 1, memory: 512 }
hv: { role: hypervisor, image: deb, cpus: 1, memory: 512, segments: [blue, red], release: 0.2.0rc002 }
hv: { role: host, image: deb, cpus: 1, memory: 512, segments: [blue, red] }
rr: { role: rr, image: deb, cpus: 1, memory: 512, segments: [red] }
`)
got := make([]string, 0, len(p.Cables))
@ -193,7 +193,7 @@ nodes:
sw: { role: switch, image: deb, cpus: 1, memory: 512 }
n1: { role: rr, image: deb, cpus: 1, memory: 512, segments: [a, b] }
n2: { role: rr, image: deb, cpus: 1, memory: 512, segments: [a, b] }
n3: { role: hypervisor, image: deb, cpus: 1, memory: 512, segments: [b, a], release: 0.2.0rc002 }
n3: { role: host, image: deb, cpus: 1, memory: 512, segments: [b, a] }
`)
macs := map[string]bool{}
ports := map[int]bool{}
@ -311,13 +311,8 @@ nodes
name role image cpus memory ssh
sw1 switch deb 2 1024 MiB 127.0.0.1:2200
rr1 rr deb 1 1024 MiB 127.0.0.1:2201
hv1 hypervisor deb 4 16384 MiB 127.0.0.1:2202
hv2 hypervisor deb 4 16384 MiB 127.0.0.1:2203
roles
name loopback secondary frr release
hv1 - - - 0.2.0rc002
hv2 - - - 0.2.0rc002
hv1 host deb 4 16384 MiB 127.0.0.1:2202
hv2 host deb 4 16384 MiB 127.0.0.1:2203
segment underlay: 10.250.0.0/24, mtu 9000, switch sw1, bridge br-underlay, gateway 10.250.0.1
node interface address mac udp switch port mac udp

View file

@ -15,7 +15,7 @@ segments:
nodes:
sw1: { role: switch, image: deb, cpus: 2, memory: 1024, secondary: { underlay: [169.254.0.1/28] }, frr: frr/sw1.conf }
rr1: { role: rr, image: deb, cpus: 1, memory: 1024, segments: [underlay], secondary: { underlay: [169.254.0.3/28] }, loopback: 10.255.255.1/32, frr: frr/rr1.conf }
hv1: { role: hypervisor, image: deb, cpus: 4, memory: 16384, segments: [underlay], frr: /etc/lab/hv1.conf, release: 0.2.0rc002 }
hv1: { role: host, image: deb, cpus: 4, memory: 16384, segments: [underlay], frr: /etc/lab/hv1.conf, provision: provision/hv.sh, post_provision: /opt/lab/post.sh, files: { agent.yml: agent/two.yml, deploy.sh: /opt/deploy.sh }, services: [agent.service] }
`
func TestCompute_CarriesTheRoleFields(t *testing.T) {
@ -99,7 +99,7 @@ segments:
blue: { switch: sw, cidr: 10.2.0.0/24 }
nodes:
sw: { role: switch, image: deb, cpus: 1, memory: 512 }
hv: { role: hypervisor, image: deb, cpus: 1, memory: 512, segments: [red, blue], release: 0.2.0rc002 }
hv: { role: host, image: deb, cpus: 1, memory: 512, segments: [red, blue] }
` + c.node + `
`
requireContains(t, validationError(t, doc), c.want)
@ -115,7 +115,7 @@ segments:
nodes:
sw: { role: switch, image: deb, cpus: 1, memory: 512, secondary: { red: [169.254.0.1/28], blue: [169.254.1.1/28] } }
other: { role: switch, image: deb, cpus: 1, memory: 512 }
hv: { role: hypervisor, image: deb, cpus: 1, memory: 512, segments: [red, blue], release: 0.2.0rc002 }
hv: { role: host, image: deb, cpus: 1, memory: 512, segments: [red, blue] }
`
msg := validationError(t, doc)
requireContains(t, msg, "node sw: secondary address given for segment blue it is not attached to")
@ -130,7 +130,7 @@ segments:
lo1: { switch: sw, cidr: 10.1.0.0/24 }
nodes:
sw: { role: switch, image: deb, cpus: 1, memory: 512 }
hv: { role: hypervisor, image: deb, cpus: 1, memory: 512, segments: [lo1], release: 0.2.0rc002 }
hv: { role: host, image: deb, cpus: 1, memory: 512, segments: [lo1] }
`
requireContains(t, validationError(t, doc), "segment lo1: name is reserved for the loopback interface")
}
@ -142,10 +142,10 @@ func TestWrite_ShowsTheRoles(t *testing.T) {
}
want := `
roles
name loopback secondary frr release
sw1 - underlay 169.254.0.1/28 sw1.conf -
rr1 lo1 10.255.255.1/32 underlay 169.254.0.3/28 rr1.conf -
hv1 - - hv1.conf 0.2.0rc002
name loopback secondary frr provision post_provision files services
sw1 - underlay 169.254.0.1/28 sw1.conf - - - -
rr1 lo1 10.255.255.1/32 underlay 169.254.0.3/28 rr1.conf - - - -
hv1 - - hv1.conf hv.sh post.sh agent.yml,deploy.sh agent.service
`
if !bytes.Contains(buf.Bytes(), []byte(want)) {
t.Errorf("plan:\n%s\ndoes not contain:\n%s", buf.String(), want)
@ -169,27 +169,34 @@ nodes:
}
}
func TestValidate_ReleaseRejections(t *testing.T) {
func TestValidate_ProvisionRejections(t *testing.T) {
cases := map[string]struct {
node string
want string
}{
"hypervisor without release": {
"the hypervisor role is gone": {
`hv: { role: hypervisor, image: deb, cpus: 1, memory: 512, segments: [red] }`,
"node hv: a hypervisor needs the release of two to deploy (release: <tag>)",
`node hv: role "hypervisor" must be one of switch, rr, host`,
},
"release with shell characters": {
`hv: { role: hypervisor, image: deb, cpus: 1, memory: 512, segments: [red], release: "0.2.0; reboot" }`,
`node hv: release "0.2.0; reboot" must match`,
"file name leaving the files directory": {
`hv: { role: host, image: deb, cpus: 1, memory: 512, segments: [red], files: { ../etc/passwd: a.yml } }`,
`node hv: file name "../etc/passwd" must match`,
},
"release on a route reflector": {
`hv: { role: rr, image: deb, cpus: 1, memory: 512, segments: [red], release: 0.2.0rc002 }`,
"node hv: release is only for hypervisors",
"file without source": {
`hv: { role: host, image: deb, cpus: 1, memory: 512, segments: [red], files: { agent.yml: "" } }`,
"node hv: file agent.yml has no source",
},
"release on a switch": {
`hv: { role: hypervisor, image: deb, cpus: 1, memory: 512, segments: [red], release: 0.2.0rc002 }
sw2: { role: switch, image: deb, cpus: 1, memory: 512, release: 0.2.0rc002 }`,
"node sw2: release is only for hypervisors",
"file source with an equals sign": {
`hv: { role: host, image: deb, cpus: 1, memory: 512, segments: [red], files: { bin: "a=b" } }`,
`node hv: file bin: source "a=b" must not contain '='`,
},
"service with shell characters": {
`hv: { role: host, image: deb, cpus: 1, memory: 512, segments: [red], services: ["agent.service; reboot"] }`,
`node hv: service "agent.service; reboot" must match`,
},
"service listed twice": {
`hv: { role: host, image: deb, cpus: 1, memory: 512, segments: [red], services: [agent.service, agent.service] }`,
"node hv: service agent.service listed twice",
},
}
for name, c := range cases {
@ -206,11 +213,61 @@ nodes:
}
}
func TestCompute_CarriesTheRelease(t *testing.T) {
if got := nodeOf(t, compute(t, withRoles), "hv1").Release; got != "0.2.0rc002" {
t.Errorf("hv1 release = %q", got)
func TestValidate_ProvisionIsAllowedOnEveryRole(t *testing.T) {
doc := header + `
segments:
red: { switch: sw, cidr: 10.1.0.0/24 }
nodes:
sw: { role: switch, image: deb, cpus: 1, memory: 512, provision: sw.sh, files: { a.conf: a.conf }, services: [lab-switch.service] }
rr: { role: rr, image: deb, cpus: 1, memory: 512, segments: [red], provision: rr.sh, post_provision: rr-post.sh }
hv: { role: host, image: deb, cpus: 1, memory: 512, segments: [red], files: { agent.yml: agent.yml }, services: [agent.service] }
`
compute(t, doc)
}
if got := nodeOf(t, compute(t, withRoles), "rr1").Release; got != "" {
t.Errorf("rr1 release = %q", got)
func TestCompute_CarriesTheProvision(t *testing.T) {
hv1 := nodeOf(t, compute(t, withRoles), "hv1")
if hv1.Provision != "provision/hv.sh" || hv1.PostProvision != "/opt/lab/post.sh" {
t.Errorf("hv1 provision = %q, post_provision = %q", hv1.Provision, hv1.PostProvision)
}
if !reflect.DeepEqual(hv1.Files, map[string]string{"agent.yml": "agent/two.yml", "deploy.sh": "/opt/deploy.sh"}) {
t.Errorf("hv1 files = %v", hv1.Files)
}
if !reflect.DeepEqual(hv1.Services, []string{"agent.service"}) {
t.Errorf("hv1 services = %v", hv1.Services)
}
rr1 := nodeOf(t, compute(t, withRoles), "rr1")
if rr1.Provision != "" || rr1.PostProvision != "" || rr1.Files != nil || rr1.Services != nil {
t.Errorf("rr1 = %+v, want no provision", rr1)
}
}
func TestLoad_ResolvesProvisionPathsAgainstTheTopologyFile(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "lab.yml")
if err := os.WriteFile(path, []byte(withRoles), 0o600); err != nil {
t.Fatal(err)
}
topo, err := Load(path)
if err != nil {
t.Fatalf("Load: %v", err)
}
p, err := Compute(topo)
if err != nil {
t.Fatal(err)
}
hv1 := nodeOf(t, p, "hv1")
if hv1.Provision != filepath.Join(dir, "provision", "hv.sh") {
t.Errorf("provision = %q", hv1.Provision)
}
if hv1.PostProvision != "/opt/lab/post.sh" {
t.Errorf("post_provision = %q, an absolute path must be kept", hv1.PostProvision)
}
want := map[string]string{"agent.yml": filepath.Join(dir, "agent", "two.yml"), "deploy.sh": "/opt/deploy.sh"}
if !reflect.DeepEqual(hv1.Files, want) {
t.Errorf("files = %v, want %v", hv1.Files, want)
}
if rr1 := nodeOf(t, p, "rr1"); rr1.Provision != "" || rr1.Files != nil {
t.Errorf("rr1 = %+v", rr1)
}
}

View file

@ -13,7 +13,7 @@ import (
const (
RoleSwitch = "switch"
RoleRR = "rr"
RoleHypervisor = "hypervisor"
RoleHost = "host"
DefaultMTU = 9000
)
@ -49,7 +49,10 @@ type Node struct {
Secondary map[string][]string
Loopback string
FRR string
Release string
Provision string
PostProvision string
Files map[string]string
Services []string
}
type fileImage struct {
@ -73,7 +76,10 @@ type fileNode struct {
Secondary map[string][]string `yaml:"secondary"`
Loopback string `yaml:"loopback"`
FRR string `yaml:"frr"`
Release string `yaml:"release"`
Provision string `yaml:"provision"`
PostProvision string `yaml:"post_provision"`
Files map[string]string `yaml:"files"`
Services []string `yaml:"services"`
}
type file struct {
@ -92,14 +98,25 @@ func Load(path string) (*Topology, error) {
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
dir := filepath.Dir(path)
for i, n := range t.Nodes {
if n.FRR != "" && !filepath.IsAbs(n.FRR) {
t.Nodes[i].FRR = filepath.Join(filepath.Dir(path), n.FRR)
t.Nodes[i].FRR = relativeTo(dir, n.FRR)
t.Nodes[i].Provision = relativeTo(dir, n.Provision)
t.Nodes[i].PostProvision = relativeTo(dir, n.PostProvision)
for name, src := range n.Files {
t.Nodes[i].Files[name] = relativeTo(dir, src)
}
}
return t, nil
}
func relativeTo(dir, path string) string {
if path == "" || filepath.IsAbs(path) {
return path
}
return filepath.Join(dir, path)
}
func Parse(data []byte) (*Topology, error) {
var f file
dec := yaml.NewDecoder(bytes.NewReader(data))
@ -143,7 +160,10 @@ func Parse(data []byte) (*Topology, error) {
Secondary: n.Secondary,
Loopback: n.Loopback,
FRR: n.FRR,
Release: n.Release,
Provision: n.Provision,
PostProvision: n.PostProvision,
Files: n.Files,
Services: n.Services,
})
}
return t, nil

View file

@ -23,7 +23,8 @@ const (
var (
namePattern = regexp.MustCompile(`^[a-z][a-z0-9-]{0,14}$`)
segmentPattern = regexp.MustCompile(`^[a-z][a-z0-9]{0,11}$`)
releasePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)
filePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)
unitPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9@._:-]{0,127}$`)
)
func (t *Topology) Validate() error {
@ -108,9 +109,9 @@ func (t *Topology) Validate() error {
add("node %s: name must match %s", n.Name, namePattern)
}
switch n.Role {
case RoleSwitch, RoleRR, RoleHypervisor:
case RoleSwitch, RoleRR, RoleHost:
default:
add("node %s: role %q must be one of %s, %s, %s", n.Name, n.Role, RoleSwitch, RoleRR, RoleHypervisor)
add("node %s: role %q must be one of %s, %s, %s", n.Name, n.Role, RoleSwitch, RoleRR, RoleHost)
}
if !images[n.Image] {
add("node %s: image %q is not declared", n.Name, n.Image)
@ -207,13 +208,25 @@ func validateExtras(n Node, segments map[string]Segment, add func(string, ...any
}
}
}
for _, name := range sortedKeys(n.Files) {
switch {
case n.Role == RoleHypervisor && n.Release == "":
add("node %s: a hypervisor needs the release of two to deploy (release: <tag>)", n.Name)
case n.Role == RoleHypervisor && !releasePattern.MatchString(n.Release):
add("node %s: release %q must match %s", n.Name, n.Release, releasePattern)
case n.Role != RoleHypervisor && n.Release != "":
add("node %s: release is only for hypervisors", n.Name)
case !filePattern.MatchString(name):
add("node %s: file name %q must match %s", n.Name, name, filePattern)
case n.Files[name] == "":
add("node %s: file %s has no source", n.Name, name)
case strings.Contains(n.Files[name], "="):
add("node %s: file %s: source %q must not contain '='", n.Name, name, n.Files[name])
}
}
seenUnits := map[string]bool{}
for _, unit := range n.Services {
switch {
case !unitPattern.MatchString(unit):
add("node %s: service %q must match %s", n.Name, unit, unitPattern)
case seenUnits[unit]:
add("node %s: service %s listed twice", n.Name, unit)
}
seenUnits[unit] = true
}
if n.Loopback != "" {
prefix, err := netip.ParsePrefix(n.Loopback)

View file

@ -1,20 +1,21 @@
#!/usr/bin/env bash
API_URL="${SCW_API_URL:-https://api.scaleway.com}"
CREDENTIALS_FILE="${LAB_CREDENTIALS_FILE:-${HOME}/.config/two-lab/scaleway.env}"
OFFER_NAME="${LAB_OFFER:-EM-B212X-SSD}"
CREDENTIALS_FILE="${LAB_CREDENTIALS_FILE:-${HOME}/.config/labctl/scaleway.env}"
OFFER_NAME="${LAB_OFFER:-EM-B420E-NVME}"
ALL_ZONES="fr-par-1 fr-par-2 nl-ams-1 nl-ams-2 pl-waw-2 pl-waw-3"
OS_NAME="${LAB_OS_NAME:-Debian}"
OS_VERSION="${LAB_OS_VERSION:-12}"
LAB_NAME="${LAB_NAME:-two-lab}"
LAB_TAG="${LAB_TAG:-two-lab}"
LAB_NAME="${LAB_NAME:-labctl}"
LAB_TAG="${LAB_TAG:-labctl}"
INSTALL_TIMEOUT="${LAB_INSTALL_TIMEOUT:-3600}"
DELETE_TIMEOUT="${LAB_DELETE_TIMEOUT:-900}"
SSH_TIMEOUT="${LAB_SSH_TIMEOUT:-600}"
POLL_INTERVAL="${LAB_POLL_INTERVAL:-20}"
HTTP_CONNECT_TIMEOUT="${LAB_HTTP_CONNECT_TIMEOUT:-10}"
HTTP_TIMEOUT="${LAB_HTTP_TIMEOUT:-60}"
STATE_DIR="${LAB_STATE_DIR:-${HOME}/.cache/two-lab}"
SSH_KEY="${LAB_SSH_KEY:-${HOME}/.config/two-lab/ssh/lab_ed25519}"
STATE_DIR="${LAB_STATE_DIR:-${HOME}/.cache/labctl}"
SSH_KEY="${LAB_SSH_KEY:-${HOME}/.config/labctl/ssh/lab_ed25519}"
REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
CREATED_ID=""
@ -30,21 +31,23 @@ usage: ${0##*/} <commande> [arguments]
et le prix ; ne crée rien
up crée le serveur de lab, attend la fin de son installation et son SSH,
puis le prépare (voir prepare)
status liste les serveurs de lab du projet
status liste les serveurs de lab du projet, dans toutes les zones candidates
ssh [commande] se connecte au serveur de lab ; avec une commande, un terminal n'est demandé
que si l'entrée standard en est un
prepare installe sur le serveur ce dont lab a besoin (qemu, genisoimage), vérifie
/dev/kvm et la virtualisation imbriquée ; lancé aussi par up
push <topologie> compile cmd/lab pour linux/amd64 et dépose sur le serveur ~/lab et le
prepare installe sur le serveur ce dont labctl a besoin (qemu, genisoimage), vérifie
/dev/kvm, la virtualisation imbriquée et un CPU x86-64-v3 ; lancé aussi par up
push <topologie> compile cmd/labctl pour linux/amd64 et dépose sur le serveur ~/labctl et le
répertoire de la topologie dans ~/topology/ (avec les fichiers qu'elle
référence) ; ensuite : ssh './lab up topology/<topologie>'
down supprime tous les serveurs de lab du projet et attend leur disparition
référence) ; ensuite : ssh './labctl up topology/<topologie>'
down supprime tous les serveurs de lab du projet, dans toutes les zones candidates,
et attend leur disparition
session [cmd] up, puis la commande distante (ou un shell), puis down quoi qu'il arrive
environnement : SCW_SECRET_KEY et SCW_DEFAULT_PROJECT_ID (requis, à défaut lus dans ${CREDENTIALS_FILE},
fichier en 0600, lignes CLÉ=valeur), SCW_DEFAULT_ZONE (${ZONE}),
LAB_OFFER (${OFFER_NAME}), LAB_OS_NAME (${OS_NAME}), LAB_OS_VERSION (${OS_VERSION}),
LAB_SSH_KEY (${SSH_KEY} ; à défaut, l'agent SSH)
fichier en 0600, lignes CLÉ=valeur), LAB_ZONES (zones candidates, dans l'ordre :
${ZONES} ; SCW_DEFAULT_ZONE passe en tête), LAB_OFFER (${OFFER_NAME}), LAB_OS_NAME (${OS_NAME}), LAB_OS_VERSION (${OS_VERSION}),
LAB_SSH_KEY (${SSH_KEY} ; à défaut, l'agent SSH), LABCTL_BIN (binaire labctl linux/amd64
envoyé par push au lieu de le compiler depuis le dépôt)
ne jamais lancer sous 'bash -x' : la trace afficherait SCW_SECRET_KEY.
EOF
@ -64,10 +67,19 @@ load_credentials () {
esac
done < "${CREDENTIALS_FILE}"
fi
ZONE="${SCW_DEFAULT_ZONE:-fr-par-1}"
ZONES=$(candidate_zones "${SCW_DEFAULT_ZONE:-}" "${LAB_ZONES:-${ALL_ZONES}}")
ZONE="${ZONES%% *}"
PROJECT_ID="${SCW_DEFAULT_PROJECT_ID:-}"
}
candidate_zones () {
local PREFERRED="${1}" LIST="${2}" Z OUT="${1}"
for Z in ${LIST}; do
[[ " ${OUT} " == *" ${Z} "* ]] || OUT="${OUT:+${OUT} }${Z}"
done
printf '%s\n' "${OUT}"
}
require_env () {
[[ -n "${SCW_SECRET_KEY:-}" ]] || die "SCW_SECRET_KEY absent de l'environnement"
[[ -n "${PROJECT_ID}" ]] || die "SCW_DEFAULT_PROJECT_ID absent de l'environnement"
@ -124,7 +136,7 @@ resolve_offer () {
[[ $(jq -r '.stock' <<< "${OFFER}") != "empty" ]] || die "offre ${OFFER_NAME} en rupture de stock en ${ZONE}"
[[ $(jq -r '((.fee.units // 0) == 0) and ((.fee.nanos // 0) == 0)' <<< "${OFFER}") == "true" ]] \
|| die "offre ${OFFER_NAME} : frais de mise en service non nuls ($(money '.fee' <<< "${OFFER}")), refus"
printf '%s\n' "${OFFER}"
jq -c --arg z "${ZONE}" '. + {zone: $z}' <<< "${OFFER}"
}
resolve_os () {
@ -159,16 +171,23 @@ build_request () {
local KEYS="${3}"
jq -nc --argjson offer "${OFFER}" --argjson os "${OS}" --argjson keys "${KEYS}" \
--arg project "${PROJECT_ID}" --arg name "${LAB_NAME}" --arg tag "${LAB_TAG}" \
'{offer_id: $offer.id, project_id: $project, name: $name, description: "lab two (#50)",
'{offer_id: $offer.id, project_id: $project, name: $name, description: "labctl",
tags: [$tag], install: {os_id: $os.id, hostname: $name, ssh_key_ids: $keys}}'
}
lab_servers () {
local JSON
JSON=$(api GET "/baremetal/v1/zones/${ZONE}/servers?project_id=${PROJECT_ID}&tags=${LAB_TAG}&page_size=100") \
|| return 1
jq -c --arg p "${PROJECT_ID}" --arg t "${LAB_TAG}" \
'[.servers[] | select(.project_id == $p and (.tags | index($t)))]' <<< "${JSON}"
local JSON Z ALL="[]" RC=0
for Z in ${ZONES}; do
if ! JSON=$(api GET "/baremetal/v1/zones/${Z}/servers?project_id=${PROJECT_ID}&tags=${LAB_TAG}&page_size=100"); then
warn "zone ${Z} : liste des serveurs de lab indisponible"
RC=1
continue
fi
ALL=$(jq -c --argjson all "${ALL}" --arg p "${PROJECT_ID}" --arg t "${LAB_TAG}" --arg z "${Z}" \
'$all + [.servers[] | select(.project_id == $p and (.tags | index($t))) | . + {zone: $z}]' <<< "${JSON}")
done
printf '%s\n' "${ALL}"
return "${RC}"
}
server_ip () {
@ -180,12 +199,26 @@ server_is_installing () {
or (.install.status // "") == "to_install" or (.install.status // "") == "installing"' >/dev/null
}
select_zone () {
local Z OUT
for Z in ${ZONES}; do
if OUT=$(ZONE="${Z}" resolve_offer 2>&1); then
printf '%s\n' "${OUT}"
return 0
fi
warn "${Z} : ${OUT##*!! }"
done
die "offre horaire ${OFFER_NAME} disponible dans aucune zone candidate (${ZONES})"
}
cmd_plan () {
local OFFER OS KEYS
OFFER=$(resolve_offer) || exit 1
OFFER=$(select_zone) || exit 1
ZONE=$(jq -r '.zone' <<< "${OFFER}")
OS=$(resolve_os "$(jq -r '.id' <<< "${OFFER}")") || exit 1
KEYS=$(resolve_ssh_keys) || exit 1
info "offre : ${OFFER_NAME} ($(jq -r '.id' <<< "${OFFER}")), facturation $(jq -r '.subscription_period' <<< "${OFFER}"), stock $(jq -r '.stock' <<< "${OFFER}")"
info "zone : ${ZONE}"
info "offre : ${OFFER_NAME} ($(jq -r '.id' <<< "${OFFER}")), $(jq -r '[.cpus[]?.name] | unique | join(", ") | if . == "" then "CPU ?" else . end' <<< "${OFFER}"), facturation $(jq -r '.subscription_period' <<< "${OFFER}"), stock $(jq -r '.stock' <<< "${OFFER}")"
info "prix : $(money '.price_per_hour' <<< "${OFFER}") HT par heure, frais de mise en service $(money '.fee' <<< "${OFFER}")"
info "os : $(jq -r '"\(.name) \(.version) (\(.id))"' <<< "${OS}"), utilisateur $(jq -r '.user.default_value // "?"' <<< "${OS}")"
info "clés : $(jq -r 'length' <<< "${KEYS}") clé(s) SSH du projet"
@ -251,7 +284,8 @@ require_no_lab_server () {
report_uncertain_creation () {
local FOUND
if FOUND=$(lab_servers) && [[ $(jq 'length' <<< "${FOUND}") -gt 0 ]]; then
FOUND=$(lab_servers)
if [[ $(jq 'length' <<< "${FOUND}") -gt 0 ]]; then
warn "un serveur de lab existe bien : $(jq -r '[.[].id] | join(", ")' <<< "${FOUND}")"
fi
die "création incertaine : le serveur a pu être créé et être facturé ; '${0##*/} status' puis '${0##*/} down'"
@ -260,15 +294,16 @@ report_uncertain_creation () {
cmd_up () {
local OFFER OS KEYS BODY JSON ID IP SSH_USER
require_no_lab_server
OFFER=$(resolve_offer) || exit 1
OFFER=$(select_zone) || exit 1
ZONE=$(jq -r '.zone' <<< "${OFFER}")
OS=$(resolve_os "$(jq -r '.id' <<< "${OFFER}")") || exit 1
KEYS=$(resolve_ssh_keys) || exit 1
BODY=$(build_request "${OFFER}" "${OS}" "${KEYS}")
info "création de ${LAB_NAME} (${OFFER_NAME}, $(money '.price_per_hour' <<< "${OFFER}")/h HT)"
info "création de ${LAB_NAME} (${OFFER_NAME}, ${ZONE}, $(money '.price_per_hour' <<< "${OFFER}")/h HT)"
JSON=$(api POST "/baremetal/v1/zones/${ZONE}/servers" "${BODY}") || report_uncertain_creation
ID=$(jq -r '.id // empty' <<< "${JSON}" 2>/dev/null)
[[ -n "${ID}" ]] || report_uncertain_creation
CREATED_ID="${ID}"
CREATED_ID="${ZONE} ${ID}"
info "serveur ${ID} créé, facturé jusqu'à '${0##*/} down'"
JSON=$(wait_installed "${ID}") || die "serveur ${ID} inutilisable — il est toujours facturé : '${0##*/} down'"
IP=$(server_ip <<< "${JSON}")
@ -283,13 +318,14 @@ cmd_up () {
}
cmd_status () {
local SERVERS
SERVERS=$(lab_servers) || die "impossible de lister les serveurs de lab"
local SERVERS RC=0
SERVERS=$(lab_servers) || RC=1
if [[ $(jq 'length' <<< "${SERVERS}") -eq 0 ]]; then
info "aucun serveur de lab dans le projet ${PROJECT_ID} (${ZONE})"
return 0
[[ "${RC}" -eq 0 ]] && info "aucun serveur de lab dans le projet ${PROJECT_ID} (${ZONES})"
else
jq -r '.[] | "\(.zone) \(.id) \(.name) \(.offer_name) \(.status) installation \(.install.status // "none") \(.created_at) \([.ips[] | select(.version == "IPv4") | .address] | join(","))"' <<< "${SERVERS}"
fi
jq -r '.[] | "\(.id) \(.name) \(.offer_name) \(.status) installation \(.install.status // "none") \(.created_at) \([.ips[] | select(.version == "IPv4") | .address] | join(","))"' <<< "${SERVERS}"
[[ "${RC}" -eq 0 ]] || die "liste incomplète : des serveurs de lab peuvent exister dans les zones en erreur"
}
require_known_server () {
@ -319,13 +355,18 @@ case "${NESTED}" in
Y|1) ;;
*) echo "virtualisation imbriquée désactivée (nested=${NESTED:-absent})" >&2; exit 1 ;;
esac
echo "qemu $(qemu-system-x86_64 --version | head -n 1), nested=${NESTED}"
LD=$(ls /lib64/ld-linux-x86-64.so.2 /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 2>/dev/null | head -n 1)
if ! "${LD}" --help 2>/dev/null | grep -q 'x86-64-v3 (supported'; then
echo "CPU sans x86-64-v3 :$(grep -m 1 'model name' /proc/cpuinfo | cut -d: -f2) — Rocky 10 / RHEL 10 n'y démarrent pas" >&2
exit 1
fi
echo "qemu $(qemu-system-x86_64 --version | head -n 1), nested=${NESTED},$(grep -m 1 'model name' /proc/cpuinfo | cut -d: -f2)"
EOF
}
cmd_prepare () {
require_known_server
info "préparation du serveur : qemu, genisoimage, KVM imbriqué"
info "préparation du serveur : qemu, genisoimage, KVM imbriqué, CPU x86-64-v3"
prepare_script | ssh_run -- bash -s
}
@ -343,17 +384,23 @@ push_dir () {
cmd_push () {
local TOPOLOGY="${1:-}"
local NAME="${TOPOLOGY##*/}"
local BINARY="${STATE_DIR}/lab"
local BINARY="${STATE_DIR}/labctl"
[[ $# -eq 1 && -n "${TOPOLOGY}" ]] || usage
[[ -f "${TOPOLOGY}" ]] || die "topologie introuvable : ${TOPOLOGY}"
[[ "${NAME}" =~ ^[A-Za-z0-9._-]+$ ]] || die "nom de topologie refusé : ${NAME} (lettres, chiffres, '.', '_', '-')"
require_known_server
info "compilation de lab (linux/amd64)"
(cd "${REPO_DIR}" && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o "${BINARY}" ./cmd/lab) \
|| die "compilation de lab échouée"
push_file "${BINARY}" lab 755 || die "envoi de lab échoué"
if [[ -n "${LABCTL_BIN:-}" ]]; then
[[ -f "${LABCTL_BIN}" && -x "${LABCTL_BIN}" ]] || die "LABCTL_BIN n'est pas un exécutable : ${LABCTL_BIN}"
BINARY="${LABCTL_BIN}"
info "labctl fourni : ${BINARY}"
else
info "compilation de labctl (linux/amd64)"
(cd "${REPO_DIR}" && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o "${BINARY}" ./cmd/labctl) \
|| die "compilation de labctl échouée"
fi
push_file "${BINARY}" labctl 755 || die "envoi de labctl échoué"
push_dir "$(dirname "${TOPOLOGY}")" || die "envoi du répertoire de ${NAME} échoué"
info "déposés sur le serveur : ~/lab, ~/topology/ — ensuite : ${0##*/} ssh './lab up topology/${NAME}'"
info "déposés sur le serveur : ~/labctl, ~/topology/ — ensuite : ${0##*/} ssh './labctl up topology/${NAME}'"
}
delete_server () {
@ -390,28 +437,29 @@ wait_gone () {
lab_server_ids () {
local DEADLINE=$(( SECONDS + DELETE_TIMEOUT ))
local SERVERS
local SERVERS="[]"
while (( SECONDS < DEADLINE )); do
if SERVERS=$(lab_servers); then
jq -r '.[].id' <<< "${SERVERS}"
jq -r '.[] | "\(.zone) \(.id)"' <<< "${SERVERS}"
return 0
fi
warn "liste des serveurs de lab indisponible, nouvel essai dans ${POLL_INTERVAL}s"
warn "liste des serveurs de lab incomplète, nouvel essai dans ${POLL_INTERVAL}s"
sleep "${POLL_INTERVAL}"
done
jq -r '.[] | "\(.zone) \(.id)"' <<< "${SERVERS}"
return 1
}
cmd_down () {
local IDS ID FAILED=0
if ! IDS=$(lab_server_ids); then
warn "impossible de lister les serveurs de lab après ${DELETE_TIMEOUT}s"
warn "liste des serveurs de lab incomplète après ${DELETE_TIMEOUT}s : suppression de ceux qui sont listés"
FAILED=1
IDS=""
fi
IDS=$(printf '%s\n%s\n' "${IDS}" "${CREATED_ID}" | grep -v '^$' | sort -u)
for ID in ${IDS}; do
info "suppression de ${ID}"
while read -r ZONE ID; do
[[ -n "${ID}" ]] || continue
info "suppression de ${ID} (${ZONE})"
if ! delete_server "${ID}"; then
warn "suppression de ${ID} toujours refusée"
FAILED=1
@ -421,7 +469,7 @@ cmd_down () {
warn "${ID} toujours présent après ${DELETE_TIMEOUT}s"
FAILED=1
fi
done
done <<< "${IDS}"
rm -f "${STATE_DIR}/ip" "${STATE_DIR}/user" "${STATE_DIR}/known_hosts"
[[ "${FAILED}" -eq 0 ]] || die "SERVEUR(S) DE LAB TOUJOURS FACTURÉ(S) — '${0##*/} status', puis la console Scaleway"
info "aucun serveur de lab ne reste dans le projet"

View file

@ -63,18 +63,22 @@ with open(os.path.join(d, "calls.log"), "a") as f:
if "X-Auth-Token: " + os.environ["FAKE_SECRET"] not in headers:
reply(401, {"message": "unauthorized"})
zone = "/baremetal/v1/zones/fr-par-1"
zname = path.split("/")[4] if path.startswith("/baremetal/v1/zones/") else ""
zone = "/baremetal/v1/zones/" + zname
if method == "GET" and path == zone + "/offers":
reply(200, {"offers": st["offers"], "total_count": len(st["offers"])})
offers = st.get("zones", {}).get(zname, {}).get("offers", st["offers"] if zname == "fr-par-1" else [])
reply(200, {"offers": offers, "total_count": len(offers)})
if method == "GET" and path == zone + "/os":
reply(200, {"os": st["os"], "total_count": len(st["os"])})
if method == "GET" and path == "/iam/v1alpha1/ssh-keys":
reply(200, {"ssh_keys": st["keys"], "total_count": len(st["keys"])})
if method == "GET" and path == zone + "/servers":
if st.get("zones", {}).get(zname, {}).get("list_fail"):
reply(503, {"message": "service unavailable"})
if st["list_errors"] > 0:
st["list_errors"] -= 1
reply(503, {"message": "service unavailable"})
listed = [v for v in st["servers"].values() if not v.get("hidden")]
listed = [v for v in st["servers"].values() if not v.get("hidden") and v.get("zone", "fr-par-1") == zname]
reply(200, {"servers": listed, "total_count": len(listed)})
if method == "POST" and path == zone + "/servers":
req = json.loads(body)
@ -84,7 +88,7 @@ if method == "POST" and path == zone + "/servers":
sid = "srv-%d" % st["seq"]
st["servers"][sid] = {"id": sid, "name": req["name"], "project_id": req["project_id"],
"tags": req["tags"], "offer_name": "EM-B212X-SSD", "status": "delivering",
"install": {"status": "to_install"}, "ips": [], "created_at": "now",
"install": {"status": "to_install"}, "ips": [], "created_at": "now", "zone": zname,
"hidden": st["hide_from_list"]}
if st["post_fail_after_create"]:
reply(502, {"message": "bad gateway"})
@ -93,7 +97,7 @@ if method == "POST" and path == zone + "/servers":
reply(200, st["servers"][sid])
if path.startswith(zone + "/servers/"):
sid = path.rsplit("/", 1)[1]
if sid not in st["servers"]:
if sid not in st["servers"] or st["servers"][sid].get("zone", "fr-par-1") != zname:
reply(404, {"message": "not found"})
srv = st["servers"][sid]
if method == "GET" and st["get_errors"] > 0:
@ -189,7 +193,7 @@ base_state () {
],
keys: [{id: "key-1", disabled: false}, {id: "key-off", disabled: true}],
servers: {
"foreign-1": {id: "foreign-1", name: "prod-db", project_id: $o, tags: ["two-lab"], status: "ready", install: {status: "completed"}, ips: []},
"foreign-1": {id: "foreign-1", name: "prod-db", project_id: $o, tags: ["labctl"], status: "ready", install: {status: "completed"}, ips: []},
"foreign-2": {id: "foreign-2", name: "autre", project_id: $p, tags: ["autre"], status: "ready", install: {status: "completed"}, ips: []}
}
}'
@ -222,7 +226,8 @@ lab_env () {
SCW_API_URL="https://api.example.invalid" SCW_SECRET_KEY="${SECRET}" \
SCW_DEFAULT_PROJECT_ID="${PROJECT}" LAB_POLL_INTERVAL="${LAB_POLL_INTERVAL:-0}" \
LAB_INSTALL_TIMEOUT="${LAB_INSTALL_TIMEOUT:-60}" LAB_DELETE_TIMEOUT="${LAB_DELETE_TIMEOUT:-60}" \
LAB_SSH_TIMEOUT="${LAB_SSH_TIMEOUT:-60}" \
LAB_SSH_TIMEOUT="${LAB_SSH_TIMEOUT:-60}" LAB_ZONES="${LAB_ZONES:-fr-par-1}" \
LAB_OFFER="${LAB_OFFER:-EM-B212X-SSD}" ${SCW_DEFAULT_ZONE:+SCW_DEFAULT_ZONE="${SCW_DEFAULT_ZONE}"} ${LABCTL_BIN:+LABCTL_BIN="${LABCTL_BIN}"} \
"$@"
}
@ -300,16 +305,16 @@ test_up_creates_and_waits_for_installation () {
mutate '.progress = [["delivering","to_install"],["ready","installing"],["ready","completed"]]'
run_lab up || fail "code de sortie $?"
[[ $(jq -r '.offer_id' "${WORK}/create.json") == "${HOURLY_ID}" ]] || fail "offre créée incorrecte"
[[ $(jq -r '.tags | join(",")' "${WORK}/create.json") == "two-lab" ]] || fail "tag absent"
[[ $(jq -r '.tags | join(",")' "${WORK}/create.json") == "labctl" ]] || fail "tag absent"
[[ $(jq -r '.project_id' "${WORK}/create.json") == "${PROJECT}" ]] || fail "projet incorrect"
[[ $(cat "${WORK}/.cache/two-lab/ip" 2>/dev/null) == "203.0.113.7" ]] || fail "IPv4 non retenue"
[[ $(cat "${WORK}/.cache/two-lab/user" 2>/dev/null) == "debian" ]] || fail "utilisateur non retenu"
[[ $(cat "${WORK}/.cache/labctl/ip" 2>/dev/null) == "203.0.113.7" ]] || fail "IPv4 non retenue"
[[ $(cat "${WORK}/.cache/labctl/user" 2>/dev/null) == "debian" ]] || fail "utilisateur non retenu"
teardown
}
test_up_refuses_when_lab_server_exists () {
setup "up : refus si un serveur de lab existe déjà"
mutate '.servers["srv-old"] = {id: "srv-old", name: "two-lab", project_id: "'"${PROJECT}"'", tags: ["two-lab"], status: "ready", install: {status: "completed"}, ips: []}'
mutate '.servers["srv-old"] = {id: "srv-old", name: "labctl", project_id: "'"${PROJECT}"'", tags: ["labctl"], status: "ready", install: {status: "completed"}, ips: []}'
run_lab up && fail "up a réussi"
grep -q "^POST" "${WORK}/calls.log" && fail "second serveur créé"
teardown
@ -326,7 +331,7 @@ test_secret_never_in_argv () {
test_down_deletes_only_lab_servers_of_project () {
setup "down : ne supprime que les serveurs de lab du projet"
mutate '.servers["srv-lab"] = {id: "srv-lab", name: "two-lab", project_id: "'"${PROJECT}"'", tags: ["two-lab"], status: "ready", install: {status: "completed"}, ips: []}'
mutate '.servers["srv-lab"] = {id: "srv-lab", name: "labctl", project_id: "'"${PROJECT}"'", tags: ["labctl"], status: "ready", install: {status: "completed"}, ips: []}'
run_lab down || fail "code de sortie $?"
[[ $(remaining) == "foreign-1,foreign-2" ]] || fail "restants : $(remaining)"
teardown
@ -334,7 +339,7 @@ test_down_deletes_only_lab_servers_of_project () {
test_down_retries_refused_deletion () {
setup "down : réessaie une suppression refusée"
mutate '.delete_refusals = 2 | .servers["srv-lab"] = {id: "srv-lab", name: "two-lab", project_id: "'"${PROJECT}"'", tags: ["two-lab"], status: "ready", install: {status: "installing"}, ips: []}'
mutate '.delete_refusals = 2 | .servers["srv-lab"] = {id: "srv-lab", name: "labctl", project_id: "'"${PROJECT}"'", tags: ["labctl"], status: "ready", install: {status: "installing"}, ips: []}'
run_lab down || fail "code de sortie $?"
[[ $(grep -c "^DELETE" "${WORK}/calls.log") -eq 3 ]] || fail "$(grep -c "^DELETE" "${WORK}/calls.log") DELETE au lieu de 3"
[[ $(remaining) == "foreign-1,foreign-2" ]] || fail "restants : $(remaining)"
@ -343,7 +348,7 @@ test_down_retries_refused_deletion () {
test_down_fails_loudly_when_deletion_keeps_failing () {
setup "down : échec bruyant si la suppression n'aboutit jamais"
mutate '.delete_refusals = 1000 | .servers["srv-lab"] = {id: "srv-lab", name: "two-lab", project_id: "'"${PROJECT}"'", tags: ["two-lab"], status: "ready", install: {status: "installing"}, ips: []}'
mutate '.delete_refusals = 1000 | .servers["srv-lab"] = {id: "srv-lab", name: "labctl", project_id: "'"${PROJECT}"'", tags: ["labctl"], status: "ready", install: {status: "installing"}, ips: []}'
LAB_DELETE_TIMEOUT=1 run_lab down && fail "down a réussi"
grep -q "TOUJOURS FACTURÉ" "${WORK}/out.log" || fail "pas d'alerte de facturation"
teardown
@ -351,7 +356,7 @@ test_down_fails_loudly_when_deletion_keeps_failing () {
test_down_waits_until_server_is_gone () {
setup "down : attend que le serveur ait disparu"
mutate '.linger = 3 | .servers["srv-lab"] = {id: "srv-lab", name: "two-lab", project_id: "'"${PROJECT}"'", tags: ["two-lab"], status: "ready", install: {status: "completed"}, ips: []}'
mutate '.linger = 3 | .servers["srv-lab"] = {id: "srv-lab", name: "labctl", project_id: "'"${PROJECT}"'", tags: ["labctl"], status: "ready", install: {status: "completed"}, ips: []}'
run_lab down || fail "code de sortie $?"
[[ $(grep -c "^GET /baremetal/v1/zones/fr-par-1/servers/srv-lab$" "${WORK}/calls.log") -ge 4 ]] || fail "disparition non attendue"
[[ $(remaining) == "foreign-1,foreign-2" ]] || fail "restants : $(remaining)"
@ -360,7 +365,7 @@ test_down_waits_until_server_is_gone () {
test_down_fails_loudly_when_server_never_disappears () {
setup "down : échec bruyant si le serveur ne disparaît jamais"
mutate '.linger = 100000 | .servers["srv-lab"] = {id: "srv-lab", name: "two-lab", project_id: "'"${PROJECT}"'", tags: ["two-lab"], status: "ready", install: {status: "completed"}, ips: []}'
mutate '.linger = 100000 | .servers["srv-lab"] = {id: "srv-lab", name: "labctl", project_id: "'"${PROJECT}"'", tags: ["labctl"], status: "ready", install: {status: "completed"}, ips: []}'
LAB_DELETE_TIMEOUT=1 run_lab down && fail "down a réussi"
grep -q "TOUJOURS FACTURÉ" "${WORK}/out.log" || fail "pas d'alerte de facturation"
teardown
@ -368,7 +373,7 @@ test_down_fails_loudly_when_server_never_disappears () {
test_down_does_not_mistake_api_error_for_disappearance () {
setup "down : une erreur de l'API n'est pas prise pour une disparition"
mutate '.linger = 100000 | .get_errors = 1 | .servers["srv-lab"] = {id: "srv-lab", name: "two-lab", project_id: "'"${PROJECT}"'", tags: ["two-lab"], status: "ready", install: {status: "completed"}, ips: []}'
mutate '.linger = 100000 | .get_errors = 1 | .servers["srv-lab"] = {id: "srv-lab", name: "labctl", project_id: "'"${PROJECT}"'", tags: ["labctl"], status: "ready", install: {status: "completed"}, ips: []}'
LAB_DELETE_TIMEOUT=1 run_lab down && fail "down a réussi alors que le serveur existe encore"
grep -q "TOUJOURS FACTURÉ" "${WORK}/out.log" || fail "pas d'alerte de facturation"
teardown
@ -412,7 +417,7 @@ test_session_deletes_server_when_installation_times_out () {
test_session_does_not_touch_existing_lab_server () {
setup "session : ne supprime pas un serveur de lab lancé à côté"
mutate '.servers["srv-old"] = {id: "srv-old", name: "two-lab", project_id: "'"${PROJECT}"'", tags: ["two-lab"], status: "ready", install: {status: "completed"}, ips: []}'
mutate '.servers["srv-old"] = {id: "srv-old", name: "labctl", project_id: "'"${PROJECT}"'", tags: ["labctl"], status: "ready", install: {status: "completed"}, ips: []}'
run_lab session true && fail "session a réussi"
grep -q "^DELETE" "${WORK}/calls.log" && fail "suppression lancée"
[[ $(remaining) == "foreign-1,foreign-2,srv-old" ]] || fail "restants : $(remaining)"
@ -427,8 +432,8 @@ test_missing_credentials_are_refused_before_any_call () {
teardown
}
LAB_SERVER='{id: "srv-lab", name: "two-lab", project_id: "'"${PROJECT}"'", tags: ["two-lab"], status: "ready", install: {status: "completed"}, ips: []}'
INSTALLING_LAB_SERVER='{id: "srv-lab", name: "two-lab", project_id: "'"${PROJECT}"'", tags: ["two-lab"], status: "ready", install: {status: "installing"}, ips: []}'
LAB_SERVER='{id: "srv-lab", name: "labctl", project_id: "'"${PROJECT}"'", tags: ["labctl"], status: "ready", install: {status: "completed"}, ips: []}'
INSTALLING_LAB_SERVER='{id: "srv-lab", name: "labctl", project_id: "'"${PROJECT}"'", tags: ["labctl"], status: "ready", install: {status: "installing"}, ips: []}'
test_down_keeps_retrying_while_server_is_installing () {
setup "down : réessaie au-delà du délai tant que le serveur s'installe"
@ -467,6 +472,33 @@ test_down_fails_loudly_when_listing_never_works () {
teardown
}
test_down_deletes_what_answering_zones_list_when_one_zone_fails () {
setup "down : une zone en erreur n'empêche pas de supprimer les serveurs des autres"
mutate ".servers[\"srv-lab\"] = ${LAB_SERVER} | .zones = {\"nl-ams-2\": {list_fail: true}}"
LAB_ZONES="fr-par-1 nl-ams-2" LAB_DELETE_TIMEOUT=1 run_lab down && fail "down a réussi malgré une zone en erreur"
[[ $(remaining) == "foreign-1,foreign-2" ]] || fail "restants : $(remaining)"
grep -q "zone nl-ams-2" "${WORK}/out.log" || fail "zone en erreur non signalée"
grep -q "TOUJOURS FACTURÉ" "${WORK}/out.log" || fail "pas d'alerte de facturation"
teardown
}
test_status_lists_answering_zones_and_fails_when_one_zone_fails () {
setup "status : liste les zones qui répondent, échoue si une zone est en erreur"
mutate ".servers[\"srv-lab\"] = ${LAB_SERVER} | .zones = {\"nl-ams-2\": {list_fail: true}}"
LAB_ZONES="fr-par-1 nl-ams-2" run_lab status && fail "status a réussi malgré une zone en erreur"
grep -q "^fr-par-1 srv-lab " "${WORK}/out.log" || fail "srv-lab non listé"
grep -q "liste incomplète" "${WORK}/out.log" || fail "liste incomplète non signalée"
teardown
}
test_up_refuses_when_one_zone_cannot_be_listed () {
setup "up : refus si une zone ne peut pas être listée"
mutate '.zones = {"nl-ams-2": {list_fail: true}} | .progress = [["ready","completed"]]'
LAB_ZONES="fr-par-1 nl-ams-2" run_lab up && fail "up a réussi"
grep -q "^POST" "${WORK}/calls.log" && fail "serveur créé sans connaître toutes les zones"
teardown
}
test_session_deletes_created_server_even_if_missing_from_list () {
setup "session : supprime le serveur créé même absent de la liste"
mutate '.hide_from_list = true | .progress = [["ready","completed"]]'
@ -587,11 +619,11 @@ test_session_deletes_server_when_ssh_never_answers () {
test_ssh_uses_dedicated_lab_key_only_when_present () {
setup "ssh : clé dédiée du lab utilisée seule quand elle existe"
mutate '.progress = [["ready","completed"]]'
mkdir -p "${WORK}/.config/two-lab/ssh"
: > "${WORK}/.config/two-lab/ssh/lab_ed25519"
mkdir -p "${WORK}/.config/labctl/ssh"
: > "${WORK}/.config/labctl/ssh/lab_ed25519"
run_lab session uname || fail "code de sortie $?"
grep -q " uname" "${WORK}/ssh.log" || fail "commande non lancée"
[[ $(grep -c -- "-i ${WORK}/.config/two-lab/ssh/lab_ed25519 -o IdentitiesOnly=yes -o IdentityAgent=none" "${WORK}/ssh.log") -eq $(wc -l < "${WORK}/ssh.log") ]] \
[[ $(grep -c -- "-i ${WORK}/.config/labctl/ssh/lab_ed25519 -o IdentitiesOnly=yes -o IdentityAgent=none" "${WORK}/ssh.log") -eq $(wc -l < "${WORK}/ssh.log") ]] \
|| fail "une connexion n'a pas utilisé la clé dédiée seule"
teardown
}
@ -606,10 +638,10 @@ test_ssh_falls_back_to_agent_without_lab_key () {
}
known_server () {
mkdir -p "${WORK}/.cache/two-lab"
echo 203.0.113.7 > "${WORK}/.cache/two-lab/ip"
echo debian > "${WORK}/.cache/two-lab/user"
: > "${WORK}/.cache/two-lab/known_hosts"
mkdir -p "${WORK}/.cache/labctl"
echo 203.0.113.7 > "${WORK}/.cache/labctl/ip"
echo debian > "${WORK}/.cache/labctl/user"
: > "${WORK}/.cache/labctl/known_hosts"
}
test_up_prepares_the_server_after_ssh () {
@ -659,7 +691,7 @@ test_prepare_without_known_server_is_refused () {
}
test_push_builds_for_linux_and_sends_binary_and_topology () {
setup "push : compile lab pour linux/amd64, envoie le binaire et le répertoire de la topologie"
setup "push : compile labctl pour linux/amd64, envoie le binaire et le répertoire de la topologie"
known_server
mkdir -p "${WORK}/conf/frr"
printf 'name: evpn-2hv\n' > "${WORK}/conf/evpn-2hv.yml"
@ -668,9 +700,9 @@ test_push_builds_for_linux_and_sends_binary_and_topology () {
run_lab push "${WORK}/conf/evpn-2hv.yml" || fail "code de sortie $?"
local REPO LISTING
REPO="$(cd "$(dirname "${SCRIPT}")/.." && pwd)"
[[ $(cat "${WORK}/go.log") == "${REPO}|build -o ${WORK}/.cache/two-lab/lab ./cmd/lab|CGO_ENABLED=0 GOOS=linux GOARCH=amd64" ]] \
[[ $(cat "${WORK}/go.log") == "${REPO}|build -o ${WORK}/.cache/labctl/labctl ./cmd/labctl|CGO_ENABLED=0 GOOS=linux GOARCH=amd64" ]] \
|| fail "compilation : $(cat "${WORK}/go.log")"
grep -q "debian@203.0.113.7 cat > 'lab.part' && chmod 755 'lab.part' && mv 'lab.part' 'lab'" "${WORK}/ssh.log" || fail "envoi de lab absent"
grep -q "debian@203.0.113.7 cat > 'labctl.part' && chmod 755 'labctl.part' && mv 'labctl.part' 'labctl'" "${WORK}/ssh.log" || fail "envoi de labctl absent"
grep -q "debian@203.0.113.7 rm -rf topology.part && mkdir topology.part && tar -C topology.part --no-same-owner -xf - && rm -rf topology && mv topology.part topology" "${WORK}/ssh.log" \
|| fail "envoi du répertoire absent"
[[ $(cat "${WORK}/pushed.1") == "binaire-lab" ]] || fail "contenu de lab : $(cat "${WORK}/pushed.1")"
@ -679,7 +711,7 @@ test_push_builds_for_linux_and_sends_binary_and_topology () {
grep -aq 'LIBARCHIVE.xattr' "${WORK}/pushed.2" && fail "attributs étendus macOS dans l'archive"
mkdir "${WORK}/x" && tar -C "${WORK}/x" -xf "${WORK}/pushed.2"
[[ $(cat "${WORK}/x/frr/rr1.conf") == "hostname rr1" ]] || fail "frr/rr1.conf altéré"
grep -q "ssh './lab up topology/evpn-2hv.yml'" "${WORK}/out.log" || fail "consigne finale absente"
grep -q "ssh './labctl up topology/evpn-2hv.yml'" "${WORK}/out.log" || fail "consigne finale absente"
teardown
}
@ -689,7 +721,32 @@ test_push_stops_when_the_build_fails () {
printf 'name: x\n' > "${WORK}/x.yml"
FAKE_GO_FAIL=1 run_lab push "${WORK}/x.yml" && fail "push a réussi"
[[ -s "${WORK}/ssh.log" ]] && fail "ssh lancé"
grep -q "compilation de lab échouée" "${WORK}/out.log" || fail "message absent"
grep -q "compilation de labctl échouée" "${WORK}/out.log" || fail "message absent"
teardown
}
test_push_sends_a_provided_binary_without_building () {
setup "push : LABCTL_BIN est envoyé tel quel, sans compilation"
known_server
printf 'name: x\n' > "${WORK}/x.yml"
printf 'binaire-de-release' > "${WORK}/labctl-release"
chmod 755 "${WORK}/labctl-release"
LABCTL_BIN="${WORK}/labctl-release" run_lab push "${WORK}/x.yml" || fail "code de sortie $?"
[[ -s "${WORK}/go.log" ]] && fail "compilation lancée : $(cat "${WORK}/go.log")"
[[ $(cat "${WORK}/pushed.1") == "binaire-de-release" ]] || fail "contenu envoyé : $(cat "${WORK}/pushed.1")"
teardown
}
test_push_refuses_a_provided_binary_that_is_not_executable () {
setup "push : LABCTL_BIN absent ou non exécutable refusé avant tout envoi"
known_server
printf 'name: x\n' > "${WORK}/x.yml"
printf 'x' > "${WORK}/labctl-release"
for BIN in "${WORK}/absent" "${WORK}/labctl-release"; do
LABCTL_BIN="${BIN}" run_lab push "${WORK}/x.yml" && fail "push a réussi avec ${BIN}"
grep -q "LABCTL_BIN n'est pas un exécutable" "${WORK}/out.log" || fail "message absent pour ${BIN}"
done
[[ -s "${WORK}/ssh.log" ]] && fail "ssh lancé"
teardown
}
@ -698,7 +755,7 @@ test_push_fails_when_a_transfer_fails () {
known_server
printf 'name: x\n' > "${WORK}/x.yml"
FAKE_PUSH_RC=1 run_lab push "${WORK}/x.yml" && fail "push a réussi"
grep -q "envoi de lab échoué" "${WORK}/out.log" || fail "message absent"
grep -q "envoi de labctl échoué" "${WORK}/out.log" || fail "message absent"
teardown
}
@ -721,8 +778,8 @@ test_push_refusals () {
test_ssh_without_terminal_does_not_ask_for_one () {
setup "ssh : pas de -t quand l'entrée n'est pas un terminal"
known_server
run_lab ssh './lab status' < /dev/null || fail "code de sortie $?"
[[ $(cat "${WORK}/ssh.log") == *"debian@203.0.113.7 ./lab status" ]] || fail "commande : $(cat "${WORK}/ssh.log")"
run_lab ssh './labctl status' < /dev/null || fail "code de sortie $?"
[[ $(cat "${WORK}/ssh.log") == *"debian@203.0.113.7 ./labctl status" ]] || fail "commande : $(cat "${WORK}/ssh.log")"
grep -q -- " -t " "${WORK}/ssh.log" && fail "-t demandé sans terminal"
teardown
}
@ -730,13 +787,13 @@ test_ssh_without_terminal_does_not_ask_for_one () {
run_lab_without_env_credentials () {
env -i PATH="${WORK}/bin:${PATH}" HOME="${WORK}" TMPDIR="${TMPDIR:-/tmp}" \
FAKE_DIR="${WORK}" FAKE_SECRET="${SECRET}" SCW_API_URL="https://api.example.invalid" \
LAB_POLL_INTERVAL=0 "$@" bash "${SCRIPT}" plan > "${WORK}/out.log" 2>&1
LAB_POLL_INTERVAL=0 LAB_ZONES=fr-par-1 LAB_OFFER=EM-B212X-SSD "$@" bash "${SCRIPT}" plan > "${WORK}/out.log" 2>&1
}
write_credentials () {
mkdir -p "${WORK}/.config/two-lab"
printf '%s\n' "$@" > "${WORK}/.config/two-lab/scaleway.env"
chmod 600 "${WORK}/.config/two-lab/scaleway.env"
mkdir -p "${WORK}/.config/labctl"
printf '%s\n' "$@" > "${WORK}/.config/labctl/scaleway.env"
chmod 600 "${WORK}/.config/labctl/scaleway.env"
}
test_credentials_file_is_used_when_environment_is_empty () {
@ -750,9 +807,9 @@ test_credentials_file_is_used_when_environment_is_empty () {
test_credentials_file_without_final_newline_is_read () {
setup "identifiants : dernière ligne sans retour à la ligne lue quand même"
mkdir -p "${WORK}/.config/two-lab"
printf 'SCW_DEFAULT_PROJECT_ID=%s\nSCW_SECRET_KEY=%s' "${PROJECT}" "${SECRET}" > "${WORK}/.config/two-lab/scaleway.env"
chmod 600 "${WORK}/.config/two-lab/scaleway.env"
mkdir -p "${WORK}/.config/labctl"
printf 'SCW_DEFAULT_PROJECT_ID=%s\nSCW_SECRET_KEY=%s' "${PROJECT}" "${SECRET}" > "${WORK}/.config/labctl/scaleway.env"
chmod 600 "${WORK}/.config/labctl/scaleway.env"
run_lab_without_env_credentials || fail "code de sortie $?"
teardown
}
@ -776,7 +833,7 @@ test_environment_value_kept_when_file_completes_the_rest () {
test_credentials_file_readable_by_others_is_refused () {
setup "identifiants : fichier lisible par d'autres refusé, sans aucun appel"
write_credentials "SCW_SECRET_KEY=${SECRET}" "SCW_DEFAULT_PROJECT_ID=${PROJECT}"
chmod 644 "${WORK}/.config/two-lab/scaleway.env"
chmod 644 "${WORK}/.config/labctl/scaleway.env"
run_lab_without_env_credentials && fail "plan a réussi"
grep -q "chmod 600" "${WORK}/out.log" || fail "pas de consigne de droits"
[[ -s "${WORK}/calls.log" ]] && fail "appel réseau avec un fichier exposé"
@ -814,6 +871,74 @@ signal_during_session () {
teardown
}
zone_offer () {
jq -n --arg id "${1}" --arg stock "${2}" '{id: $id, name: "EM-B420E-NVME", subscription_period: "hourly", enable: true,
stock: $stock, cpus: [{name: "AMD EPYC 7272"}], price_per_hour: {currency_code: "EUR", units: 0, nanos: 444000000},
fee: {currency_code: "EUR", units: 0, nanos: 0}}'
}
test_default_offer_is_the_epyc_one () {
setup "offre par défaut : EM-B420E-NVME"
LAB_OFFER=EM-B420E-NVME run_lab plan
grep -q 'aucune zone candidate' "${WORK}/out.log" || fail "l'offre EM-B420E-NVME n'a pas été cherchée"
grep -q 'name=EM-B420E-NVME' "${WORK}/calls.log" || fail "requête : $(cat "${WORK}/calls.log")"
[[ $(env -i bash -c ". '${SCRIPT}'; echo \${OFFER_NAME}") == EM-B420E-NVME ]] \
|| fail "défaut lu : $(env -i bash -c ". '${SCRIPT}'; echo \${OFFER_NAME}")"
teardown
}
test_up_takes_the_first_zone_with_stock () {
setup "up : première zone candidate où l'offre est en stock"
mutate ".zones = {\"fr-par-2\": {offers: [$(zone_offer off-par2 empty)]}, \"nl-ams-2\": {offers: [$(zone_offer off-ams2 available)]}}
| .progress = [[\"ready\", \"completed\"]]"
LAB_ZONES="fr-par-2 nl-ams-2 pl-waw-3" LAB_OFFER=EM-B420E-NVME run_lab up
grep -q 'POST /baremetal/v1/zones/nl-ams-2/servers' "${WORK}/calls.log" || fail "pas de création en nl-ams-2 : $(grep POST "${WORK}/calls.log")"
grep -q 'zones/pl-waw-3/offers' "${WORK}/calls.log" && fail "zone suivante interrogée après avoir trouvé du stock"
[[ $(jq -r '.offer_id' "${WORK}/create.json") == off-ams2 ]] || fail "offre créée : $(jq -c . "${WORK}/create.json")"
grep -q 'fr-par-2 : offre EM-B420E-NVME en rupture de stock' "${WORK}/out.log" || fail "raison du refus de fr-par-2 absente"
teardown
}
test_preferred_zone_goes_first () {
setup "SCW_DEFAULT_ZONE : préférence placée en tête, sans exclure les autres"
[[ $(lab_env bash -c ". '${SCRIPT}'; candidate_zones nl-ams-2 'fr-par-1 nl-ams-2 pl-waw-3'") == "nl-ams-2 fr-par-1 pl-waw-3" ]] \
|| fail "ordre : $(lab_env bash -c ". '${SCRIPT}'; candidate_zones nl-ams-2 'fr-par-1 nl-ams-2 pl-waw-3'")"
[[ $(lab_env bash -c ". '${SCRIPT}'; candidate_zones '' 'fr-par-1 nl-ams-2'") == "fr-par-1 nl-ams-2" ]] || fail "sans préférence"
teardown
}
test_no_zone_with_stock_is_refused_without_creation () {
setup "aucune zone en stock : refus, rien n'est créé"
LAB_ZONES="fr-par-2 nl-ams-2" LAB_OFFER=EM-B420E-NVME run_lab up && fail "code de retour nul"
grep -q 'disponible dans aucune zone candidate (fr-par-2 nl-ams-2)' "${WORK}/out.log" || fail "message absent"
grep -q '^POST' "${WORK}/calls.log" && fail "serveur créé"
teardown
}
test_down_and_status_cover_every_candidate_zone () {
setup "down et status : serveurs de lab de toutes les zones candidates"
mutate ".servers[\"lab-ams\"] = {id: \"lab-ams\", name: \"labctl\", project_id: \"${PROJECT}\", tags: [\"labctl\"],
status: \"ready\", install: {status: \"completed\"}, ips: [], zone: \"nl-ams-2\", offer_name: \"EM-B420E-NVME\", created_at: \"now\"}"
mutate ".servers[\"lab-par\"] = {id: \"lab-par\", name: \"labctl\", project_id: \"${PROJECT}\", tags: [\"labctl\"],
status: \"ready\", install: {status: \"completed\"}, ips: [], offer_name: \"EM-B212X-SSD\", created_at: \"now\"}"
LAB_ZONES="fr-par-1 nl-ams-2" run_lab status
grep -q '^nl-ams-2 lab-ams' "${WORK}/out.log" || fail "status : $(cat "${WORK}/out.log")"
LAB_ZONES="fr-par-1 nl-ams-2" run_lab down || fail "down en échec"
grep -q 'DELETE /baremetal/v1/zones/nl-ams-2/servers/lab-ams' "${WORK}/calls.log" || fail "lab-ams non supprimé dans sa zone"
[[ $(remaining) == "foreign-1,foreign-2" ]] || fail "restants : $(remaining)"
teardown
}
test_prepare_script_requires_x86_64_v3 () {
setup "prepare : refus d'un CPU sans x86-64-v3"
local DIR="${WORK}/root"
mkdir -p "${DIR}/bin" "${DIR}/sys/module/kvm_intel/parameters" "${DIR}/dev"
lab_env bash -c ". '${SCRIPT}'; prepare_script" > "${WORK}/prepare.sh"
grep -q "x86-64-v3 (supported" "${WORK}/prepare.sh" || fail "aucune vérification x86-64-v3 dans le script de préparation"
grep -q "exit 1" <<< "$(sed -n '/x86-64-v3/,/fi/p' "${WORK}/prepare.sh")" || fail "pas d'arrêt si le niveau manque"
teardown
}
test_session_handles_term () { signal_during_session TERM 143; }
test_session_handles_hup () { signal_during_session HUP 129; }
test_session_handles_int () { signal_during_session INT 130; }