chore: build
ci-api / test (push) Successful in 28m19s

This commit is contained in:
Xor290
2026-10-26 20:58:30 +01:00
parent e9659854db
commit 5061095fe2
21 changed files with 1303 additions and 26 deletions
+12
View File
@@ -178,6 +178,9 @@ func main() {
Domain: cfg.VitrineDomain,
// Un client ne peut pas revendiquer un domaine d'Omnex (démos).
ReservedDomains: []string{cfg.DemoDomain},
// Incidents projets vers le Discord / Telegram de chaque admin (sans
// base, pas de réglages : l'alerte reste dans les logs).
Alert: projectAlert(alertRecipients),
})
go projectSvc.RunExpirationLoop(context.Background(), 5*time.Minute)
@@ -253,3 +256,12 @@ func main() {
log.Printf("extinction forcée après délai: %v", err)
}
}
// projectAlert adapte les destinataires d'alertes au hook Alert des projets.
// nil si aucun destinataire n'est résolvable (mode mémoire).
func projectAlert(recipients func(ctx context.Context) ([]alerts.Notifier, error)) func(string) {
if recipients == nil {
return nil
}
return func(message string) { alerts.Broadcast(recipients, message) }
}
@@ -0,0 +1,35 @@
package alerts
import (
"context"
"log"
"time"
)
// broadcastTimeout borne l'envoi d'une alerte ponctuelle (résolution des
// destinataires en base + appels HTTP Discord/Telegram).
const broadcastTimeout = 20 * time.Second
// Broadcast envoie message à tous les destinataires actuels (admins ayant
// renseigné un webhook Discord et/ou un bot Telegram). Les destinataires sont
// résolus à l'appel : un changement de réglages est pris en compte sans
// redémarrage. Les erreurs sont journalisées, jamais renvoyées — une alerte
// qui échoue ne doit pas faire échouer l'opération qui l'a déclenchée.
// Bloquant : à appeler dans une goroutine depuis un chemin sensible.
func Broadcast(recipients func(ctx context.Context) ([]Notifier, error), message string) {
ctx, cancel := context.WithTimeout(context.Background(), broadcastTimeout)
defer cancel()
list, err := recipients(ctx)
if err != nil {
log.Printf("alerts: chargement des destinataires échoué: %v", err)
return
}
if len(list) == 0 {
log.Printf("alerts: aucun destinataire configuré, alerte non envoyée: %s", message)
return
}
if err := MultiNotifier(list).Notify(ctx, message); err != nil {
log.Printf("alerts: envoi de l'alerte échoué: %v", err)
}
}
@@ -0,0 +1,37 @@
package alerts
import (
"context"
"errors"
"sync"
"testing"
)
type recordingNotifier struct {
mu sync.Mutex
msgs []string
err error
}
func (r *recordingNotifier) Notify(_ context.Context, message string) error {
r.mu.Lock()
defer r.mu.Unlock()
r.msgs = append(r.msgs, message)
return r.err
}
func TestBroadcast_DeliversToEveryRecipientEvenIfOneFails(t *testing.T) {
failing := &recordingNotifier{err: errors.New("webhook mort")}
ok := &recordingNotifier{}
Broadcast(func(context.Context) ([]Notifier, error) { return []Notifier{failing, ok}, nil }, "incident")
if len(failing.msgs) != 1 || len(ok.msgs) != 1 || ok.msgs[0] != "incident" {
t.Errorf("failing=%v ok=%v : l'échec d'un canal a empêché l'autre", failing.msgs, ok.msgs)
}
}
func TestBroadcast_SwallowsRecipientErrorsAndEmptyLists(t *testing.T) {
// Ne doit ni paniquer ni bloquer.
Broadcast(func(context.Context) ([]Notifier, error) { return nil, errors.New("db indisponible") }, "x")
Broadcast(func(context.Context) ([]Notifier, error) { return nil, nil }, "x")
}
@@ -800,12 +800,18 @@ func (h *HelmProvisioner) ensureWorkloadRoleBinding(namespace string) error {
return nil
}
// deleteNamespace supprime un namespace (avec cascading).
// deleteNamespace supprime un namespace (avec cascading). Idempotent : un
// namespace déjà supprimé (à la main avec kubectl, ou par un appel précédent)
// n'est pas une erreur — sinon la ligne en base reste bloquée en "deleting".
func (h *HelmProvisioner) deleteNamespace(name string) error {
propagationPolicy := metav1.DeletePropagationForeground
return h.k8sClient.CoreV1().Namespaces().Delete(context.Background(), name, metav1.DeleteOptions{
err := h.k8sClient.CoreV1().Namespaces().Delete(context.Background(), name, metav1.DeleteOptions{
PropagationPolicy: &propagationPolicy,
})
if k8sErrors.IsNotFound(err) {
return nil
}
return err
}
// veleroNamespace : namespace fixe où tourne Velero (installé une fois par
@@ -7,6 +7,7 @@ import (
"strconv"
corev1 "k8s.io/api/core/v1"
k8sErrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
@@ -150,6 +151,20 @@ func (h *HelmProvisioner) ProjectState(ctx context.Context, namespace string) (R
return buildProjectState(pods.Items, h.podUsage(ctx, namespace)), nil
}
// NamespaceExists : le namespace existe-t-il dans le cluster ? Seule une erreur
// « not found » explicite signifie « absent » ; toute autre erreur (API
// injoignable, droits) est renvoyée pour que l'appelant ne conclue rien.
func (h *HelmProvisioner) NamespaceExists(ctx context.Context, namespace string) (bool, error) {
_, err := h.k8sClient.CoreV1().Namespaces().Get(ctx, namespace, metav1.GetOptions{})
if k8sErrors.IsNotFound(err) {
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
// buildProjectState range les pods d'un projet par composant (voir
// ProjectState). usage : nom de pod -> [cpuMilli, memMi].
func buildProjectState(pods []corev1.Pod, usage map[string][2]int64) ResourceState {
+14 -24
View File
@@ -41,30 +41,20 @@ func (s Status) Extendable() bool {
}
type Project struct {
ID string `gorm:"type:uuid;primaryKey" json:"id"`
ClientName string `gorm:"size:64;not null;index" json:"client_name"`
Status Status `gorm:"size:20;not null;index" json:"status"`
Namespace string `gorm:"size:63;uniqueIndex" json:"namespace"`
Host string `gorm:"size:255" json:"host"`
URL string `gorm:"size:255" json:"url"`
// CustomDomain : domaine du client, servi en plus de Host ("" = aucun).
// URL pointe dessus quand il est défini.
CustomDomain string `gorm:"size:255" json:"custom_domain,omitempty"`
// OwnerUsername : compte client qui a demandé le site ("" = déployé
// directement par l'admin). Donne au client la lecture de son site.
OwnerUsername string `gorm:"size:64;index" json:"owner_username,omitempty"`
// AdminUsername : compte admin créé dans le backend déployé (le mot de
// passe n'est jamais persisté). AdminNumber : ADMIN_NUMBER du backend.
AdminUsername string `gorm:"size:64" json:"admin_username"`
AdminNumber int `json:"admin_number"`
// MonthsPurchased : total des mois souscrits (création + renouvellements).
MonthsPurchased int `json:"months_purchased"`
CreatedAt time.Time `json:"created_at"`
// ExpiresAt : fin de l'abonnement (le projet est alors supprimé).
ExpiresAt time.Time `json:"expires_at"`
ID string `gorm:"type:uuid;primaryKey" json:"id"`
ClientName string `gorm:"size:64;not null;index" json:"client_name"`
Status Status `gorm:"size:20;not null;index" json:"status"`
Namespace string `gorm:"size:63;uniqueIndex" json:"namespace"`
Host string `gorm:"size:255" json:"host"`
URL string `gorm:"size:255" json:"url"`
CustomDomain string `gorm:"size:255" json:"custom_domain,omitempty"`
OwnerUsername string `gorm:"size:64;index" json:"owner_username,omitempty"`
AdminUsername string `gorm:"size:64" json:"admin_username"`
AdminNumber int `json:"admin_number"`
MonthsPurchased int `json:"months_purchased"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
UpdateAt time.Time `json:"update_at"`
}
func (Project) TableName() string { return "projects" }
@@ -3,6 +3,7 @@ package projects
import (
"context"
"errors"
"fmt"
"log"
"net"
"regexp"
@@ -38,6 +39,7 @@ type Provisioner interface {
TeardownProject(namespace string) error
UpdateProjectDomain(spec demos.ProjectDomainSpec) error
ProjectState(ctx context.Context, namespace string) (demos.ResourceState, error)
NamespaceExists(ctx context.Context, namespace string) (bool, error)
}
// NoopProvisioner : aucun déploiement réel (dev en mémoire, tests).
@@ -49,6 +51,7 @@ func (NoopProvisioner) UpdateProjectDomain(demos.ProjectDomainSpec) error { retu
func (NoopProvisioner) ProjectState(context.Context, string) (demos.ResourceState, error) {
return demos.ResourceState{}, nil
}
func (NoopProvisioner) NamespaceExists(context.Context, string) (bool, error) { return true, nil }
// Config du service (injectable pour les tests).
type Config struct {
@@ -57,6 +60,10 @@ type Config struct {
// pas revendiquer comme domaine personnalisé — ceux d'Omnex (démos…). Le
// domaine des projets (Domain) est toujours réservé.
ReservedDomains []string
// Alert reçoit un message à destination des admins pour les incidents qui
// demandent une intervention (ex. site en ligne dont le namespace a
// disparu). Facultatif ; appelé dans une goroutine, il peut être lent.
Alert func(message string)
}
// CreateInput : saisie de l'admin Omnex au déploiement (dashboard).
@@ -364,6 +371,7 @@ func (s *Service) RunExpirationLoop(ctx context.Context, interval time.Duration)
return
case <-ticker.C:
s.expireOverdue()
s.reconcile()
}
}
}
@@ -395,6 +403,95 @@ func (s *Service) applyLifecycle(id string) {
log.Printf("projets: %s supprimé (abonnement échu)", p.Namespace)
}
// reconcile aligne la base sur le cluster : une ligne dont le namespace n'existe
// plus est purgée, mais seulement quand c'est sans risque (voir reconcileOne).
func (s *Service) reconcile() {
all, err := s.store.List()
if err != nil {
log.Printf("projets: réconciliation, liste échouée: %v", err)
return
}
for _, p := range all {
s.mu.Lock()
s.reconcileOne(p.ID)
s.mu.Unlock()
}
}
// reconcileOne relit le projet (il a pu changer depuis List) puis compare son
// statut à l'existence réelle de son namespace. À appeler avec s.mu tenu.
func (s *Service) reconcileOne(id string) {
p, ok := s.store.Get(id)
if !ok {
return
}
// Seuls ces statuts ont une raison d'avoir (ou non) un namespace.
// provisioning/pending : le namespace est créé après la ligne, donc son
// absence est normale. failed : on garde la ligne pour que l'admin voie
// l'échec (il la supprime lui-même depuis l'interface).
if p.Status != StatusDeleting && p.Status != StatusDeleted && p.Status != StatusReady {
return
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
exists, err := s.prov.NamespaceExists(ctx, p.Namespace)
if err != nil {
// Erreur ≠ « absent » : on ne conclut rien ce tour-ci.
log.Printf("projets: namespace %s non vérifiable: %v", p.Namespace, err)
return
}
if exists {
return // y compris Terminating : Kubernetes n'a pas fini
}
if p.Status == StatusReady {
// Un projet en ligne sans namespace est un incident : on ne supprime
// jamais la ligne (client payant), on la passe en échec et on le signale.
p.Status = StatusFailed
if _, err := s.store.Update(p); err != nil {
log.Printf("projets: mise en échec de %s échouée: %v", p.Namespace, err)
return
}
log.Printf("projets: ATTENTION %s était en ligne mais son namespace a disparu", p.Namespace)
s.alert(fmt.Sprintf(
"⚠️ Omnex — le site vitrine « %s » (%s) était en ligne mais son namespace %s n'existe plus dans le cluster. "+
"Il est passé en échec. Vérifiez la suppression manuelle éventuelle et les sauvegardes Velero.",
alertText(p.ClientName), p.Host, p.Namespace))
return
}
if err := s.store.Delete(p.ID); err != nil {
log.Printf("projets: purge de %s échouée: %v", p.Namespace, err)
return
}
log.Printf("projets: %s purgé (namespace absent du cluster)", p.Namespace)
}
// alert transmet un incident aux admins sans jamais bloquer ni faire échouer
// l'appelant (qui tient s.mu) : l'envoi part dans une goroutine.
func (s *Service) alert(message string) {
if s.cfg.Alert == nil {
return
}
go s.cfg.Alert(message)
}
// alertText neutralise le texte saisi par un client avant de l'insérer dans une
// alerte : sans « @ » une mention (@everyone) ne peut pas être déclenchée sur
// le Discord d'un admin, et sans retour à la ligne le message reste lisible.
func alertText(s string) string {
return strings.Map(func(r rune) rune {
switch r {
case '@':
return '@'
case '\n', '\r', '\t':
return ' '
}
return r
}, s)
}
// shortID : 8 premiers caractères hex d'un uuid pour un nom de namespace court.
func shortID(id string) string {
clean := strings.ReplaceAll(id, "-", "")
@@ -3,6 +3,7 @@ package projects
import (
"context"
"errors"
"strings"
"sync"
"testing"
"time"
@@ -22,6 +23,8 @@ type fakeProv struct {
stateCalls []string
domainSpecs []demos.ProjectDomainSpec
domainErr error
missing map[string]bool // namespaces absents du cluster simulé
existsErr error
provisioned chan struct{}
}
@@ -48,6 +51,15 @@ func (f *fakeProv) ProjectState(_ context.Context, ns string) (demos.ResourceSta
return f.state, f.stateErr
}
func (f *fakeProv) NamespaceExists(_ context.Context, ns string) (bool, error) {
f.mu.Lock()
defer f.mu.Unlock()
if f.existsErr != nil {
return false, f.existsErr
}
return !f.missing[ns], nil
}
func (f *fakeProv) UpdateProjectDomain(s demos.ProjectDomainSpec) error {
f.mu.Lock()
defer f.mu.Unlock()
@@ -446,3 +458,240 @@ func TestSetDomain_StateAndClusterErrors(t *testing.T) {
t.Errorf("projet supprimé : erreur %v, attendu ErrNotReady", err)
}
}
// --- Réconciliation base / cluster ---
// setStatus force le statut d'un projet en base (simule un état hérité).
func setStatus(t *testing.T, svc *Service, id string, st Status) Project {
t.Helper()
p, ok := svc.store.Get(id)
if !ok {
t.Fatalf("projet %s introuvable", id)
}
p.Status = st
if _, err := svc.store.Update(p); err != nil {
t.Fatal(err)
}
return p
}
func TestReconcile_PurgesDeletingAndDeletedWhenNamespaceIsGone(t *testing.T) {
for _, st := range []Status{StatusDeleting, StatusDeleted} {
svc, prov, _ := newTestService(t)
p := createReady(t, svc, prov, validInput())
setStatus(t, svc, p.ID, st)
prov.missing = map[string]bool{p.Namespace: true}
svc.reconcile()
if _, ok := svc.store.Get(p.ID); ok {
t.Errorf("statut %s : ligne conservée alors que le namespace n'existe plus", st)
}
}
}
func TestReconcile_KeepsRowWhileNamespaceExists(t *testing.T) {
svc, prov, _ := newTestService(t)
p := createReady(t, svc, prov, validInput())
setStatus(t, svc, p.ID, StatusDeleting) // namespace encore là (Terminating compris)
svc.reconcile()
if got, ok := svc.store.Get(p.ID); !ok || got.Status != StatusDeleting {
t.Errorf("ligne purgée alors que le namespace existe : ok=%v %+v", ok, got)
}
}
func TestReconcile_ReadyWithoutNamespaceBecomesFailedNeverDeleted(t *testing.T) {
svc, prov, _ := newTestService(t)
p := createReady(t, svc, prov, validInput())
prov.missing = map[string]bool{p.Namespace: true}
svc.reconcile()
got, ok := svc.store.Get(p.ID)
if !ok {
t.Fatal("un projet en ligne ne doit jamais être purgé")
}
if got.Status != StatusFailed {
t.Errorf("statut %s, attendu failed", got.Status)
}
}
func TestReconcile_LeavesFailedProvisioningAndPendingAlone(t *testing.T) {
for _, st := range []Status{StatusFailed, StatusProvisioning, StatusPending} {
svc, prov, _ := newTestService(t)
p := createReady(t, svc, prov, validInput())
setStatus(t, svc, p.ID, st)
prov.missing = map[string]bool{p.Namespace: true}
svc.reconcile()
if got, ok := svc.store.Get(p.ID); !ok || got.Status != st {
t.Errorf("statut %s : ligne modifiée ou purgée (%v %+v)", st, ok, got)
}
}
}
func TestReconcile_APIErrorWritesNothing(t *testing.T) {
svc, prov, _ := newTestService(t)
gone := createReady(t, svc, prov, validInput())
live := createReady(t, svc, prov, validInput())
setStatus(t, svc, gone.ID, StatusDeleted)
prov.missing = map[string]bool{gone.Namespace: true}
prov.existsErr = errors.New("api k8s injoignable")
svc.reconcile()
if _, ok := svc.store.Get(gone.ID); !ok {
t.Error("ligne purgée alors que le cluster était injoignable")
}
if got, _ := svc.store.Get(live.ID); got.Status != StatusReady {
t.Errorf("projet en ligne modifié sur une simple erreur d'API : %s", got.Status)
}
}
func TestReconcile_OnlyTargetsMissingNamespaces(t *testing.T) {
svc, prov, _ := newTestService(t)
a := createReady(t, svc, prov, validInput())
b := createReady(t, svc, prov, validInput())
setStatus(t, svc, a.ID, StatusDeleted)
setStatus(t, svc, b.ID, StatusDeleted)
prov.missing = map[string]bool{a.Namespace: true}
svc.reconcile()
if _, ok := svc.store.Get(a.ID); ok {
t.Error("la ligne au namespace absent aurait dû être purgée")
}
if _, ok := svc.store.Get(b.ID); !ok {
t.Error("la ligne au namespace existant ne doit pas être purgée")
}
}
func TestStoreDelete_IsIdempotent(t *testing.T) {
st := NewMemStore()
if _, err := st.Create(Project{ID: "p1"}); err != nil {
t.Fatal(err)
}
if err := st.Delete("p1"); err != nil {
t.Fatal(err)
}
if _, ok := st.Get("p1"); ok {
t.Error("ligne toujours présente après Delete")
}
if err := st.Delete("p1"); err != nil {
t.Errorf("second Delete : %v, attendu nil", err)
}
}
func TestRunExpirationLoop_ReconcilesOnEachTick(t *testing.T) {
svc, prov, _ := newTestService(t)
p := createReady(t, svc, prov, validInput())
setStatus(t, svc, p.ID, StatusDeleting)
prov.missing = map[string]bool{p.Namespace: true}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
svc.RunExpirationLoop(ctx, 5*time.Millisecond)
close(done)
}()
deadline := time.After(2 * time.Second)
for {
if _, ok := svc.store.Get(p.ID); !ok {
break
}
select {
case <-deadline:
t.Fatal("la boucle n'a pas purgé la ligne : reconcile() n'est pas appelé")
case <-time.After(5 * time.Millisecond):
}
}
cancel()
<-done
}
// --- Alerte d'incident ---
// captureAlerts branche un Alert de test ; chaque message arrive sur le canal.
func captureAlerts(svc *Service) chan string {
ch := make(chan string, 8)
svc.cfg.Alert = func(m string) { ch <- m }
return ch
}
func waitAlert(t *testing.T, ch chan string) string {
t.Helper()
select {
case m := <-ch:
return m
case <-time.After(2 * time.Second):
t.Fatal("aucune alerte reçue")
return ""
}
}
func TestReconcile_ReadyWithoutNamespaceAlertsAdminsOnce(t *testing.T) {
svc, prov, _ := newTestService(t)
alerts := captureAlerts(svc)
p := createReady(t, svc, prov, validInput())
prov.missing = map[string]bool{p.Namespace: true}
svc.reconcile()
msg := waitAlert(t, alerts)
for _, want := range []string{p.Namespace, p.Host, "Boutique Dupont"} {
if !strings.Contains(msg, want) {
t.Errorf("l'alerte ne mentionne pas %q : %s", want, msg)
}
}
// Le projet est passé en échec : les tours suivants ne renvoient rien.
svc.reconcile()
svc.reconcile()
select {
case m := <-alerts:
t.Errorf("alerte répétée : %s", m)
case <-time.After(100 * time.Millisecond):
}
}
func TestReconcile_NoAlertForRoutinePurgesOrAPIErrors(t *testing.T) {
svc, prov, _ := newTestService(t)
alerts := captureAlerts(svc)
gone := createReady(t, svc, prov, validInput())
setStatus(t, svc, gone.ID, StatusDeleting)
prov.missing = map[string]bool{gone.Namespace: true}
svc.reconcile() // purge normale
live := createReady(t, svc, prov, validInput())
prov.missing = map[string]bool{live.Namespace: true}
prov.existsErr = errors.New("api k8s injoignable")
svc.reconcile() // cluster injoignable : aucun incident à déclarer
select {
case m := <-alerts:
t.Errorf("alerte inutile : %s", m)
case <-time.After(100 * time.Millisecond):
}
}
func TestReconcile_WithoutAlertHookStillMarksFailed(t *testing.T) {
svc, prov, _ := newTestService(t) // Config.Alert == nil
p := createReady(t, svc, prov, validInput())
prov.missing = map[string]bool{p.Namespace: true}
svc.reconcile() // ne doit pas paniquer
if got, _ := svc.store.Get(p.ID); got.Status != StatusFailed {
t.Errorf("statut %s, attendu failed", got.Status)
}
}
func TestAlertText_NeutralisesMentionsAndLineBreaks(t *testing.T) {
got := alertText("a@everyone\nb\tc")
if strings.Contains(got, "@") || strings.ContainsAny(got, "\n\t") {
t.Errorf("texte non neutralisé : %q", got)
}
}
@@ -14,6 +14,9 @@ type Store interface {
Get(id string) (Project, bool)
List() ([]Project, error)
Update(p Project) (Project, error)
// Delete supprime définitivement la ligne. Idempotent : un identifiant
// inconnu n'est pas une erreur.
Delete(id string) error
}
// GormStore : Store adossé à PostgreSQL via GORM.
@@ -52,6 +55,10 @@ func (s *GormStore) Update(p Project) (Project, error) {
return p, nil
}
func (s *GormStore) Delete(id string) error {
return s.db.Where("id = ?", id).Delete(&Project{}).Error
}
// MemStore : Store en mémoire (dev/tests).
type MemStore struct {
mu sync.RWMutex
@@ -91,3 +98,10 @@ func (m *MemStore) Update(p Project) (Project, error) {
m.items[p.ID] = p
return p, nil
}
func (m *MemStore) Delete(id string) error {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.items, id)
return nil
}