f-42: api: ressource /nat-gateways, état, métrique et watchdog #42
Signed-off-by: GnomeZworc <nicolas.boufidjeline@g3e.fr>
This commit is contained in:
parent
4aec9927ad
commit
2737b61bc4
16 changed files with 841 additions and 11 deletions
|
|
@ -82,3 +82,18 @@ type VM struct {
|
|||
type ErrorResponse struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
type NATGatewayCreateRequest struct {
|
||||
Name string `json:"name"`
|
||||
VPC string `json:"vpc"`
|
||||
IP string `json:"ip"`
|
||||
Gateway string `json:"gateway"`
|
||||
}
|
||||
|
||||
type NATGateway struct {
|
||||
Name string `json:"name"`
|
||||
State string `json:"state"`
|
||||
VPC string `json:"vpc,omitempty"`
|
||||
IP string `json:"ip,omitempty"`
|
||||
Gateway string `json:"gateway,omitempty"`
|
||||
}
|
||||
|
|
|
|||
65
internal/api/agent/natgw.go
Normal file
65
internal/api/agent/natgw.go
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
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) NATGatewayByNameHandler(w http.ResponseWriter, r *http.Request) {
|
||||
name := strings.TrimPrefix(r.URL.Path, "/nat-gateways/")
|
||||
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.getNATGateway(w, r, name)
|
||||
case http.MethodDelete:
|
||||
s.deleteNATGateway(w, r, name)
|
||||
default:
|
||||
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) getNATGateway(w http.ResponseWriter, _ *http.Request, name string) {
|
||||
prefix := "nat-gateway/" + name + "/"
|
||||
state, err := kv.GetFromDB(s.db, prefix+"state")
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
json.NewEncoder(w).Encode(ErrorResponse{Error: "nat gateway not found"})
|
||||
return
|
||||
}
|
||||
vpc, _ := kv.GetFromDB(s.db, prefix+"vpc")
|
||||
ip, _ := kv.GetFromDB(s.db, prefix+"ip")
|
||||
gateway, _ := kv.GetFromDB(s.db, prefix+"gateway")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(NATGateway{Name: name, State: state, VPC: vpc, IP: ip, Gateway: gateway})
|
||||
}
|
||||
|
||||
func (s *Server) deleteNATGateway(w http.ResponseWriter, _ *http.Request, name string) {
|
||||
cmd := dispatcher.DeleteNATGatewayCommand{Name: name}
|
||||
if err := s.dispatcher.Prepare(cmd); err != nil {
|
||||
if _, dbErr := kv.GetFromDB(s.db, "nat-gateway/"+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, "nat-gateway/"+name+"/state")
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
json.NewEncoder(w).Encode(ErrorResponse{Error: "failed to read nat gateway state"})
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
json.NewEncoder(w).Encode(NATGateway{Name: name, State: state})
|
||||
}
|
||||
168
internal/api/agent/natgw_test.go
Normal file
168
internal/api/agent/natgw_test.go
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
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 seedRoutedVPC(t *testing.T, db *badger.DB) {
|
||||
t.Helper()
|
||||
kv.AddInDB(db, "vpc/vp-s7/state", "running")
|
||||
kv.AddInDB(db, "vpc/vp-s7/cidr", "10.241.0.0/16")
|
||||
kv.AddInDB(db, "vpc/vp-s7/l3vni", "2700")
|
||||
}
|
||||
|
||||
func postNATGateway(t *testing.T, s *Server, req NATGatewayCreateRequest) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
body, _ := json.Marshal(req)
|
||||
w := httptest.NewRecorder()
|
||||
s.NATGatewaysHandler(w, httptest.NewRequest(http.MethodPost, "/nat-gateways", bytes.NewReader(body)))
|
||||
return w
|
||||
}
|
||||
|
||||
func validNATGatewayRequest() NATGatewayCreateRequest {
|
||||
return NATGatewayCreateRequest{Name: "ng-1", VPC: "vp-s7", IP: "198.51.100.50/24", Gateway: "198.51.100.1"}
|
||||
}
|
||||
|
||||
func TestPostNATGateway_Accepted(t *testing.T) {
|
||||
s, db := newTestServer(t)
|
||||
seedRoutedVPC(t, db)
|
||||
w := postNATGateway(t, s, validNATGatewayRequest())
|
||||
if w.Code != http.StatusAccepted {
|
||||
t.Fatalf("attendu 202, obtenu %d : %s", w.Code, w.Body.String())
|
||||
}
|
||||
var got NATGateway
|
||||
json.NewDecoder(w.Body).Decode(&got)
|
||||
want := NATGateway{Name: "ng-1", State: "creating", VPC: "vp-s7", IP: "198.51.100.50/24", Gateway: "198.51.100.1"}
|
||||
if got != want {
|
||||
t.Errorf("réponse %+v, attendu %+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostNATGateway_BadRequest(t *testing.T) {
|
||||
cases := []struct {
|
||||
label string
|
||||
mutate func(*NATGatewayCreateRequest)
|
||||
msg string
|
||||
}{
|
||||
{"nom absent", func(r *NATGatewayCreateRequest) { r.Name = "" }, "name is required"},
|
||||
{"vpc absent", func(r *NATGatewayCreateRequest) { r.VPC = "" }, "vpc is required"},
|
||||
{"ip absente", func(r *NATGatewayCreateRequest) { r.IP = "" }, "ip is required"},
|
||||
{"gateway absente", func(r *NATGatewayCreateRequest) { r.Gateway = "" }, "gateway is required"},
|
||||
{"ip sans préfixe", func(r *NATGatewayCreateRequest) { r.IP = "198.51.100.50" }, "invalid ip"},
|
||||
{"ip IPv6", func(r *NATGatewayCreateRequest) { r.IP = "2001:db8::50/64" }, "invalid ip"},
|
||||
{"gateway invalide", func(r *NATGatewayCreateRequest) { r.Gateway = "bordure" }, "invalid gateway"},
|
||||
{"gateway IPv6", func(r *NATGatewayCreateRequest) { r.Gateway = "2001:db8::1" }, "invalid gateway"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
s, db := newTestServer(t)
|
||||
seedRoutedVPC(t, db)
|
||||
req := validNATGatewayRequest()
|
||||
c.mutate(&req)
|
||||
w := postNATGateway(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, "nat-gateway/ng-1/state"); err == nil {
|
||||
t.Errorf("%s : passerelle écrite malgré le refus", c.label)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostNATGateway_InvalidBody(t *testing.T) {
|
||||
s, _ := newTestServer(t)
|
||||
w := httptest.NewRecorder()
|
||||
s.NATGatewaysHandler(w, httptest.NewRequest(http.MethodPost, "/nat-gateways", bytes.NewReader([]byte("not json"))))
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("attendu 400, obtenu %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostNATGateway_ConflictWithoutRunningRoutedVPC(t *testing.T) {
|
||||
s, _ := newTestServer(t)
|
||||
w := postNATGateway(t, s, validNATGatewayRequest())
|
||||
if w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), `vpc \"vp-s7\" not found`) {
|
||||
t.Errorf("%d %s, 409 attendu", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestListNATGateways(t *testing.T) {
|
||||
s, db := newTestServer(t)
|
||||
kv.AddInDB(db, "nat-gateway/ng-1/state", "running")
|
||||
kv.AddInDB(db, "nat-gateway/ng-1/vpc", "vp-s7")
|
||||
kv.AddInDB(db, "nat-gateway/ng-1/ip", "198.51.100.50/24")
|
||||
kv.AddInDB(db, "nat-gateway/ng-1/gateway", "198.51.100.1")
|
||||
w := httptest.NewRecorder()
|
||||
s.NATGatewaysHandler(w, httptest.NewRequest(http.MethodGet, "/nat-gateways", nil))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("attendu 200, obtenu %d", w.Code)
|
||||
}
|
||||
var got []NATGateway
|
||||
json.NewDecoder(w.Body).Decode(&got)
|
||||
want := NATGateway{Name: "ng-1", State: "running", VPC: "vp-s7", IP: "198.51.100.50/24", Gateway: "198.51.100.1"}
|
||||
if len(got) != 1 || got[0] != want {
|
||||
t.Errorf("liste %+v, attendu [%+v]", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListNATGateways_Empty(t *testing.T) {
|
||||
s, _ := newTestServer(t)
|
||||
w := httptest.NewRecorder()
|
||||
s.NATGatewaysHandler(w, httptest.NewRequest(http.MethodGet, "/nat-gateways", nil))
|
||||
if w.Code != http.StatusOK || strings.TrimSpace(w.Body.String()) != "[]" {
|
||||
t.Errorf("%d %q, 200 [] attendu", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetNATGateway(t *testing.T) {
|
||||
s, db := newTestServer(t)
|
||||
kv.AddInDB(db, "nat-gateway/ng-1/state", "running")
|
||||
kv.AddInDB(db, "nat-gateway/ng-1/vpc", "vp-s7")
|
||||
w := httptest.NewRecorder()
|
||||
s.NATGatewayByNameHandler(w, httptest.NewRequest(http.MethodGet, "/nat-gateways/ng-1", nil))
|
||||
var got NATGateway
|
||||
json.NewDecoder(w.Body).Decode(&got)
|
||||
if w.Code != http.StatusOK || got.Name != "ng-1" || got.State != "running" || got.VPC != "vp-s7" {
|
||||
t.Errorf("%d %+v", w.Code, got)
|
||||
}
|
||||
w = httptest.NewRecorder()
|
||||
s.NATGatewayByNameHandler(w, httptest.NewRequest(http.MethodGet, "/nat-gateways/ng-x", nil))
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("passerelle absente : %d, 404 attendu", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteNATGateway(t *testing.T) {
|
||||
cases := map[string]int{"running": http.StatusAccepted, "error": http.StatusAccepted, "creating": http.StatusConflict, "": http.StatusNotFound}
|
||||
for st, want := range cases {
|
||||
s, db := newTestServer(t)
|
||||
if st != "" {
|
||||
kv.AddInDB(db, "nat-gateway/ng-1/state", st)
|
||||
kv.AddInDB(db, "nat-gateway/ng-1/vpc", "vp-s7")
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
s.NATGatewayByNameHandler(w, httptest.NewRequest(http.MethodDelete, "/nat-gateways/ng-1", nil))
|
||||
if w.Code != want {
|
||||
t.Errorf("état %q : %d, %d attendu (%s)", st, w.Code, want, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteVpc_BlockedByNATGateway(t *testing.T) {
|
||||
s, db := newTestServer(t)
|
||||
seedRoutedVPC(t, db)
|
||||
kv.AddInDB(db, "nat-gateway/ng-1/state", "running")
|
||||
kv.AddInDB(db, "nat-gateway/ng-1/vpc", "vp-s7")
|
||||
w := httptest.NewRecorder()
|
||||
s.VpcByNameHandler(w, httptest.NewRequest(http.MethodDelete, "/vpcs/vp-s7", nil))
|
||||
if w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), `nat gateway \"ng-1\" must be deleted`) {
|
||||
t.Errorf("%d %s, 409 attendu", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
100
internal/api/agent/natgws.go
Normal file
100
internal/api/agent/natgws.go
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
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) NATGatewaysHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
s.listNATGateways(w, r)
|
||||
case http.MethodPost:
|
||||
s.postNATGateway(w, r)
|
||||
default:
|
||||
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) listNATGateways(w http.ResponseWriter, _ *http.Request) {
|
||||
entries, err := kv.ListByPrefix(s.db, "nat-gateway/")
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
json.NewEncoder(w).Encode(ErrorResponse{Error: "failed to list nat gateways"})
|
||||
return
|
||||
}
|
||||
gateways := make(map[string]*NATGateway)
|
||||
for key, value := range entries {
|
||||
parts := strings.Split(key, "/")
|
||||
if len(parts) != 3 {
|
||||
continue
|
||||
}
|
||||
name := parts[1]
|
||||
if _, ok := gateways[name]; !ok {
|
||||
gateways[name] = &NATGateway{Name: name}
|
||||
}
|
||||
switch parts[2] {
|
||||
case "state":
|
||||
gateways[name].State = value
|
||||
case "vpc":
|
||||
gateways[name].VPC = value
|
||||
case "ip":
|
||||
gateways[name].IP = value
|
||||
case "gateway":
|
||||
gateways[name].Gateway = value
|
||||
}
|
||||
}
|
||||
result := make([]NATGateway, 0, len(gateways))
|
||||
for _, g := range gateways {
|
||||
result = append(result, *g)
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(result)
|
||||
}
|
||||
|
||||
func (s *Server) postNATGateway(w http.ResponseWriter, r *http.Request) {
|
||||
var req NATGatewayCreateRequest
|
||||
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}, {"vpc", req.VPC}, {"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.CreateNATGatewayCommand{Name: req.Name, VPC: req.VPC, 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, "nat-gateway/"+req.Name+"/state")
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
json.NewEncoder(w).Encode(ErrorResponse{Error: "failed to read nat gateway state"})
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
json.NewEncoder(w).Encode(NATGateway{Name: req.Name, State: state, VPC: req.VPC, IP: req.IP, Gateway: req.Gateway})
|
||||
}
|
||||
|
|
@ -29,6 +29,8 @@ func New(d *dispatcher.Dispatcher, db *badger.DB, logger *slog.Logger, address s
|
|||
mux.HandleFunc("/subnets/", s.SubnetByNameHandler)
|
||||
mux.HandleFunc("/vms", s.VmsHandler)
|
||||
mux.HandleFunc("/vms/", s.VmByNameHandler)
|
||||
mux.HandleFunc("/nat-gateways", s.NATGatewaysHandler)
|
||||
mux.HandleFunc("/nat-gateways/", s.NATGatewayByNameHandler)
|
||||
s.srv = &http.Server{Addr: address, Handler: s.logMiddleware(mux)}
|
||||
return s
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue