ajoute le stock chaud, la correction automatique et les nouveaux essais de création de stack
Stock de stacks prêtes par lab dans Redis (prise atomique en Lua, ménage par comparaison avec Heat, disjoncteur), files gérées par Horizon, séances planifiables. Correcteur Go sur l'hyperviseur : socket Unix, commandes lues dans le lab.yaml uniquement, exécution par l'agent invité QEMU. Une création de stack ratée est supprimée et réessayée deux fois, puis la session passe en échec, visible du prof. Corrige aussi trois défauts des étapes précédentes : la console se coupait à la première frappe d'un navigateur (trames texte), l'élève ne pouvait pas rejoindre une séance, la déconnexion n'avait pas de jeton CSRF. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
ca2f6f3b7a
commit
80b6c0722d
71 changed files with 2959 additions and 170 deletions
2
correcteur/.gitignore
vendored
Normal file
2
correcteur/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
/correcteur
|
||||
/correcteur-linux-amd64
|
||||
5
correcteur/go.mod
Normal file
5
correcteur/go.mod
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
module correcteur
|
||||
|
||||
go 1.27.1
|
||||
|
||||
require gopkg.in/yaml.v3 v3.0.1
|
||||
4
correcteur/go.sum
Normal file
4
correcteur/go.sum
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
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=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
71
correcteur/lab.go
Normal file
71
correcteur/lab.go
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type attendu struct {
|
||||
CodeRetour int `yaml:"code_retour"`
|
||||
SortieContient string `yaml:"sortie_contient"`
|
||||
}
|
||||
|
||||
func (a attendu) satisfait(code int, sortie string) bool {
|
||||
if code != a.CodeRetour {
|
||||
return false
|
||||
}
|
||||
return a.SortieContient == "" || strings.Contains(sortie, a.SortieContient)
|
||||
}
|
||||
|
||||
type verification struct {
|
||||
ID string `yaml:"id"`
|
||||
Machine string `yaml:"machine"`
|
||||
Commande string `yaml:"commande"`
|
||||
Attendu attendu `yaml:"attendu"`
|
||||
}
|
||||
|
||||
type lab struct {
|
||||
Machines []struct {
|
||||
Nom string `yaml:"nom"`
|
||||
} `yaml:"machines"`
|
||||
Verifications []verification `yaml:"verifications"`
|
||||
}
|
||||
|
||||
// L'identifiant a déjà été validé (^[a-z0-9][a-z0-9-]*$) : pas de « .. »
|
||||
// possible dans le chemin.
|
||||
func chargerLab(dossier, id string) (*lab, error) {
|
||||
contenu, err := os.ReadFile(filepath.Join(dossier, id, "lab.yaml"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var l lab
|
||||
if err := yaml.Unmarshal(contenu, &l); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &l, nil
|
||||
}
|
||||
|
||||
func (l *lab) verification(id string) (verification, bool) {
|
||||
for _, v := range l.Verifications {
|
||||
if v.ID == id {
|
||||
return v, true
|
||||
}
|
||||
}
|
||||
return verification{}, false
|
||||
}
|
||||
|
||||
// Le portail nomme chaque VM « {préfixe}-{machine} » (GenerateurTemplateHeat).
|
||||
// On retrouve la machine par le suffixe le plus long : avec des machines
|
||||
// « a » et « pc-a », le nom « …-pc-a » désigne bien pc-a, pas a.
|
||||
func (l *lab) machineDuNom(nomInstance string) string {
|
||||
trouvee := ""
|
||||
for _, m := range l.Machines {
|
||||
if strings.HasSuffix(nomInstance, "-"+m.Nom) && len(m.Nom) > len(trouvee) {
|
||||
trouvee = m.Nom
|
||||
}
|
||||
}
|
||||
return trouvee
|
||||
}
|
||||
55
correcteur/lab_test.go
Normal file
55
correcteur/lab_test.go
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestLab08(t *testing.T) {
|
||||
l, err := chargerLab("../labs", "08-deux-lan-routeur")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v, ok := l.verification("forwarding")
|
||||
if !ok || v.Machine != "routeur" || v.Attendu.CodeRetour != 0 || v.Commande == "" {
|
||||
t.Fatalf("vérification forwarding mal lue : %+v", v)
|
||||
}
|
||||
if _, ok := l.verification("inexistante"); ok {
|
||||
t.Fatal("une vérification inconnue ne doit pas être trouvée")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMachineDuNom(t *testing.T) {
|
||||
l := &lab{}
|
||||
for _, n := range []string{"a", "pc-a", "routeur"} {
|
||||
l.Machines = append(l.Machines, struct {
|
||||
Nom string `yaml:"nom"`
|
||||
}{n})
|
||||
}
|
||||
cas := map[string]string{
|
||||
"lab-session-3-e1-pc-a": "pc-a",
|
||||
"stock-08-deux-lan-routeur-x-e2-a": "a",
|
||||
"lab-session-3-e1-routeur": "routeur",
|
||||
"vm-sans-rapport": "",
|
||||
}
|
||||
for nom, attendu := range cas {
|
||||
if got := l.machineDuNom(nom); got != attendu {
|
||||
t.Errorf("machineDuNom(%q) = %q, attendu %q", nom, got, attendu)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttendu(t *testing.T) {
|
||||
a := attendu{CodeRetour: 0, SortieContient: "ok"}
|
||||
if !a.satisfait(0, "tout est ok") || a.satisfait(1, "ok") || a.satisfait(0, "non") {
|
||||
t.Fatal("règle code_retour + sortie_contient mal appliquée")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidationIdentifiants(t *testing.T) {
|
||||
for _, mauvais := range []string{"../etc", "08/../..", "A", "", "lab;rm"} {
|
||||
if reIdent.MatchString(mauvais) {
|
||||
t.Errorf("%q ne doit pas être accepté", mauvais)
|
||||
}
|
||||
}
|
||||
if reInstance.MatchString("not-a-uuid") || !reInstance.MatchString("8c8d5447-80fe-40da-ae65-812e077941f8") {
|
||||
t.Fatal("validation d'uuid incorrecte")
|
||||
}
|
||||
}
|
||||
113
correcteur/libvirt.go
Normal file
113
correcteur/libvirt.go
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"time"
|
||||
)
|
||||
|
||||
var errDelaiDepasse = errors.New("délai dépassé")
|
||||
|
||||
// virsh lancé dans le conteneur nova_libvirt de Kolla. Les arguments sont
|
||||
// passés tels quels (pas de shell) : rien n'est interprété sur l'hôte.
|
||||
func virsh(ctx context.Context, args ...string) ([]byte, error) {
|
||||
cmd := exec.CommandContext(ctx, "docker", append([]string{"exec", "nova_libvirt", "virsh"}, args...)...)
|
||||
sortie, err := cmd.Output()
|
||||
if err != nil {
|
||||
var ee *exec.ExitError
|
||||
if errors.As(err, &ee) {
|
||||
return nil, fmt.Errorf("%w : %s", err, ee.Stderr)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return sortie, nil
|
||||
}
|
||||
|
||||
// Métadonnées que Nova écrit dans la définition libvirt de chaque instance
|
||||
// (espace de noms http://openstack.org/xmlns/libvirt/nova/…).
|
||||
type domaine struct {
|
||||
Metadata struct {
|
||||
Instance struct {
|
||||
Nom string `xml:"name"`
|
||||
Owner struct {
|
||||
Projet struct {
|
||||
UUID string `xml:"uuid,attr"`
|
||||
} `xml:"project"`
|
||||
} `xml:"owner"`
|
||||
} `xml:"instance"`
|
||||
} `xml:"metadata"`
|
||||
}
|
||||
|
||||
func (d domaine) nom() string { return d.Metadata.Instance.Nom }
|
||||
func (d domaine) projet() string { return d.Metadata.Instance.Owner.Projet.UUID }
|
||||
|
||||
func lireDomaine(ctx context.Context, instance string) (domaine, error) {
|
||||
var d domaine
|
||||
brut, err := virsh(ctx, "dumpxml", instance)
|
||||
if err != nil {
|
||||
return d, err
|
||||
}
|
||||
err = xml.Unmarshal(brut, &d)
|
||||
return d, err
|
||||
}
|
||||
|
||||
// Lance /bin/sh -c <commande> dans la VM (guest-exec), puis interroge
|
||||
// guest-exec-status jusqu'à la fin du processus.
|
||||
func executer(ctx context.Context, instance, commande string) (int, string, error) {
|
||||
lancement, _ := json.Marshal(map[string]any{
|
||||
"execute": "guest-exec",
|
||||
"arguments": map[string]any{
|
||||
"path": "/bin/sh",
|
||||
"arg": []string{"-c", commande},
|
||||
"capture-output": true,
|
||||
},
|
||||
})
|
||||
brut, err := virsh(ctx, "qemu-agent-command", instance, string(lancement), "--timeout", "5")
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
var pid struct {
|
||||
Return struct {
|
||||
PID int `json:"pid"`
|
||||
} `json:"return"`
|
||||
}
|
||||
if err := json.Unmarshal(brut, &pid); err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
|
||||
statut, _ := json.Marshal(map[string]any{"execute": "guest-exec-status", "arguments": map[string]int{"pid": pid.Return.PID}})
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return 0, "", errDelaiDepasse
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
}
|
||||
|
||||
brut, err := virsh(ctx, "qemu-agent-command", instance, string(statut), "--timeout", "5")
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return 0, "", errDelaiDepasse
|
||||
}
|
||||
return 0, "", err
|
||||
}
|
||||
var r struct {
|
||||
Return struct {
|
||||
Exited bool `json:"exited"`
|
||||
ExitCode int `json:"exitcode"`
|
||||
OutData string `json:"out-data"`
|
||||
} `json:"return"`
|
||||
}
|
||||
if err := json.Unmarshal(brut, &r); err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
if r.Return.Exited {
|
||||
sortie, _ := base64.StdEncoding.DecodeString(r.Return.OutData)
|
||||
return r.Return.ExitCode, string(sortie), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
180
correcteur/main.go
Normal file
180
correcteur/main.go
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
// Correcteur Syllabus (étape 11) : exécute dans les VM des élèves les
|
||||
// vérifications déclarées dans le lab.yaml, par l'agent invité QEMU.
|
||||
//
|
||||
// Il écoute sur un socket Unix accessible au seul groupe www-data (le
|
||||
// portail) et n'accepte que trois identifiants : instance, lab,
|
||||
// vérification. La commande exécutée est toujours lue dans le lab.yaml,
|
||||
// jamais reçue du portail.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
tailleMaxRequete = 1024
|
||||
delaiConnexion = 20 * time.Second
|
||||
// README du pack de contenus : 10 s maximum par commande.
|
||||
delaiVerification = 10 * time.Second
|
||||
maxSimultanees = 8
|
||||
)
|
||||
|
||||
var (
|
||||
reInstance = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
|
||||
reIdent = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,63}$`)
|
||||
)
|
||||
|
||||
type requete struct {
|
||||
Instance string `json:"instance"`
|
||||
Lab string `json:"lab"`
|
||||
Verification string `json:"verification"`
|
||||
}
|
||||
|
||||
type reponse struct {
|
||||
Reussi bool `json:"reussi"`
|
||||
Erreur string `json:"erreur,omitempty"`
|
||||
}
|
||||
|
||||
// Codes d'erreur renvoyés au portail (jamais la sortie de la commande).
|
||||
const (
|
||||
errRequete = "requete_invalide"
|
||||
errLab = "lab_inconnu"
|
||||
errVerification = "verification_inconnue"
|
||||
errMachine = "machine_non_conforme"
|
||||
errAgent = "agent_injoignable"
|
||||
errDelai = "delai_depasse"
|
||||
)
|
||||
|
||||
type config struct {
|
||||
socket string
|
||||
dossierLabs string
|
||||
projet string
|
||||
uidClient int
|
||||
}
|
||||
|
||||
func main() {
|
||||
cfg := config{
|
||||
socket: envOu("CORRECTEUR_SOCKET", "/run/correcteur/correcteur.sock"),
|
||||
dossierLabs: envOu("CORRECTEUR_LABS", "/opt/labs"),
|
||||
projet: os.Getenv("CORRECTEUR_PROJET"),
|
||||
}
|
||||
uid, err := strconv.Atoi(os.Getenv("CORRECTEUR_UID_CLIENT"))
|
||||
if err != nil || cfg.projet == "" {
|
||||
log.Fatal("CORRECTEUR_PROJET et CORRECTEUR_UID_CLIENT sont obligatoires")
|
||||
}
|
||||
cfg.uidClient = uid
|
||||
|
||||
_ = os.Remove(cfg.socket)
|
||||
ecoute, err := net.Listen("unix", cfg.socket)
|
||||
if err != nil {
|
||||
log.Fatalf("écoute impossible sur %s : %v", cfg.socket, err)
|
||||
}
|
||||
// Le groupe du processus est www-data (unité systemd) : 0660 réserve le
|
||||
// socket à root et au portail.
|
||||
if err := os.Chmod(cfg.socket, 0o660); err != nil {
|
||||
log.Fatalf("chmod du socket : %v", err)
|
||||
}
|
||||
log.Printf("correcteur prêt sur %s (labs : %s)", cfg.socket, cfg.dossierLabs)
|
||||
|
||||
places := make(chan struct{}, maxSimultanees)
|
||||
for {
|
||||
conn, err := ecoute.Accept()
|
||||
if err != nil {
|
||||
log.Printf("accept : %v", err)
|
||||
continue
|
||||
}
|
||||
places <- struct{}{}
|
||||
go func() {
|
||||
defer func() { <-places }()
|
||||
traiter(cfg, conn.(*net.UnixConn))
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func traiter(cfg config, conn *net.UnixConn) {
|
||||
defer conn.Close()
|
||||
_ = conn.SetDeadline(time.Now().Add(delaiConnexion))
|
||||
debut := time.Now()
|
||||
|
||||
// Défense en profondeur : en plus des droits du socket, on vérifie
|
||||
// l'identité du processus à l'autre bout (SO_PEERCRED).
|
||||
uid, err := uidPair(conn)
|
||||
if err != nil || (uid != cfg.uidClient && uid != 0) {
|
||||
log.Printf("connexion refusée (uid %d, %v)", uid, err)
|
||||
return
|
||||
}
|
||||
|
||||
var req requete
|
||||
ligne, err := bufio.NewReader(io.LimitReader(conn, tailleMaxRequete)).ReadBytes('\n')
|
||||
if err == nil {
|
||||
dec := json.NewDecoder(bytes.NewReader(ligne))
|
||||
dec.DisallowUnknownFields()
|
||||
err = dec.Decode(&req)
|
||||
}
|
||||
var rep reponse
|
||||
if err != nil || !reInstance.MatchString(req.Instance) || !reIdent.MatchString(req.Lab) || !reIdent.MatchString(req.Verification) {
|
||||
rep = reponse{Erreur: errRequete}
|
||||
} else {
|
||||
rep = verifier(cfg, req)
|
||||
}
|
||||
|
||||
sortie, _ := json.Marshal(rep)
|
||||
_, _ = conn.Write(append(sortie, '\n'))
|
||||
log.Printf("instance=%s lab=%s verification=%s reussi=%t erreur=%q duree=%s",
|
||||
req.Instance, req.Lab, req.Verification, rep.Reussi, rep.Erreur, time.Since(debut).Round(time.Millisecond))
|
||||
}
|
||||
|
||||
func verifier(cfg config, req requete) reponse {
|
||||
lab, err := chargerLab(cfg.dossierLabs, req.Lab)
|
||||
if err != nil {
|
||||
return reponse{Erreur: errLab}
|
||||
}
|
||||
v, ok := lab.verification(req.Verification)
|
||||
if !ok {
|
||||
return reponse{Erreur: errVerification}
|
||||
}
|
||||
|
||||
ctx, annuler := context.WithTimeout(context.Background(), delaiVerification+5*time.Second)
|
||||
defer annuler()
|
||||
|
||||
dom, err := lireDomaine(ctx, req.Instance)
|
||||
if err != nil {
|
||||
log.Printf("dumpxml %s : %v", req.Instance, err)
|
||||
return reponse{Erreur: errMachine}
|
||||
}
|
||||
if dom.projet() != cfg.projet || lab.machineDuNom(dom.nom()) != v.Machine {
|
||||
log.Printf("instance %s refusée : projet %q, nom %q, machine attendue %q", req.Instance, dom.projet(), dom.nom(), v.Machine)
|
||||
return reponse{Erreur: errMachine}
|
||||
}
|
||||
|
||||
ctxExec, annulerExec := context.WithTimeout(ctx, delaiVerification)
|
||||
defer annulerExec()
|
||||
code, sortieCmd, err := executer(ctxExec, req.Instance, v.Commande)
|
||||
switch {
|
||||
case errors.Is(err, errDelaiDepasse):
|
||||
return reponse{Erreur: errDelai}
|
||||
case err != nil:
|
||||
log.Printf("guest-exec %s : %v", req.Instance, err)
|
||||
return reponse{Erreur: errAgent}
|
||||
}
|
||||
|
||||
return reponse{Reussi: v.Attendu.satisfait(code, sortieCmd)}
|
||||
}
|
||||
|
||||
func envOu(cle, defaut string) string {
|
||||
if v := os.Getenv(cle); v != "" {
|
||||
return v
|
||||
}
|
||||
return defaut
|
||||
}
|
||||
14
correcteur/peercred_autres.go
Normal file
14
correcteur/peercred_autres.go
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
//go:build !linux
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
)
|
||||
|
||||
// Le correcteur ne tourne que sur l'hyperviseur Linux ; ce fichier permet
|
||||
// seulement de compiler et tester le reste sur le Mac.
|
||||
func uidPair(*net.UnixConn) (int, error) {
|
||||
return -1, errors.New("SO_PEERCRED indisponible hors Linux")
|
||||
}
|
||||
24
correcteur/peercred_linux.go
Normal file
24
correcteur/peercred_linux.go
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"net"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func uidPair(conn *net.UnixConn) (int, error) {
|
||||
brut, err := conn.SyscallConn()
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
var cred *syscall.Ucred
|
||||
var errCred error
|
||||
if err := brut.Control(func(fd uintptr) {
|
||||
cred, errCred = syscall.GetsockoptUcred(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
|
||||
}); err != nil {
|
||||
return -1, err
|
||||
}
|
||||
if errCred != nil {
|
||||
return -1, errCred
|
||||
}
|
||||
return int(cred.Uid), nil
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue