f-88: api: ressource /floating-ips, refus et affichage sur la VM #88

Signed-off-by: GnomeZworc <nicolas.boufidjeline@g3e.fr>
This commit is contained in:
GnomeZworc 2026-10-29 21:48:12 +01:00
commit 385ee9d1f0
Signed by: nicolas.boufideline
GPG key ID: 4406BBBF8845D632
15 changed files with 942 additions and 12 deletions

66
internal/api/agent/fip.go Normal file
View file

@ -0,0 +1,66 @@
package agentapi
import (
"encoding/json"
"net/http"
"strings"
dispatcher "git.g3e.fr/syonad/two/internal/dispatcher/agent"
"git.g3e.fr/syonad/two/pkg/db/kv"
)
func (s *Server) FloatingIPByNameHandler(w http.ResponseWriter, r *http.Request) {
name := strings.TrimPrefix(r.URL.Path, "/floating-ips/")
w.Header().Set("Content-Type", "application/json")
if name == "" {
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(ErrorResponse{Error: "resource not found"})
return
}
switch r.Method {
case http.MethodGet:
s.getFloatingIP(w, r, name)
case http.MethodDelete:
s.deleteFloatingIP(w, r, name)
default:
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
}
}
func (s *Server) getFloatingIP(w http.ResponseWriter, _ *http.Request, name string) {
prefix := "floating-ip/" + name + "/"
state, err := kv.GetFromDB(s.db, prefix+"state")
if err != nil {
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(ErrorResponse{Error: "floating ip not found"})
return
}
vm, _ := kv.GetFromDB(s.db, prefix+"vm")
iface, _ := kv.GetFromDB(s.db, prefix+"interface")
ip, _ := kv.GetFromDB(s.db, prefix+"ip")
gateway, _ := kv.GetFromDB(s.db, prefix+"gateway")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(FloatingIP{Name: name, State: state, VM: vm, Interface: iface, IP: ip, Gateway: gateway})
}
func (s *Server) deleteFloatingIP(w http.ResponseWriter, _ *http.Request, name string) {
cmd := dispatcher.DeleteFloatingIPCommand{Name: name}
if err := s.dispatcher.Prepare(cmd); err != nil {
if _, dbErr := kv.GetFromDB(s.db, "floating-ip/"+name+"/state"); dbErr != nil {
w.WriteHeader(http.StatusNotFound)
} else {
w.WriteHeader(http.StatusConflict)
}
json.NewEncoder(w).Encode(ErrorResponse{Error: err.Error()})
return
}
s.dispatcher.Dispatch(cmd)
state, err := kv.GetFromDB(s.db, "floating-ip/"+name+"/state")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(ErrorResponse{Error: "failed to read floating ip state"})
return
}
w.WriteHeader(http.StatusAccepted)
json.NewEncoder(w).Encode(FloatingIP{Name: name, State: state})
}

View file

@ -0,0 +1,195 @@
package agentapi
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.g3e.fr/syonad/two/pkg/db/kv"
"github.com/dgraph-io/badger/v4"
)
func seedRunningVM(t *testing.T, db *badger.DB) {
t.Helper()
for key, value := range map[string]string{
"vpc/vp-t47/cidr": "10.47.0.0/16",
"subnet/sn-a/vpc": "vp-t47",
"vm/vm-1/state": "running",
"vm/vm-1/nic/0/name": "nic-a",
"vm/vm-1/nic/0/subnet": "sn-a",
"vm/vm-1/nic/0/ip": "10.47.1.10",
"vm/vm-1/nic/1/name": "nic-b",
"vm/vm-1/nic/1/subnet": "sn-a",
"vm/vm-1/nic/1/ip": "10.47.1.11",
} {
kv.AddInDB(db, key, value)
}
}
func seedFloatingIP(t *testing.T, db *badger.DB, name, vm, iface, st string) {
t.Helper()
kv.AddInDB(db, "floating-ip/"+name+"/state", st)
kv.AddInDB(db, "floating-ip/"+name+"/vm", vm)
kv.AddInDB(db, "floating-ip/"+name+"/interface", iface)
kv.AddInDB(db, "floating-ip/"+name+"/ip", "240.0.0.47/24")
kv.AddInDB(db, "floating-ip/"+name+"/gateway", "240.0.0.1")
}
func validFloatingIPRequest() FloatingIPCreateRequest {
return FloatingIPCreateRequest{Name: "fip-1", VM: "vm-1", Interface: "nic-a", IP: "240.0.0.47/24", Gateway: "240.0.0.1"}
}
func postFloatingIP(t *testing.T, s *Server, req FloatingIPCreateRequest) *httptest.ResponseRecorder {
t.Helper()
body, _ := json.Marshal(req)
w := httptest.NewRecorder()
s.FloatingIPsHandler(w, httptest.NewRequest(http.MethodPost, "/floating-ips", bytes.NewReader(body)))
return w
}
func TestPostFloatingIP_Accepted(t *testing.T) {
s, db := newTestServer(t)
seedRunningVM(t, db)
w := postFloatingIP(t, s, validFloatingIPRequest())
if w.Code != http.StatusAccepted {
t.Fatalf("attendu 202, obtenu %d : %s", w.Code, w.Body.String())
}
var got FloatingIP
json.NewDecoder(w.Body).Decode(&got)
want := FloatingIP{Name: "fip-1", State: "creating", VM: "vm-1", Interface: "nic-a", IP: "240.0.0.47/24", Gateway: "240.0.0.1"}
if got != want {
t.Errorf("réponse %+v, attendu %+v", got, want)
}
}
func TestPostFloatingIP_BadRequest(t *testing.T) {
cases := []struct {
label string
mutate func(*FloatingIPCreateRequest)
msg string
}{
{"nom absent", func(r *FloatingIPCreateRequest) { r.Name = "" }, "name is required"},
{"vm absente", func(r *FloatingIPCreateRequest) { r.VM = "" }, "vm is required"},
{"interface absente", func(r *FloatingIPCreateRequest) { r.Interface = "" }, "interface is required"},
{"ip absente", func(r *FloatingIPCreateRequest) { r.IP = "" }, "ip is required"},
{"gateway absente", func(r *FloatingIPCreateRequest) { r.Gateway = "" }, "gateway is required"},
{"ip sans préfixe", func(r *FloatingIPCreateRequest) { r.IP = "240.0.0.47" }, "invalid ip"},
{"gateway IPv6", func(r *FloatingIPCreateRequest) { r.Gateway = "2001:db8::1" }, "invalid gateway"},
}
for _, c := range cases {
s, db := newTestServer(t)
seedRunningVM(t, db)
req := validFloatingIPRequest()
c.mutate(&req)
w := postFloatingIP(t, s, req)
if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), c.msg) {
t.Errorf("%s : %d %s, 400 « %s » attendu", c.label, w.Code, w.Body.String(), c.msg)
}
if _, err := kv.GetFromDB(db, "floating-ip/fip-1/state"); err == nil {
t.Errorf("%s : IP flottante écrite malgré le refus", c.label)
}
}
}
func TestPostFloatingIP_ConflictOnUnknownInterface(t *testing.T) {
s, db := newTestServer(t)
seedRunningVM(t, db)
req := validFloatingIPRequest()
req.Interface = "nic-z"
w := postFloatingIP(t, s, req)
if w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), `has no interface \"nic-z\"`) {
t.Errorf("%d %s, 409 attendu", w.Code, w.Body.String())
}
}
func TestFloatingIPGetListAndDelete(t *testing.T) {
s, db := newTestServer(t)
seedFloatingIP(t, db, "fip-1", "vm-1", "nic-a", "running")
want := FloatingIP{Name: "fip-1", State: "running", VM: "vm-1", Interface: "nic-a", IP: "240.0.0.47/24", Gateway: "240.0.0.1"}
w := httptest.NewRecorder()
s.FloatingIPsHandler(w, httptest.NewRequest(http.MethodGet, "/floating-ips", nil))
var list []FloatingIP
json.NewDecoder(w.Body).Decode(&list)
if w.Code != http.StatusOK || len(list) != 1 || list[0] != want {
t.Errorf("liste %d %+v", w.Code, list)
}
w = httptest.NewRecorder()
s.FloatingIPByNameHandler(w, httptest.NewRequest(http.MethodGet, "/floating-ips/fip-1", nil))
var got FloatingIP
json.NewDecoder(w.Body).Decode(&got)
if w.Code != http.StatusOK || got != want {
t.Errorf("get %d %+v", w.Code, got)
}
w = httptest.NewRecorder()
s.FloatingIPByNameHandler(w, httptest.NewRequest(http.MethodDelete, "/floating-ips/fip-x", nil))
if w.Code != http.StatusNotFound {
t.Errorf("suppression d'une IP flottante absente : %d, 404 attendu", w.Code)
}
w = httptest.NewRecorder()
s.FloatingIPByNameHandler(w, httptest.NewRequest(http.MethodDelete, "/floating-ips/fip-1", nil))
if w.Code != http.StatusAccepted {
t.Errorf("suppression : %d, 202 attendu", w.Code)
}
}
func TestGetVM_ShowsTheFloatingIPOfItsInterface(t *testing.T) {
s, db := newTestServer(t)
seedRunningVM(t, db)
seedFloatingIP(t, db, "fip-1", "vm-1", "nic-b", "running")
seedFloatingIP(t, db, "fip-9", "vm-10", "nic-a", "running")
w := httptest.NewRecorder()
s.VmByNameHandler(w, httptest.NewRequest(http.MethodGet, "/vms/vm-1", nil))
raw := w.Body.String()
var vm VM
json.Unmarshal([]byte(raw), &vm)
if len(vm.Interfaces) != 2 {
t.Fatalf("interfaces %+v", vm.Interfaces)
}
if vm.Interfaces[0].FloatingIP != nil {
t.Errorf("nic-a porte une IP flottante qui n'est pas la sienne : %+v", vm.Interfaces[0].FloatingIP)
}
want := VMFloatingIP{Name: "fip-1", IP: "240.0.0.47/24", State: "running"}
if vm.Interfaces[1].FloatingIP == nil || *vm.Interfaces[1].FloatingIP != want {
t.Errorf("nic-b : %+v, attendu %+v", vm.Interfaces[1].FloatingIP, want)
}
if strings.Count(raw, "floating_ip") != 1 {
t.Errorf("floating_ip doit être absent du JSON d'une interface sans IP flottante : %s", raw)
}
}
func TestDeleteVM_BlockedByAFloatingIP(t *testing.T) {
s, db := newTestServer(t)
seedRunningVM(t, db)
seedFloatingIP(t, db, "fip-1", "vm-1", "nic-a", "running")
w := httptest.NewRecorder()
s.VmByNameHandler(w, httptest.NewRequest(http.MethodDelete, "/vms/vm-1", nil))
if w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), `floating ip \"fip-1\" must be deleted`) {
t.Errorf("%d %s, 409 attendu", w.Code, w.Body.String())
}
}
func TestStartVM_RefusesAFloatingIPInTheRequest(t *testing.T) {
s, db := newTestServer(t)
kv.AddInDB(db, "subnet/sn-1/state", "running")
kv.AddInDB(db, "subnet/sn-1/vpc", "vpc-1")
kv.AddInDB(db, "subnet/sn-1/cidr", "10.0.0.0/24")
body, _ := json.Marshal(VMCreateRequest{
Name: "vm-f",
Interfaces: []VMInterface{{Name: "nic-a", Subnet: "sn-1", IP: "10.0.0.10", MAC: "52:54:00:00:00:05", Primary: true, FloatingIP: &VMFloatingIP{Name: "fip-1"}}},
Storage: []VMStorage{{Path: "/data/root.qcow2", Dev: "vda"}},
})
w := httptest.NewRecorder()
s.VmsHandler(w, httptest.NewRequest(http.MethodPost, "/vms", bytes.NewReader(body)))
if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "floating_ip is read-only") {
t.Errorf("%d %s, 400 attendu", w.Code, w.Body.String())
}
if _, err := kv.GetFromDB(db, "vm/vm-f/state"); err == nil {
t.Error("une VM refusée ne doit laisser aucune trace en base")
}
}

102
internal/api/agent/fips.go Normal file
View file

@ -0,0 +1,102 @@
package agentapi
import (
"encoding/json"
"net"
"net/http"
"strings"
dispatcher "git.g3e.fr/syonad/two/internal/dispatcher/agent"
"git.g3e.fr/syonad/two/pkg/db/kv"
)
func (s *Server) FloatingIPsHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.Method {
case http.MethodGet:
s.listFloatingIPs(w, r)
case http.MethodPost:
s.postFloatingIP(w, r)
default:
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
}
}
func (s *Server) listFloatingIPs(w http.ResponseWriter, _ *http.Request) {
entries, err := kv.ListByPrefix(s.db, "floating-ip/")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(ErrorResponse{Error: "failed to list floating ips"})
return
}
ips := make(map[string]*FloatingIP)
for key, value := range entries {
parts := strings.Split(key, "/")
if len(parts) != 3 {
continue
}
name := parts[1]
if _, ok := ips[name]; !ok {
ips[name] = &FloatingIP{Name: name}
}
switch parts[2] {
case "state":
ips[name].State = value
case "vm":
ips[name].VM = value
case "interface":
ips[name].Interface = value
case "ip":
ips[name].IP = value
case "gateway":
ips[name].Gateway = value
}
}
result := make([]FloatingIP, 0, len(ips))
for _, f := range ips {
result = append(result, *f)
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(result)
}
func (s *Server) postFloatingIP(w http.ResponseWriter, r *http.Request) {
var req FloatingIPCreateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(ErrorResponse{Error: "invalid request body"})
return
}
for _, f := range []struct{ name, value string }{{"name", req.Name}, {"vm", req.VM}, {"interface", req.Interface}, {"ip", req.IP}, {"gateway", req.Gateway}} {
if f.value == "" {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(ErrorResponse{Error: f.name + " is required"})
return
}
}
if ip, _, err := net.ParseCIDR(req.IP); err != nil || ip.To4() == nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(ErrorResponse{Error: "invalid ip: an IPv4 address with its prefix length is expected"})
return
}
if gw := net.ParseIP(req.Gateway); gw == nil || gw.To4() == nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(ErrorResponse{Error: "invalid gateway: an IPv4 address is expected"})
return
}
cmd := dispatcher.CreateFloatingIPCommand{Name: req.Name, VM: req.VM, Interface: req.Interface, IP: req.IP, Gateway: req.Gateway}
if err := s.dispatcher.Prepare(cmd); err != nil {
w.WriteHeader(http.StatusConflict)
json.NewEncoder(w).Encode(ErrorResponse{Error: err.Error()})
return
}
s.dispatcher.Dispatch(cmd)
state, err := kv.GetFromDB(s.db, "floating-ip/"+req.Name+"/state")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(ErrorResponse{Error: "failed to read floating ip state"})
return
}
w.WriteHeader(http.StatusAccepted)
json.NewEncoder(w).Encode(FloatingIP{Name: req.Name, State: state, VM: req.VM, Interface: req.Interface, IP: req.IP, Gateway: req.Gateway})
}

View file

@ -46,6 +46,14 @@ type VMInterface struct {
MAC string `json:"mac"`
Primary bool `json:"primary"`
DHCPServer bool `json:"dhcp_server"`
FloatingIP *VMFloatingIP `json:"floating_ip,omitempty"`
}
type VMFloatingIP struct {
Name string `json:"name"`
IP string `json:"ip"`
State string `json:"state"`
}
type VMStorage struct {
@ -98,3 +106,20 @@ type NATGateway struct {
IP string `json:"ip,omitempty"`
Gateway string `json:"gateway,omitempty"`
}
type FloatingIPCreateRequest struct {
Name string `json:"name"`
VM string `json:"vm"`
Interface string `json:"interface"`
IP string `json:"ip"`
Gateway string `json:"gateway"`
}
type FloatingIP struct {
Name string `json:"name"`
State string `json:"state"`
VM string `json:"vm,omitempty"`
Interface string `json:"interface,omitempty"`
IP string `json:"ip,omitempty"`
Gateway string `json:"gateway,omitempty"`
}

View file

@ -31,6 +31,8 @@ func New(d *dispatcher.Dispatcher, db *badger.DB, logger *slog.Logger, address s
mux.HandleFunc("/vms/", s.VmByNameHandler)
mux.HandleFunc("/nat-gateways", s.NATGatewaysHandler)
mux.HandleFunc("/nat-gateways/", s.NATGatewayByNameHandler)
mux.HandleFunc("/floating-ips", s.FloatingIPsHandler)
mux.HandleFunc("/floating-ips/", s.FloatingIPByNameHandler)
s.srv = &http.Server{Addr: address, Handler: s.logMiddleware(mux)}
return s
}

View file

@ -44,6 +44,13 @@ func (s *Server) getVM(w http.ResponseWriter, _ *http.Request, name string) {
json.NewEncoder(w).Encode(ErrorResponse{Error: "failed to read vm"})
return
}
floating, err := kv.ListByPrefix(s.db, "floating-ip/")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(ErrorResponse{Error: "failed to list floating ips"})
return
}
attachFloatingIPs(&vm, floating)
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(vm)
}
@ -145,3 +152,18 @@ func vmFromDB(name string, entries map[string]string) (VM, error) {
return vm, nil
}
func attachFloatingIPs(vm *VM, entries map[string]string) {
for key, value := range entries {
name, ok := strings.CutSuffix(strings.TrimPrefix(key, "floating-ip/"), "/vm")
if !ok || strings.Contains(name, "/") || value != vm.Name {
continue
}
prefix := "floating-ip/" + name + "/"
for i := range vm.Interfaces {
if vm.Interfaces[i].Name == entries[prefix+"interface"] {
vm.Interfaces[i].FloatingIP = &VMFloatingIP{Name: name, IP: entries[prefix+"ip"], State: entries[prefix+"state"]}
}
}
}
}

View file

@ -44,12 +44,19 @@ func (s *Server) listVMs(w http.ResponseWriter, _ *http.Request) {
}
}
floating, err := kv.ListByPrefix(s.db, "floating-ip/")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(ErrorResponse{Error: "failed to list floating ips"})
return
}
result := make([]VM, 0, len(names))
for name := range names {
vm, err := vmFromDB(name, entries)
if err != nil {
continue
}
attachFloatingIPs(&vm, floating)
result = append(result, vm)
}
@ -85,6 +92,11 @@ func (s *Server) startVM(w http.ResponseWriter, r *http.Request) {
return
}
names[iface.Name] = i
if iface.FloatingIP != nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(ErrorResponse{Error: fmt.Sprintf("interface %d: floating_ip is read-only, attach it with /floating-ips", i)})
return
}
if iface.MAC == "" {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(ErrorResponse{Error: fmt.Sprintf("interface %d: mac is required", i)})