From ca8f86a07f0e02e4417d7a59246ea5511efa6df3 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Sun, 12 Apr 2026 17:29:14 +0200 Subject: [PATCH 01/23] f-21: api: add openapi file Signed-off-by: GnomeZworc --- api/openapi.yaml | 296 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 296 insertions(+) create mode 100644 api/openapi.yaml diff --git a/api/openapi.yaml b/api/openapi.yaml new file mode 100644 index 0000000..be328d0 --- /dev/null +++ b/api/openapi.yaml @@ -0,0 +1,296 @@ +openapi: "3.1.0" +info: + title: Two API + version: "0.1.0" + description: REST API for managing VPCs and Subnets in the Two orchestrator. + +servers: + - url: http://localhost:8080 + description: Local development server + +paths: + + # ── VPC ──────────────────────────────────────────────────────────────────── + + /vpcs: + get: + summary: List all VPCs + operationId: listVPCs + responses: + "200": + description: List of VPCs + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/VPC" + "500": + $ref: "#/components/responses/InternalError" + + post: + summary: Create a VPC + operationId: createVPC + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/VPCCreateRequest" + responses: + "202": + description: VPC creation accepted + content: + application/json: + schema: + $ref: "#/components/schemas/VPC" + "409": + description: VPC already exists + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "500": + $ref: "#/components/responses/InternalError" + + /vpcs/{name}: + parameters: + - $ref: "#/components/parameters/ResourceName" + + get: + summary: Get VPC status and info + operationId: getVPC + responses: + "200": + description: VPC found + content: + application/json: + schema: + $ref: "#/components/schemas/VPC" + "404": + $ref: "#/components/responses/NotFound" + "500": + $ref: "#/components/responses/InternalError" + + delete: + summary: Delete a VPC + operationId: deleteVPC + responses: + "202": + description: VPC deletion accepted + content: + application/json: + schema: + $ref: "#/components/schemas/VPC" + "404": + $ref: "#/components/responses/NotFound" + "409": + description: VPC not in a deletable state + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "500": + $ref: "#/components/responses/InternalError" + + # ── Subnet ───────────────────────────────────────────────────────────────── + + /subnets: + get: + summary: List all subnets + operationId: listSubnets + responses: + "200": + description: List of subnets + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/Subnet" + "500": + $ref: "#/components/responses/InternalError" + + post: + summary: Create a subnet + operationId: createSubnet + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/SubnetCreateRequest" + responses: + "202": + description: Subnet creation accepted + content: + application/json: + schema: + $ref: "#/components/schemas/Subnet" + "409": + description: Subnet already exists + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "422": + description: Parent VPC does not exist or is not ready + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "500": + $ref: "#/components/responses/InternalError" + + /subnets/{name}: + parameters: + - $ref: "#/components/parameters/ResourceName" + + get: + summary: Get subnet status and info + operationId: getSubnet + responses: + "200": + description: Subnet found + content: + application/json: + schema: + $ref: "#/components/schemas/Subnet" + "404": + $ref: "#/components/responses/NotFound" + "500": + $ref: "#/components/responses/InternalError" + + delete: + summary: Delete a subnet + operationId: deleteSubnet + responses: + "202": + description: Subnet deletion accepted + content: + application/json: + schema: + $ref: "#/components/schemas/Subnet" + "404": + $ref: "#/components/responses/NotFound" + "409": + description: Subnet not in a deletable state + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "500": + $ref: "#/components/responses/InternalError" + +# ── Components ────────────────────────────────────────────────────────────── + +components: + + parameters: + ResourceName: + name: name + in: path + required: true + schema: + type: string + description: Resource name + + schemas: + + VPCCreateRequest: + type: object + required: [name] + properties: + name: + type: string + description: Unique name for the VPC + example: vpc1 + + VPC: + type: object + properties: + name: + type: string + example: vpc1 + state: + type: string + enum: [creating, created, deleting, deleted] + example: created + + SubnetCreateRequest: + type: object + required: [name, vpc, vxlan_id, local_ip, gateway_ip, cidr] + properties: + name: + type: string + description: Unique name for the subnet + example: sn-00001 + vpc: + type: string + description: Parent VPC name + example: vpc1 + vxlan_id: + type: integer + description: VXLAN VNI identifier + example: 100 + local_ip: + type: string + format: ipv4 + description: Local VTEP IP address + example: "10.0.0.5" + gateway_ip: + type: string + format: ipv4 + description: Gateway IP for the subnet + example: "10.10.10.1" + cidr: + type: string + description: Subnet CIDR block + example: "10.10.10.0/24" + + Subnet: + type: object + properties: + name: + type: string + example: sn-00001 + state: + type: string + enum: [creating, created, deleting, deleted] + example: created + vpc: + type: string + example: vpc1 + vxlan_id: + type: integer + example: 100 + local_ip: + type: string + example: "10.0.0.5" + gateway_ip: + type: string + example: "10.10.10.1" + cidr: + type: string + example: "10.10.10.0/24" + + Error: + type: object + properties: + error: + type: string + example: "resource not found" + + responses: + NotFound: + description: Resource not found + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + InternalError: + description: Internal server error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" From 9ad407755b73a40a78d2d9fe34cb55fc3956957a Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Sun, 12 Apr 2026 17:29:37 +0200 Subject: [PATCH 02/23] f-21: add first api file Signed-off-by: GnomeZworc --- internal/api/agent/server.go | 16 ++++++++++++++++ internal/api/agent/subnet.go | 25 +++++++++++++++++++++++++ internal/api/agent/subnets.go | 19 +++++++++++++++++++ internal/api/agent/vpc.go | 25 +++++++++++++++++++++++++ internal/api/agent/vpcs.go | 19 +++++++++++++++++++ 5 files changed, 104 insertions(+) create mode 100644 internal/api/agent/server.go create mode 100644 internal/api/agent/subnet.go create mode 100644 internal/api/agent/subnets.go create mode 100644 internal/api/agent/vpc.go create mode 100644 internal/api/agent/vpcs.go diff --git a/internal/api/agent/server.go b/internal/api/agent/server.go new file mode 100644 index 0000000..05653a4 --- /dev/null +++ b/internal/api/agent/server.go @@ -0,0 +1,16 @@ +package agentapi + +import ( + "log" + "net/http" +) + +func Start(address string) { + mux := http.NewServeMux() + mux.HandleFunc("/vpcs", VpcsHandler) + mux.HandleFunc("/vpcs/", VpcByNameHandler) + mux.HandleFunc("/subnets", SubnetsHandler) + mux.HandleFunc("/subnets/", SubnetByNameHandler) + log.Printf("API server listening on %s", address) + log.Fatal(http.ListenAndServe(address, mux)) +} diff --git a/internal/api/agent/subnet.go b/internal/api/agent/subnet.go new file mode 100644 index 0000000..e46e4f4 --- /dev/null +++ b/internal/api/agent/subnet.go @@ -0,0 +1,25 @@ +package agentapi + +import ( + "encoding/json" + "net/http" + "strings" +) + +func SubnetByNameHandler(w http.ResponseWriter, r *http.Request) { + name := strings.TrimPrefix(r.URL.Path, "/subnets/") + if name == "" { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + switch r.Method { + case http.MethodGet: + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(map[string]string{"name": name}) + case http.MethodDelete: + w.WriteHeader(http.StatusAccepted) + default: + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } +} diff --git a/internal/api/agent/subnets.go b/internal/api/agent/subnets.go new file mode 100644 index 0000000..53dce2e --- /dev/null +++ b/internal/api/agent/subnets.go @@ -0,0 +1,19 @@ +package agentapi + +import ( + "encoding/json" + "net/http" +) + +func SubnetsHandler(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.Method { + case http.MethodGet: + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode([]interface{}{}) + case http.MethodPost: + w.WriteHeader(http.StatusAccepted) + default: + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } +} diff --git a/internal/api/agent/vpc.go b/internal/api/agent/vpc.go new file mode 100644 index 0000000..aecfaa1 --- /dev/null +++ b/internal/api/agent/vpc.go @@ -0,0 +1,25 @@ +package agentapi + +import ( + "encoding/json" + "net/http" + "strings" +) + +func VpcByNameHandler(w http.ResponseWriter, r *http.Request) { + name := strings.TrimPrefix(r.URL.Path, "/vpcs/") + if name == "" { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + switch r.Method { + case http.MethodGet: + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(map[string]string{"name": name}) + case http.MethodDelete: + w.WriteHeader(http.StatusAccepted) + default: + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } +} diff --git a/internal/api/agent/vpcs.go b/internal/api/agent/vpcs.go new file mode 100644 index 0000000..c4e9b27 --- /dev/null +++ b/internal/api/agent/vpcs.go @@ -0,0 +1,19 @@ +package agentapi + +import ( + "encoding/json" + "net/http" +) + +func VpcsHandler(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.Method { + case http.MethodGet: + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode([]interface{}{}) + case http.MethodPost: + w.WriteHeader(http.StatusAccepted) + default: + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } +} From 32669371d6c90d23b06583c67f73d9b3bca5eecd Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Sun, 12 Apr 2026 17:30:07 +0200 Subject: [PATCH 03/23] f-21: mon: add prometheus data Signed-off-by: GnomeZworc --- internal/prometheus/agent/collector.go | 67 ++++++++++++++++++++++++++ pkg/prometheus/server.go | 20 ++++++++ 2 files changed, 87 insertions(+) create mode 100644 internal/prometheus/agent/collector.go create mode 100644 pkg/prometheus/server.go diff --git a/internal/prometheus/agent/collector.go b/internal/prometheus/agent/collector.go new file mode 100644 index 0000000..04712ad --- /dev/null +++ b/internal/prometheus/agent/collector.go @@ -0,0 +1,67 @@ +package agentmetrics + +import ( + "strings" + + "git.g3e.fr/syonad/two/pkg/db/kv" + "github.com/dgraph-io/badger/v4" + "github.com/prometheus/client_golang/prometheus" +) + +var allStates = []string{"creating", "created", "deleting", "deleted"} + +// AgentCollector implements prometheus.Collector and exposes agent metrics +// by querying the BadgerDB on each scrape. +type AgentCollector struct { + db *badger.DB + vpcsTotal *prometheus.Desc + subnetsTotal *prometheus.Desc +} + +func NewAgentCollector(db *badger.DB) *AgentCollector { + return &AgentCollector{ + db: db, + vpcsTotal: prometheus.NewDesc( + "syonad_vpcs_total", + "Number of VPCs by state.", + []string{"state"}, nil, + ), + subnetsTotal: prometheus.NewDesc( + "syonad_subnets_total", + "Number of subnets by state.", + []string{"state"}, nil, + ), + } +} + +func (c *AgentCollector) Describe(ch chan<- *prometheus.Desc) { + ch <- c.vpcsTotal + ch <- c.subnetsTotal +} + +func (c *AgentCollector) Collect(ch chan<- prometheus.Metric) { + c.collectStates(ch, "vpc/", c.vpcsTotal) + c.collectStates(ch, "subnet/", c.subnetsTotal) +} + +// collectStates counts resources under the given DB prefix by their state value +// and emits one gauge per state label. +func (c *AgentCollector) collectStates(ch chan<- prometheus.Metric, prefix string, desc *prometheus.Desc) { + counts := make(map[string]float64, len(allStates)) + for _, s := range allStates { + counts[s] = 0 + } + + items, err := kv.ListByPrefix(c.db, prefix) + if err == nil { + for key, val := range items { + if strings.HasSuffix(key, "/state") { + counts[val]++ + } + } + } + + for _, state := range allStates { + ch <- prometheus.MustNewConstMetric(desc, prometheus.GaugeValue, counts[state], state) + } +} diff --git a/pkg/prometheus/server.go b/pkg/prometheus/server.go new file mode 100644 index 0000000..9f8e557 --- /dev/null +++ b/pkg/prometheus/server.go @@ -0,0 +1,20 @@ +package promserver + +import ( + "log" + "net/http" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" +) + +// Start launches the Prometheus metrics HTTP server on the given address. +// The provided registry is used to expose metrics at /metrics. +func Start(address string, registry *prometheus.Registry) { + mux := http.NewServeMux() + mux.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{ + EnableOpenMetrics: true, + })) + log.Printf("Prometheus server listening on %s", address) + log.Fatal(http.ListenAndServe(address, mux)) +} From 94a14dbe604f72627dc5ef446a116e3347f4157b Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Sun, 12 Apr 2026 17:30:36 +0200 Subject: [PATCH 04/23] f-21: code: add list prefix Signed-off-by: GnomeZworc --- pkg/db/kv/listByPrefix.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 pkg/db/kv/listByPrefix.go diff --git a/pkg/db/kv/listByPrefix.go b/pkg/db/kv/listByPrefix.go new file mode 100644 index 0000000..e6c095e --- /dev/null +++ b/pkg/db/kv/listByPrefix.go @@ -0,0 +1,33 @@ +package kv + +import ( + "github.com/dgraph-io/badger/v4" +) + +// ListByPrefix returns all key-value pairs whose key starts with prefix. +func ListByPrefix(db *badger.DB, prefix string) (map[string]string, error) { + result := make(map[string]string) + p := []byte(prefix) + + err := db.View(func(txn *badger.Txn) error { + opts := badger.DefaultIteratorOptions + opts.PrefetchSize = 10 + + it := txn.NewIterator(opts) + defer it.Close() + + for it.Seek(p); it.ValidForPrefix(p); it.Next() { + item := it.Item() + key := string(item.Key()) + + val, err := item.ValueCopy(nil) + if err != nil { + return err + } + result[key] = string(val) + } + return nil + }) + + return result, err +} From 1bb3681b68b0c3a6bd41e98ea1e965d3466e6c76 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Sun, 12 Apr 2026 17:30:58 +0200 Subject: [PATCH 05/23] f-21: config: add config data Signed-off-by: GnomeZworc --- internal/config/agent/struct.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/internal/config/agent/struct.go b/internal/config/agent/struct.go index c9537bf..0cca127 100644 --- a/internal/config/agent/struct.go +++ b/internal/config/agent/struct.go @@ -8,6 +8,14 @@ type Config struct { Database struct { Path string `mapstructure:"path"` } `mapstructure:"database"` + Api struct { + Address string `mapstructure:"address"` + Port int `mapstructure:"port"` + } `mapstructure:"api"` + Prometheus struct { + Address string `mapstructure:"address"` + Port int `mapstructure:"port"` + } `mapstructure:"prometheus"` } func LoadConfig(path string) (*Config, error) { @@ -16,6 +24,10 @@ func LoadConfig(path string) (*Config, error) { v.SetConfigType("yaml") v.SetDefault("database.path", "/var/lib/two/data/") + v.SetDefault("api.address", "") + v.SetDefault("api.port", 8080) + v.SetDefault("prometheus.address", "") + v.SetDefault("prometheus.port", 9090) v.ReadInConfig() From 544016cefe1812bb04f6f6c46fe3fab0e90aca82 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Sun, 12 Apr 2026 17:31:24 +0200 Subject: [PATCH 06/23] f-21: agent: implement api first Signed-off-by: GnomeZworc --- cmd/agent/main.go | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/cmd/agent/main.go b/cmd/agent/main.go index 0f82e93..ce3df4e 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -1,17 +1,38 @@ package main import ( + "flag" "fmt" - "os" -) + "log" -var ( - bin_name = os.Args[0] + agentapi "git.g3e.fr/syonad/two/internal/api/agent" + agentmetrics "git.g3e.fr/syonad/two/internal/prometheus/agent" + configuration "git.g3e.fr/syonad/two/internal/config/agent" + promserver "git.g3e.fr/syonad/two/pkg/prometheus" + "git.g3e.fr/syonad/two/pkg/db/kv" + "github.com/prometheus/client_golang/prometheus" ) func main() { + confFile := flag.String("config", "/etc/two/agent.yml", "config file path") + flag.Parse() - fmt.Printf("%s: Start process\n", bin_name) + cfg, err := configuration.LoadConfig(*confFile) + if err != nil { + log.Fatalf("failed to load config: %v", err) + } - os.Exit(0) + db := kv.InitDB(kv.Config{Path: cfg.Database.Path}, true) + defer db.Close() + + apiAddr := fmt.Sprintf("%s:%d", cfg.Api.Address, cfg.Api.Port) + promAddr := fmt.Sprintf("%s:%d", cfg.Prometheus.Address, cfg.Prometheus.Port) + + registry := prometheus.NewRegistry() + registry.MustRegister(agentmetrics.NewAgentCollector(db)) + + go agentapi.Start(apiAddr) + go promserver.Start(promAddr, registry) + + select {} } From e1f7676093218ca55c515eace4a8ebc080f76cb3 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Sun, 12 Apr 2026 17:31:42 +0200 Subject: [PATCH 07/23] f-21: go: add import lib Signed-off-by: GnomeZworc --- go.mod | 11 +++++++++-- go.sum | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/go.mod b/go.mod index 7430e72..a4b0b38 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.24.0 toolchain go1.24.11 require ( + github.com/beorn7/perks v1.0.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/coreos/go-systemd/v22 v22.6.0 // indirect github.com/dgraph-io/badger/v4 v4.8.0 // indirect @@ -17,7 +18,12 @@ require ( github.com/godbus/dbus/v5 v5.1.0 // indirect github.com/google/flatbuffers v25.2.10+incompatible // indirect github.com/klauspost/compress v1.18.0 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect + github.com/prometheus/client_golang v1.23.2 // indirect + github.com/prometheus/client_model v0.6.2 // indirect + github.com/prometheus/common v0.66.1 // indirect + github.com/prometheus/procfs v0.16.1 // indirect github.com/sagikazarmark/locafero v0.11.0 // indirect github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect github.com/spf13/afero v1.15.0 // indirect @@ -31,9 +37,10 @@ require ( go.opentelemetry.io/otel v1.37.0 // indirect go.opentelemetry.io/otel/metric v1.37.0 // indirect go.opentelemetry.io/otel/trace v1.37.0 // indirect + go.yaml.in/yaml/v2 v2.4.2 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect - golang.org/x/net v0.41.0 // indirect + golang.org/x/net v0.43.0 // indirect golang.org/x/sys v0.39.0 // indirect golang.org/x/text v0.28.0 // indirect - google.golang.org/protobuf v1.36.6 // indirect + google.golang.org/protobuf v1.36.8 // indirect ) diff --git a/go.sum b/go.sum index 73d16f3..402452d 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/coreos/go-systemd/v22 v22.6.0 h1:aGVa/v8B7hpb0TKl0MWoAavPDmHvobFe5R5zn0bCJWo= @@ -23,8 +25,18 @@ github.com/google/flatbuffers v25.2.10+incompatible h1:F3vclr7C3HpB1k9mxCGRMXq6F github.com/google/flatbuffers v25.2.10+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= +github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= +github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= +github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= +github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs= +github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA= +github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg= +github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is= github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik= github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw= @@ -51,10 +63,14 @@ go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/Wgbsd go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E= go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4= go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0= +go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI= +go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU= 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/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw= golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA= +golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE= +golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA= @@ -65,4 +81,6 @@ golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng= golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU= google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= +google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc= +google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= From 8637c33bd8f7f7dda132a6706611734bfd1b3ae6 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Tue, 14 Apr 2026 21:24:13 +0200 Subject: [PATCH 08/23] f-21: code: ajout d'un system de worker Signed-off-by: GnomeZworc --- cmd/agent/main.go | 14 +++++++++----- internal/api/agent/server.go | 20 +++++++++++++++----- internal/api/agent/subnet.go | 7 ++++++- internal/api/agent/subnets.go | 7 ++++++- internal/api/agent/vpc.go | 7 ++++++- internal/api/agent/vpcs.go | 7 ++++++- internal/config/agent/struct.go | 6 ++++++ pkg/worker/queue.go | 33 +++++++++++++++++++++++++++++++++ 8 files changed, 87 insertions(+), 14 deletions(-) create mode 100644 pkg/worker/queue.go diff --git a/cmd/agent/main.go b/cmd/agent/main.go index ce3df4e..56011bf 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -6,10 +6,11 @@ import ( "log" agentapi "git.g3e.fr/syonad/two/internal/api/agent" - agentmetrics "git.g3e.fr/syonad/two/internal/prometheus/agent" configuration "git.g3e.fr/syonad/two/internal/config/agent" - promserver "git.g3e.fr/syonad/two/pkg/prometheus" + agentmetrics "git.g3e.fr/syonad/two/internal/prometheus/agent" "git.g3e.fr/syonad/two/pkg/db/kv" + promserver "git.g3e.fr/syonad/two/pkg/prometheus" + "git.g3e.fr/syonad/two/pkg/worker" "github.com/prometheus/client_golang/prometheus" ) @@ -25,13 +26,16 @@ func main() { db := kv.InitDB(kv.Config{Path: cfg.Database.Path}, true) defer db.Close() - apiAddr := fmt.Sprintf("%s:%d", cfg.Api.Address, cfg.Api.Port) - promAddr := fmt.Sprintf("%s:%d", cfg.Prometheus.Address, cfg.Prometheus.Port) + q := worker.New(cfg.Worker.BufferSize) + q.Start(cfg.Worker.Count) registry := prometheus.NewRegistry() registry.MustRegister(agentmetrics.NewAgentCollector(db)) - go agentapi.Start(apiAddr) + apiAddr := fmt.Sprintf("%s:%d", cfg.Api.Address, cfg.Api.Port) + promAddr := fmt.Sprintf("%s:%d", cfg.Prometheus.Address, cfg.Prometheus.Port) + + go agentapi.New(q).Start(apiAddr) go promserver.Start(promAddr, registry) select {} diff --git a/internal/api/agent/server.go b/internal/api/agent/server.go index 05653a4..aebe2c3 100644 --- a/internal/api/agent/server.go +++ b/internal/api/agent/server.go @@ -3,14 +3,24 @@ package agentapi import ( "log" "net/http" + + "git.g3e.fr/syonad/two/pkg/worker" ) -func Start(address string) { +type Server struct { + queue *worker.Queue +} + +func New(queue *worker.Queue) *Server { + return &Server{queue: queue} +} + +func (s *Server) Start(address string) { mux := http.NewServeMux() - mux.HandleFunc("/vpcs", VpcsHandler) - mux.HandleFunc("/vpcs/", VpcByNameHandler) - mux.HandleFunc("/subnets", SubnetsHandler) - mux.HandleFunc("/subnets/", SubnetByNameHandler) + mux.HandleFunc("/vpcs", s.VpcsHandler) + mux.HandleFunc("/vpcs/", s.VpcByNameHandler) + mux.HandleFunc("/subnets", s.SubnetsHandler) + mux.HandleFunc("/subnets/", s.SubnetByNameHandler) log.Printf("API server listening on %s", address) log.Fatal(http.ListenAndServe(address, mux)) } diff --git a/internal/api/agent/subnet.go b/internal/api/agent/subnet.go index e46e4f4..52b27d0 100644 --- a/internal/api/agent/subnet.go +++ b/internal/api/agent/subnet.go @@ -6,7 +6,7 @@ import ( "strings" ) -func SubnetByNameHandler(w http.ResponseWriter, r *http.Request) { +func (s *Server) SubnetByNameHandler(w http.ResponseWriter, r *http.Request) { name := strings.TrimPrefix(r.URL.Path, "/subnets/") if name == "" { http.NotFound(w, r) @@ -18,8 +18,13 @@ func SubnetByNameHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(map[string]string{"name": name}) case http.MethodDelete: + s.queue.Submit(func() { + deleteSubnet(name) + }) w.WriteHeader(http.StatusAccepted) default: http.Error(w, "method not allowed", http.StatusMethodNotAllowed) } } + +func deleteSubnet(name string) {} diff --git a/internal/api/agent/subnets.go b/internal/api/agent/subnets.go index 53dce2e..b3d587b 100644 --- a/internal/api/agent/subnets.go +++ b/internal/api/agent/subnets.go @@ -5,15 +5,20 @@ import ( "net/http" ) -func SubnetsHandler(w http.ResponseWriter, r *http.Request) { +func (s *Server) SubnetsHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch r.Method { case http.MethodGet: w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode([]interface{}{}) case http.MethodPost: + s.queue.Submit(func() { + createSubnet() + }) w.WriteHeader(http.StatusAccepted) default: http.Error(w, "method not allowed", http.StatusMethodNotAllowed) } } + +func createSubnet() {} diff --git a/internal/api/agent/vpc.go b/internal/api/agent/vpc.go index aecfaa1..73cecd9 100644 --- a/internal/api/agent/vpc.go +++ b/internal/api/agent/vpc.go @@ -6,7 +6,7 @@ import ( "strings" ) -func VpcByNameHandler(w http.ResponseWriter, r *http.Request) { +func (s *Server) VpcByNameHandler(w http.ResponseWriter, r *http.Request) { name := strings.TrimPrefix(r.URL.Path, "/vpcs/") if name == "" { http.NotFound(w, r) @@ -18,8 +18,13 @@ func VpcByNameHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(map[string]string{"name": name}) case http.MethodDelete: + s.queue.Submit(func() { + deleteVpc(name) + }) w.WriteHeader(http.StatusAccepted) default: http.Error(w, "method not allowed", http.StatusMethodNotAllowed) } } + +func deleteVpc(name string) {} diff --git a/internal/api/agent/vpcs.go b/internal/api/agent/vpcs.go index c4e9b27..57386b6 100644 --- a/internal/api/agent/vpcs.go +++ b/internal/api/agent/vpcs.go @@ -5,15 +5,20 @@ import ( "net/http" ) -func VpcsHandler(w http.ResponseWriter, r *http.Request) { +func (s *Server) VpcsHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch r.Method { case http.MethodGet: w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode([]interface{}{}) case http.MethodPost: + s.queue.Submit(func() { + createVpc() + }) w.WriteHeader(http.StatusAccepted) default: http.Error(w, "method not allowed", http.StatusMethodNotAllowed) } } + +func createVpc() {} diff --git a/internal/config/agent/struct.go b/internal/config/agent/struct.go index 0cca127..24ad0f5 100644 --- a/internal/config/agent/struct.go +++ b/internal/config/agent/struct.go @@ -16,6 +16,10 @@ type Config struct { Address string `mapstructure:"address"` Port int `mapstructure:"port"` } `mapstructure:"prometheus"` + Worker struct { + Count int `mapstructure:"count"` + BufferSize int `mapstructure:"buffer_size"` + } `mapstructure:"worker"` } func LoadConfig(path string) (*Config, error) { @@ -28,6 +32,8 @@ func LoadConfig(path string) (*Config, error) { v.SetDefault("api.port", 8080) v.SetDefault("prometheus.address", "") v.SetDefault("prometheus.port", 9090) + v.SetDefault("worker.count", 4) + v.SetDefault("worker.buffer_size", 100) v.ReadInConfig() diff --git a/pkg/worker/queue.go b/pkg/worker/queue.go new file mode 100644 index 0000000..109c726 --- /dev/null +++ b/pkg/worker/queue.go @@ -0,0 +1,33 @@ +package worker + +import "log" + +// Task is a function to be executed asynchronously by a worker. +type Task func() + +// Queue is a FIFO channel-backed task queue consumed by worker goroutines. +type Queue struct { + tasks chan Task +} + +// New creates a Queue with the given channel buffer size. +func New(bufferSize int) *Queue { + return &Queue{tasks: make(chan Task, bufferSize)} +} + +// Submit enqueues a task. Blocks if the queue is full. +func (q *Queue) Submit(t Task) { + q.tasks <- t +} + +// Start launches n worker goroutines that consume and execute tasks. +func (q *Queue) Start(n int) { + log.Printf("worker: starting %d workers", n) + for i := range n { + go func(id int) { + for task := range q.tasks { + task() + } + }(i) + } +} From 24536ed89104198d795fb7167d4c8cc3183ee6d3 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Thu, 16 Apr 2026 22:40:27 +0200 Subject: [PATCH 09/23] f-21: code: set db tu readwrite Signed-off-by: GnomeZworc --- cmd/agent/main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/agent/main.go b/cmd/agent/main.go index 56011bf..5ebf09f 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -23,7 +23,7 @@ func main() { log.Fatalf("failed to load config: %v", err) } - db := kv.InitDB(kv.Config{Path: cfg.Database.Path}, true) + db := kv.InitDB(kv.Config{Path: cfg.Database.Path}, false) defer db.Close() q := worker.New(cfg.Worker.BufferSize) From 75e02bd4f7f05692211b3083786c031fbe893c31 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Thu, 16 Apr 2026 22:57:20 +0200 Subject: [PATCH 10/23] f-21: code: separate and create route fonction Signed-off-by: GnomeZworc --- internal/api/agent/models.go | 33 ++++++++++++++++++++++++++ internal/api/agent/server.go | 9 ++++++- internal/api/agent/subnet.go | 29 ++++++++++++++++------- internal/api/agent/subnets.go | 44 ++++++++++++++++++++++++++++------- internal/api/agent/vpc.go | 29 ++++++++++++++++------- internal/api/agent/vpcs.go | 36 +++++++++++++++++++++------- 6 files changed, 145 insertions(+), 35 deletions(-) create mode 100644 internal/api/agent/models.go diff --git a/internal/api/agent/models.go b/internal/api/agent/models.go new file mode 100644 index 0000000..bd09c76 --- /dev/null +++ b/internal/api/agent/models.go @@ -0,0 +1,33 @@ +package agentapi + +type VPCCreateRequest struct { + Name string `json:"name"` +} + +type VPC struct { + Name string `json:"name"` + State string `json:"state"` +} + +type SubnetCreateRequest struct { + Name string `json:"name"` + VPC string `json:"vpc"` + VxlanID int `json:"vxlan_id"` + LocalIP string `json:"local_ip"` + GatewayIP string `json:"gateway_ip"` + CIDR string `json:"cidr"` +} + +type Subnet struct { + Name string `json:"name"` + State string `json:"state"` + VPC string `json:"vpc"` + VxlanID int `json:"vxlan_id"` + LocalIP string `json:"local_ip"` + GatewayIP string `json:"gateway_ip"` + CIDR string `json:"cidr"` +} + +type ErrorResponse struct { + Error string `json:"error"` +} diff --git a/internal/api/agent/server.go b/internal/api/agent/server.go index aebe2c3..75833c9 100644 --- a/internal/api/agent/server.go +++ b/internal/api/agent/server.go @@ -22,5 +22,12 @@ func (s *Server) Start(address string) { mux.HandleFunc("/subnets", s.SubnetsHandler) mux.HandleFunc("/subnets/", s.SubnetByNameHandler) log.Printf("API server listening on %s", address) - log.Fatal(http.ListenAndServe(address, mux)) + log.Fatal(http.ListenAndServe(address, logMiddleware(mux))) +} + +func logMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + log.Printf("%s %s %s", r.RemoteAddr, r.Method, r.URL.Path) + next.ServeHTTP(w, r) + }) } diff --git a/internal/api/agent/subnet.go b/internal/api/agent/subnet.go index 52b27d0..289667f 100644 --- a/internal/api/agent/subnet.go +++ b/internal/api/agent/subnet.go @@ -9,22 +9,33 @@ import ( func (s *Server) SubnetByNameHandler(w http.ResponseWriter, r *http.Request) { name := strings.TrimPrefix(r.URL.Path, "/subnets/") if name == "" { - http.NotFound(w, r) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) + json.NewEncoder(w).Encode(ErrorResponse{Error: "resource not found"}) return } w.Header().Set("Content-Type", "application/json") switch r.Method { case http.MethodGet: - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(map[string]string{"name": name}) + s.getSubnet(w, r, name) case http.MethodDelete: - s.queue.Submit(func() { - deleteSubnet(name) - }) - w.WriteHeader(http.StatusAccepted) + s.deleteSubnet(w, r, name) default: - http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed) } } -func deleteSubnet(name string) {} +func (s *Server) getSubnet(w http.ResponseWriter, r *http.Request, name string) { + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(Subnet{Name: name, State: "created"}) +} + +func (s *Server) deleteSubnet(w http.ResponseWriter, r *http.Request, name string) { + s.queue.Submit(func() { + destroySubnet(name) + }) + w.WriteHeader(http.StatusAccepted) + json.NewEncoder(w).Encode(Subnet{Name: name, State: "deleting"}) +} + +func destroySubnet(name string) {} diff --git a/internal/api/agent/subnets.go b/internal/api/agent/subnets.go index b3d587b..5e0ebdc 100644 --- a/internal/api/agent/subnets.go +++ b/internal/api/agent/subnets.go @@ -9,16 +9,44 @@ func (s *Server) SubnetsHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch r.Method { case http.MethodGet: - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode([]interface{}{}) + s.listSubnets(w, r) case http.MethodPost: - s.queue.Submit(func() { - createSubnet() - }) - w.WriteHeader(http.StatusAccepted) + s.postSubnet(w, r) default: - http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed) } } -func createSubnet() {} +func (s *Server) listSubnets(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode([]Subnet{}) +} + +func (s *Server) postSubnet(w http.ResponseWriter, r *http.Request) { + var req SubnetCreateRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{Error: "invalid request body"}) + return + } + if req.Name == "" || req.VPC == "" || req.LocalIP == "" || req.GatewayIP == "" || req.CIDR == "" { + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{Error: "name, vpc, local_ip, gateway_ip and cidr are required"}) + return + } + s.queue.Submit(func() { + createSubnet(req) + }) + w.WriteHeader(http.StatusAccepted) + json.NewEncoder(w).Encode(Subnet{ + Name: req.Name, + State: "creating", + VPC: req.VPC, + VxlanID: req.VxlanID, + LocalIP: req.LocalIP, + GatewayIP: req.GatewayIP, + CIDR: req.CIDR, + }) +} + +func createSubnet(req SubnetCreateRequest) {} diff --git a/internal/api/agent/vpc.go b/internal/api/agent/vpc.go index 73cecd9..f1d34c1 100644 --- a/internal/api/agent/vpc.go +++ b/internal/api/agent/vpc.go @@ -9,22 +9,33 @@ import ( func (s *Server) VpcByNameHandler(w http.ResponseWriter, r *http.Request) { name := strings.TrimPrefix(r.URL.Path, "/vpcs/") if name == "" { - http.NotFound(w, r) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) + json.NewEncoder(w).Encode(ErrorResponse{Error: "resource not found"}) return } w.Header().Set("Content-Type", "application/json") switch r.Method { case http.MethodGet: - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(map[string]string{"name": name}) + s.getVpc(w, r, name) case http.MethodDelete: - s.queue.Submit(func() { - deleteVpc(name) - }) - w.WriteHeader(http.StatusAccepted) + s.deleteVpc(w, r, name) default: - http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed) } } -func deleteVpc(name string) {} +func (s *Server) getVpc(w http.ResponseWriter, r *http.Request, name string) { + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(VPC{Name: name, State: "created"}) +} + +func (s *Server) deleteVpc(w http.ResponseWriter, r *http.Request, name string) { + s.queue.Submit(func() { + destroyVpc(name) + }) + w.WriteHeader(http.StatusAccepted) + json.NewEncoder(w).Encode(VPC{Name: name, State: "deleting"}) +} + +func destroyVpc(name string) {} diff --git a/internal/api/agent/vpcs.go b/internal/api/agent/vpcs.go index 57386b6..aba4e7a 100644 --- a/internal/api/agent/vpcs.go +++ b/internal/api/agent/vpcs.go @@ -9,16 +9,36 @@ func (s *Server) VpcsHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch r.Method { case http.MethodGet: - w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode([]interface{}{}) + s.listVpcs(w, r) case http.MethodPost: - s.queue.Submit(func() { - createVpc() - }) - w.WriteHeader(http.StatusAccepted) + s.postVpc(w, r) default: - http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed) } } -func createVpc() {} +func (s *Server) listVpcs(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode([]VPC{}) +} + +func (s *Server) postVpc(w http.ResponseWriter, r *http.Request) { + var req VPCCreateRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{Error: "invalid request body"}) + return + } + if req.Name == "" { + w.WriteHeader(http.StatusBadRequest) + json.NewEncoder(w).Encode(ErrorResponse{Error: "name is required"}) + return + } + s.queue.Submit(func() { + createVpc(req.Name) + }) + w.WriteHeader(http.StatusAccepted) + json.NewEncoder(w).Encode(VPC{Name: req.Name, State: "creating"}) +} + +func createVpc(name string) {} From b0c73b29522bdf6660ea1de898ee62fe9d4c7e25 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Thu, 16 Apr 2026 22:57:53 +0200 Subject: [PATCH 11/23] f-21: doc: rename api doc Signed-off-by: GnomeZworc --- api/{openapi.yaml => agent.yaml} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename api/{openapi.yaml => agent.yaml} (100%) diff --git a/api/openapi.yaml b/api/agent.yaml similarity index 100% rename from api/openapi.yaml rename to api/agent.yaml From 3955fb211276dc5cff426dafb52913cc5a34b1fd Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Fri, 17 Apr 2026 23:25:35 +0200 Subject: [PATCH 12/23] f-21: code: add database in api Signed-off-by: GnomeZworc --- cmd/agent/main.go | 2 +- internal/api/agent/server.go | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/cmd/agent/main.go b/cmd/agent/main.go index 5ebf09f..2f5e084 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -35,7 +35,7 @@ func main() { apiAddr := fmt.Sprintf("%s:%d", cfg.Api.Address, cfg.Api.Port) promAddr := fmt.Sprintf("%s:%d", cfg.Prometheus.Address, cfg.Prometheus.Port) - go agentapi.New(q).Start(apiAddr) + go agentapi.New(q, db).Start(apiAddr) go promserver.Start(promAddr, registry) select {} diff --git a/internal/api/agent/server.go b/internal/api/agent/server.go index 75833c9..7e4eb21 100644 --- a/internal/api/agent/server.go +++ b/internal/api/agent/server.go @@ -5,14 +5,16 @@ import ( "net/http" "git.g3e.fr/syonad/two/pkg/worker" + "github.com/dgraph-io/badger/v4" ) type Server struct { queue *worker.Queue + db *badger.DB } -func New(queue *worker.Queue) *Server { - return &Server{queue: queue} +func New(queue *worker.Queue, db *badger.DB) *Server { + return &Server{queue: queue, db: db} } func (s *Server) Start(address string) { From 6dd21a465dc765c1aae36b76cc9cef0387936eee Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Fri, 17 Apr 2026 23:26:04 +0200 Subject: [PATCH 13/23] f-21: code: add vpc gestion in api Signed-off-by: GnomeZworc --- internal/api/agent/vpc.go | 20 +++++++++++++++++--- internal/api/agent/vpcs.go | 13 +++++++++---- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/internal/api/agent/vpc.go b/internal/api/agent/vpc.go index f1d34c1..3396d23 100644 --- a/internal/api/agent/vpc.go +++ b/internal/api/agent/vpc.go @@ -2,8 +2,13 @@ package agentapi import ( "encoding/json" + "fmt" "net/http" + "os" "strings" + + "git.g3e.fr/syonad/two/internal/vpc" + "git.g3e.fr/syonad/two/pkg/db/kv" ) func (s *Server) VpcByNameHandler(w http.ResponseWriter, r *http.Request) { @@ -25,14 +30,23 @@ func (s *Server) VpcByNameHandler(w http.ResponseWriter, r *http.Request) { } } -func (s *Server) getVpc(w http.ResponseWriter, r *http.Request, name string) { +func (s *Server) getVpc(w http.ResponseWriter, _ *http.Request, name string) { w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(VPC{Name: name, State: "created"}) } -func (s *Server) deleteVpc(w http.ResponseWriter, r *http.Request, name string) { +func (s *Server) deleteVpc(w http.ResponseWriter, _ *http.Request, name string) { s.queue.Submit(func() { - destroyVpc(name) + kv.AddInDB(s.db, "vpc/"+name+"/state", "deleting") + if err := vpc.DeleteVPC(s.db, name); err != nil { + fmt.Println(err) + } + if state, err := kv.GetFromDB(s.db, "vpc/"+name+"/state"); err != nil { + fmt.Println(err) + os.Exit(1) + } else if state == "deleted" { + kv.DeleteInDB(s.db, "vpc/"+name) + } }) w.WriteHeader(http.StatusAccepted) json.NewEncoder(w).Encode(VPC{Name: name, State: "deleting"}) diff --git a/internal/api/agent/vpcs.go b/internal/api/agent/vpcs.go index aba4e7a..2dddd42 100644 --- a/internal/api/agent/vpcs.go +++ b/internal/api/agent/vpcs.go @@ -2,7 +2,11 @@ package agentapi import ( "encoding/json" + "fmt" "net/http" + + "git.g3e.fr/syonad/two/internal/vpc" + "git.g3e.fr/syonad/two/pkg/db/kv" ) func (s *Server) VpcsHandler(w http.ResponseWriter, r *http.Request) { @@ -17,7 +21,7 @@ func (s *Server) VpcsHandler(w http.ResponseWriter, r *http.Request) { } } -func (s *Server) listVpcs(w http.ResponseWriter, r *http.Request) { +func (s *Server) listVpcs(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode([]VPC{}) } @@ -35,10 +39,11 @@ func (s *Server) postVpc(w http.ResponseWriter, r *http.Request) { return } s.queue.Submit(func() { - createVpc(req.Name) + kv.AddInDB(s.db, "vpc/"+req.Name+"/state", "creating") + if err := vpc.CreateVPC(s.db, req.Name); err != nil { + fmt.Println(err) + } }) w.WriteHeader(http.StatusAccepted) json.NewEncoder(w).Encode(VPC{Name: req.Name, State: "creating"}) } - -func createVpc(name string) {} From 40fa49d3a989bb3a1e419f4f5dc0410e1561e090 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Sun, 19 Apr 2026 00:04:46 +0200 Subject: [PATCH 14/23] f-21: git: add claude to gitignore Signed-off-by: GnomeZworc --- .gitignore | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 3a0b507..68ae417 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,9 @@ # Output of the go coverage tool, specifically when used with LiteIDE *.out +# Output of the go coverage tool, specifically when used with LiteIDE +.claude + # Dependency directories (remove the comment below to include it) # vendor/ @@ -26,4 +29,4 @@ go.work.sum .env # ignore local info -data/ \ No newline at end of file +data/ From 064b90f5e4fc3d4d47d9646a6bfb1366cb69df96 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Sun, 19 Apr 2026 00:06:50 +0200 Subject: [PATCH 15/23] f-21: refactor: add dispatcher layer for MQTT migration Introduce internal/dispatcher package with a Command interface and typed commands (CreateVPC, DeleteVPC, CreateSubnet, DeleteSubnet). The API handlers now call dispatcher.Dispatch() instead of enqueuing closures directly, decoupling transport (HTTP today, MQTT tomorrow) from execution. Signed-off-by: GnomeZworc --- cmd/agent/main.go | 4 ++- internal/api/agent/server.go | 10 ++++---- internal/api/agent/subnet.go | 7 +++--- internal/api/agent/subnets.go | 12 ++++++--- internal/api/agent/vpc.go | 19 ++------------ internal/api/agent/vpcs.go | 11 ++------ internal/dispatcher/dispatcher.go | 29 +++++++++++++++++++++ internal/dispatcher/subnet_commands.go | 26 +++++++++++++++++++ internal/dispatcher/vpc_commands.go | 35 ++++++++++++++++++++++++++ 9 files changed, 114 insertions(+), 39 deletions(-) create mode 100644 internal/dispatcher/dispatcher.go create mode 100644 internal/dispatcher/subnet_commands.go create mode 100644 internal/dispatcher/vpc_commands.go diff --git a/cmd/agent/main.go b/cmd/agent/main.go index 2f5e084..b61bb6f 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -7,6 +7,7 @@ import ( agentapi "git.g3e.fr/syonad/two/internal/api/agent" configuration "git.g3e.fr/syonad/two/internal/config/agent" + "git.g3e.fr/syonad/two/internal/dispatcher" agentmetrics "git.g3e.fr/syonad/two/internal/prometheus/agent" "git.g3e.fr/syonad/two/pkg/db/kv" promserver "git.g3e.fr/syonad/two/pkg/prometheus" @@ -35,7 +36,8 @@ func main() { apiAddr := fmt.Sprintf("%s:%d", cfg.Api.Address, cfg.Api.Port) promAddr := fmt.Sprintf("%s:%d", cfg.Prometheus.Address, cfg.Prometheus.Port) - go agentapi.New(q, db).Start(apiAddr) + d := dispatcher.New(q, db) + go agentapi.New(d, db).Start(apiAddr) go promserver.Start(promAddr, registry) select {} diff --git a/internal/api/agent/server.go b/internal/api/agent/server.go index 7e4eb21..7f3247c 100644 --- a/internal/api/agent/server.go +++ b/internal/api/agent/server.go @@ -4,17 +4,17 @@ import ( "log" "net/http" - "git.g3e.fr/syonad/two/pkg/worker" + "git.g3e.fr/syonad/two/internal/dispatcher" "github.com/dgraph-io/badger/v4" ) type Server struct { - queue *worker.Queue - db *badger.DB + dispatcher *dispatcher.Dispatcher + db *badger.DB } -func New(queue *worker.Queue, db *badger.DB) *Server { - return &Server{queue: queue, db: db} +func New(d *dispatcher.Dispatcher, db *badger.DB) *Server { + return &Server{dispatcher: d, db: db} } func (s *Server) Start(address string) { diff --git a/internal/api/agent/subnet.go b/internal/api/agent/subnet.go index 289667f..b20c65a 100644 --- a/internal/api/agent/subnet.go +++ b/internal/api/agent/subnet.go @@ -4,6 +4,8 @@ import ( "encoding/json" "net/http" "strings" + + "git.g3e.fr/syonad/two/internal/dispatcher" ) func (s *Server) SubnetByNameHandler(w http.ResponseWriter, r *http.Request) { @@ -31,11 +33,8 @@ func (s *Server) getSubnet(w http.ResponseWriter, r *http.Request, name string) } func (s *Server) deleteSubnet(w http.ResponseWriter, r *http.Request, name string) { - s.queue.Submit(func() { - destroySubnet(name) - }) + s.dispatcher.Dispatch(dispatcher.DeleteSubnetCommand{Name: name}) w.WriteHeader(http.StatusAccepted) json.NewEncoder(w).Encode(Subnet{Name: name, State: "deleting"}) } -func destroySubnet(name string) {} diff --git a/internal/api/agent/subnets.go b/internal/api/agent/subnets.go index 5e0ebdc..b251c3c 100644 --- a/internal/api/agent/subnets.go +++ b/internal/api/agent/subnets.go @@ -3,6 +3,8 @@ package agentapi import ( "encoding/json" "net/http" + + "git.g3e.fr/syonad/two/internal/dispatcher" ) func (s *Server) SubnetsHandler(w http.ResponseWriter, r *http.Request) { @@ -34,8 +36,13 @@ func (s *Server) postSubnet(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(ErrorResponse{Error: "name, vpc, local_ip, gateway_ip and cidr are required"}) return } - s.queue.Submit(func() { - createSubnet(req) + s.dispatcher.Dispatch(dispatcher.CreateSubnetCommand{ + Name: req.Name, + VPC: req.VPC, + VxlanID: req.VxlanID, + LocalIP: req.LocalIP, + GatewayIP: req.GatewayIP, + CIDR: req.CIDR, }) w.WriteHeader(http.StatusAccepted) json.NewEncoder(w).Encode(Subnet{ @@ -49,4 +56,3 @@ func (s *Server) postSubnet(w http.ResponseWriter, r *http.Request) { }) } -func createSubnet(req SubnetCreateRequest) {} diff --git a/internal/api/agent/vpc.go b/internal/api/agent/vpc.go index 3396d23..60d614e 100644 --- a/internal/api/agent/vpc.go +++ b/internal/api/agent/vpc.go @@ -2,13 +2,10 @@ package agentapi import ( "encoding/json" - "fmt" "net/http" - "os" "strings" - "git.g3e.fr/syonad/two/internal/vpc" - "git.g3e.fr/syonad/two/pkg/db/kv" + "git.g3e.fr/syonad/two/internal/dispatcher" ) func (s *Server) VpcByNameHandler(w http.ResponseWriter, r *http.Request) { @@ -36,20 +33,8 @@ func (s *Server) getVpc(w http.ResponseWriter, _ *http.Request, name string) { } func (s *Server) deleteVpc(w http.ResponseWriter, _ *http.Request, name string) { - s.queue.Submit(func() { - kv.AddInDB(s.db, "vpc/"+name+"/state", "deleting") - if err := vpc.DeleteVPC(s.db, name); err != nil { - fmt.Println(err) - } - if state, err := kv.GetFromDB(s.db, "vpc/"+name+"/state"); err != nil { - fmt.Println(err) - os.Exit(1) - } else if state == "deleted" { - kv.DeleteInDB(s.db, "vpc/"+name) - } - }) + s.dispatcher.Dispatch(dispatcher.DeleteVPCCommand{Name: name}) w.WriteHeader(http.StatusAccepted) json.NewEncoder(w).Encode(VPC{Name: name, State: "deleting"}) } -func destroyVpc(name string) {} diff --git a/internal/api/agent/vpcs.go b/internal/api/agent/vpcs.go index 2dddd42..eb633e3 100644 --- a/internal/api/agent/vpcs.go +++ b/internal/api/agent/vpcs.go @@ -2,11 +2,9 @@ package agentapi import ( "encoding/json" - "fmt" "net/http" - "git.g3e.fr/syonad/two/internal/vpc" - "git.g3e.fr/syonad/two/pkg/db/kv" + "git.g3e.fr/syonad/two/internal/dispatcher" ) func (s *Server) VpcsHandler(w http.ResponseWriter, r *http.Request) { @@ -38,12 +36,7 @@ func (s *Server) postVpc(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(ErrorResponse{Error: "name is required"}) return } - s.queue.Submit(func() { - kv.AddInDB(s.db, "vpc/"+req.Name+"/state", "creating") - if err := vpc.CreateVPC(s.db, req.Name); err != nil { - fmt.Println(err) - } - }) + s.dispatcher.Dispatch(dispatcher.CreateVPCCommand{Name: req.Name}) w.WriteHeader(http.StatusAccepted) json.NewEncoder(w).Encode(VPC{Name: req.Name, State: "creating"}) } diff --git a/internal/dispatcher/dispatcher.go b/internal/dispatcher/dispatcher.go new file mode 100644 index 0000000..937adf2 --- /dev/null +++ b/internal/dispatcher/dispatcher.go @@ -0,0 +1,29 @@ +package dispatcher + +import ( + "log" + + "git.g3e.fr/syonad/two/pkg/worker" + "github.com/dgraph-io/badger/v4" +) + +type Command interface { + Execute(db *badger.DB) error +} + +type Dispatcher struct { + queue *worker.Queue + db *badger.DB +} + +func New(queue *worker.Queue, db *badger.DB) *Dispatcher { + return &Dispatcher{queue: queue, db: db} +} + +func (d *Dispatcher) Dispatch(cmd Command) { + d.queue.Submit(func() { + if err := cmd.Execute(d.db); err != nil { + log.Printf("command error (%T): %v", cmd, err) + } + }) +} diff --git a/internal/dispatcher/subnet_commands.go b/internal/dispatcher/subnet_commands.go new file mode 100644 index 0000000..d8ef8e3 --- /dev/null +++ b/internal/dispatcher/subnet_commands.go @@ -0,0 +1,26 @@ +package dispatcher + +import "github.com/dgraph-io/badger/v4" + +type CreateSubnetCommand struct { + Name string + VPC string + VxlanID int + LocalIP string + GatewayIP string + CIDR string +} + +func (c CreateSubnetCommand) Execute(db *badger.DB) error { + // TODO: brancher internal/subnet/create.go + return nil +} + +type DeleteSubnetCommand struct { + Name string +} + +func (c DeleteSubnetCommand) Execute(db *badger.DB) error { + // TODO: brancher internal/subnet/delete.go + return nil +} diff --git a/internal/dispatcher/vpc_commands.go b/internal/dispatcher/vpc_commands.go new file mode 100644 index 0000000..195b014 --- /dev/null +++ b/internal/dispatcher/vpc_commands.go @@ -0,0 +1,35 @@ +package dispatcher + +import ( + "git.g3e.fr/syonad/two/internal/vpc" + "git.g3e.fr/syonad/two/pkg/db/kv" + "github.com/dgraph-io/badger/v4" +) + +type CreateVPCCommand struct { + Name string +} + +func (c CreateVPCCommand) Execute(db *badger.DB) error { + kv.AddInDB(db, "vpc/"+c.Name+"/state", "creating") + return vpc.CreateVPC(db, c.Name) +} + +type DeleteVPCCommand struct { + Name string +} + +func (c DeleteVPCCommand) Execute(db *badger.DB) error { + kv.AddInDB(db, "vpc/"+c.Name+"/state", "deleting") + if err := vpc.DeleteVPC(db, c.Name); err != nil { + return err + } + state, err := kv.GetFromDB(db, "vpc/"+c.Name+"/state") + if err != nil { + return err + } + if state == "deleted" { + kv.DeleteInDB(db, "vpc/"+c.Name) + } + return nil +} From d028dbe57b47c7f9dc2f6a867b952fbdcbb14e09 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Sun, 19 Apr 2026 20:49:50 +0200 Subject: [PATCH 16/23] f-21: clean: delete vpc notions Signed-off-by: GnomeZworc --- .forgejo/workflows/prerelease.yml | 1 - cmd/vpc/main.go | 65 ------------------------------- 2 files changed, 66 deletions(-) delete mode 100644 cmd/vpc/main.go diff --git a/.forgejo/workflows/prerelease.yml b/.forgejo/workflows/prerelease.yml index 8003e82..ed635e9 100644 --- a/.forgejo/workflows/prerelease.yml +++ b/.forgejo/workflows/prerelease.yml @@ -37,7 +37,6 @@ jobs: - metadata - metacli - agent - - vpc - dhcp - subnet uses: ./.forgejo/workflows/build.yml diff --git a/cmd/vpc/main.go b/cmd/vpc/main.go deleted file mode 100644 index e73f7e9..0000000 --- a/cmd/vpc/main.go +++ /dev/null @@ -1,65 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "os" - - configuration "git.g3e.fr/syonad/two/internal/config/agent" - "git.g3e.fr/syonad/two/internal/vpc" - "git.g3e.fr/syonad/two/pkg/db/kv" - "github.com/dgraph-io/badger/v4" -) - -var ( - netns = flag.String("netns", "", "Network namespace à faire") - name = flag.String("name", "", "interface name") - action = flag.String("action", "", "Action a faire") - conf_file = flag.String("conf", "/etc/two/agent.yml", "configuration file") -) - -var DB *badger.DB - -func main() { - flag.Parse() - - conf, err := configuration.LoadConfig(*conf_file) - if err != nil { - fmt.Println(err) - return - } - - DB = kv.InitDB(kv.Config{ - Path: conf.Database.Path, - }, false) - defer DB.Close() - - switch *action { - case "create": - kv.AddInDB(DB, "vpc/"+*name+"/state", "creating") - if err := vpc.CreateVPC(DB, *name); err != nil { - fmt.Println(err) - } - case "delete": - kv.AddInDB(DB, "vpc/"+*name+"/state", "deleting") - if err := vpc.DeleteVPC(DB, *name); err != nil { - fmt.Println(err) - } - if state, err := kv.GetFromDB(DB, "vpc/"+*name+"/state"); err != nil { - fmt.Println(err) - os.Exit(1) - } else if state == "deleted" { - kv.DeleteInDB(DB, "vpc/"+*name) - } - case "check": - if state, err := kv.GetFromDB(DB, "vpc/"+*name+"/state"); err != nil { - os.Exit(1) - } else if state != "created" { - os.Exit(1) - } - default: - fmt.Printf("Available commande:\n - create\n - delete\n - check\n") - os.Exit(1) - } - os.Exit(0) -} From 374bb34695b67d12dcf8c5c4b7dd46b1a9d0a7dc Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Sun, 19 Apr 2026 21:02:54 +0200 Subject: [PATCH 17/23] f-21: code: add dispatch command for subnet Signed-off-by: GnomeZworc --- internal/dispatcher/subnet_commands.go | 31 ++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/internal/dispatcher/subnet_commands.go b/internal/dispatcher/subnet_commands.go index d8ef8e3..b23949e 100644 --- a/internal/dispatcher/subnet_commands.go +++ b/internal/dispatcher/subnet_commands.go @@ -1,6 +1,14 @@ package dispatcher -import "github.com/dgraph-io/badger/v4" +import ( + "fmt" + "os" + "strconv" + + "git.g3e.fr/syonad/two/internal/subnet" + "git.g3e.fr/syonad/two/pkg/db/kv" + "github.com/dgraph-io/badger/v4" +) type CreateSubnetCommand struct { Name string @@ -12,8 +20,13 @@ type CreateSubnetCommand struct { } func (c CreateSubnetCommand) Execute(db *badger.DB) error { - // TODO: brancher internal/subnet/create.go - return nil + kv.AddInDB(db, "subnet/"+c.Name+"/state", "creating") + kv.AddInDB(db, "subnet/"+c.Name+"/vpc", c.VPC) + kv.AddInDB(db, "subnet/"+c.Name+"/vxlan_id", strconv.Itoa(c.VxlanID)) + kv.AddInDB(db, "subnet/"+c.Name+"/local_ip", c.LocalIP) + kv.AddInDB(db, "subnet/"+c.Name+"/gateway_ip", c.GatewayIP) + kv.AddInDB(db, "subnet/"+c.Name+"/cidr", c.CIDR) + return subnet.CreateSubnet(db, c.Name) } type DeleteSubnetCommand struct { @@ -21,6 +34,16 @@ type DeleteSubnetCommand struct { } func (c DeleteSubnetCommand) Execute(db *badger.DB) error { - // TODO: brancher internal/subnet/delete.go + kv.AddInDB(db, "subnet/"+c.Name+"/state", "deleting") + if err := subnet.DeleteSubnet(db, c.Name); err != nil { + fmt.Println(err) + os.Exit(1) + } + if state, err := kv.GetFromDB(db, "subnet/"+c.Name+"/state"); err != nil { + fmt.Println(err) + os.Exit(1) + } else if state == "deleted" { + kv.DeleteInDB(db, "subnet/"+c.Name) + } return nil } From a3549fd822a68744dbb4a3279f0136f26c94acaa Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Tue, 21 Apr 2026 21:27:19 +0200 Subject: [PATCH 18/23] f-21: code: add interface name in config Signed-off-by: GnomeZworc --- conf/agent/config.exemple.yml | 7 ++++++- internal/config/agent/struct.go | 1 + 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/conf/agent/config.exemple.yml b/conf/agent/config.exemple.yml index a2b9f1b..5bd1dfd 100644 --- a/conf/agent/config.exemple.yml +++ b/conf/agent/config.exemple.yml @@ -1,2 +1,7 @@ database: - path: "/var/lib/two/data/" \ No newline at end of file + path: "/var/lib/two/data/" + +interfaces: + vms: br-000000 + internet: br-000000 + admin: br-000000 \ No newline at end of file diff --git a/internal/config/agent/struct.go b/internal/config/agent/struct.go index 24ad0f5..21dde0d 100644 --- a/internal/config/agent/struct.go +++ b/internal/config/agent/struct.go @@ -20,6 +20,7 @@ type Config struct { Count int `mapstructure:"count"` BufferSize int `mapstructure:"buffer_size"` } `mapstructure:"worker"` + Interfaces map[string]string `mapstructure:"interfaces"` } func LoadConfig(path string) (*Config, error) { From a52118cddbd2f9d4bacc6418d07f6d058d24165a Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Tue, 21 Apr 2026 21:28:20 +0200 Subject: [PATCH 19/23] f-21: code: change from ip to interface type Signed-off-by: GnomeZworc --- cmd/agent/main.go | 2 +- internal/api/agent/models.go | 16 ++++++++-------- internal/api/agent/subnets.go | 8 +++----- internal/dispatcher/dispatcher.go | 13 +++++++------ internal/dispatcher/subnet_commands.go | 12 ++++++++---- internal/dispatcher/vpc_commands.go | 4 ++-- internal/netif/vxlan.go | 16 +++++++++------- internal/subnet/create.go | 10 +++------- 8 files changed, 41 insertions(+), 40 deletions(-) diff --git a/cmd/agent/main.go b/cmd/agent/main.go index b61bb6f..faa6139 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -36,7 +36,7 @@ func main() { apiAddr := fmt.Sprintf("%s:%d", cfg.Api.Address, cfg.Api.Port) promAddr := fmt.Sprintf("%s:%d", cfg.Prometheus.Address, cfg.Prometheus.Port) - d := dispatcher.New(q, db) + d := dispatcher.New(q, db, cfg.Interfaces) go agentapi.New(d, db).Start(apiAddr) go promserver.Start(promAddr, registry) diff --git a/internal/api/agent/models.go b/internal/api/agent/models.go index bd09c76..e826082 100644 --- a/internal/api/agent/models.go +++ b/internal/api/agent/models.go @@ -13,19 +13,19 @@ type SubnetCreateRequest struct { Name string `json:"name"` VPC string `json:"vpc"` VxlanID int `json:"vxlan_id"` - LocalIP string `json:"local_ip"` + IfaceType string `json:"iface_type"` GatewayIP string `json:"gateway_ip"` CIDR string `json:"cidr"` } type Subnet struct { - Name string `json:"name"` - State string `json:"state"` - VPC string `json:"vpc"` - VxlanID int `json:"vxlan_id"` - LocalIP string `json:"local_ip"` - GatewayIP string `json:"gateway_ip"` - CIDR string `json:"cidr"` + Name string `json:"name"` + State string `json:"state"` + VPC string `json:"vpc"` + VxlanID int `json:"vxlan_id"` + LocalIface string `json:"local_iface"` + GatewayIP string `json:"gateway_ip"` + CIDR string `json:"cidr"` } type ErrorResponse struct { diff --git a/internal/api/agent/subnets.go b/internal/api/agent/subnets.go index b251c3c..263c9ce 100644 --- a/internal/api/agent/subnets.go +++ b/internal/api/agent/subnets.go @@ -31,16 +31,16 @@ func (s *Server) postSubnet(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(ErrorResponse{Error: "invalid request body"}) return } - if req.Name == "" || req.VPC == "" || req.LocalIP == "" || req.GatewayIP == "" || req.CIDR == "" { + if req.Name == "" || req.VPC == "" || req.IfaceType == "" || req.GatewayIP == "" || req.CIDR == "" { w.WriteHeader(http.StatusBadRequest) - json.NewEncoder(w).Encode(ErrorResponse{Error: "name, vpc, local_ip, gateway_ip and cidr are required"}) + json.NewEncoder(w).Encode(ErrorResponse{Error: "name, vpc, iface_type, gateway_ip and cidr are required"}) return } s.dispatcher.Dispatch(dispatcher.CreateSubnetCommand{ Name: req.Name, VPC: req.VPC, VxlanID: req.VxlanID, - LocalIP: req.LocalIP, + IfaceType: req.IfaceType, GatewayIP: req.GatewayIP, CIDR: req.CIDR, }) @@ -50,9 +50,7 @@ func (s *Server) postSubnet(w http.ResponseWriter, r *http.Request) { State: "creating", VPC: req.VPC, VxlanID: req.VxlanID, - LocalIP: req.LocalIP, GatewayIP: req.GatewayIP, CIDR: req.CIDR, }) } - diff --git a/internal/dispatcher/dispatcher.go b/internal/dispatcher/dispatcher.go index 937adf2..f240245 100644 --- a/internal/dispatcher/dispatcher.go +++ b/internal/dispatcher/dispatcher.go @@ -8,21 +8,22 @@ import ( ) type Command interface { - Execute(db *badger.DB) error + Execute(db *badger.DB, interfaces map[string]string) error } type Dispatcher struct { - queue *worker.Queue - db *badger.DB + queue *worker.Queue + db *badger.DB + interfaces map[string]string } -func New(queue *worker.Queue, db *badger.DB) *Dispatcher { - return &Dispatcher{queue: queue, db: db} +func New(queue *worker.Queue, db *badger.DB, interfaces map[string]string) *Dispatcher { + return &Dispatcher{queue: queue, db: db, interfaces: interfaces} } func (d *Dispatcher) Dispatch(cmd Command) { d.queue.Submit(func() { - if err := cmd.Execute(d.db); err != nil { + if err := cmd.Execute(d.db, d.interfaces); err != nil { log.Printf("command error (%T): %v", cmd, err) } }) diff --git a/internal/dispatcher/subnet_commands.go b/internal/dispatcher/subnet_commands.go index b23949e..dcb0398 100644 --- a/internal/dispatcher/subnet_commands.go +++ b/internal/dispatcher/subnet_commands.go @@ -14,16 +14,20 @@ type CreateSubnetCommand struct { Name string VPC string VxlanID int - LocalIP string + IfaceType string GatewayIP string CIDR string } -func (c CreateSubnetCommand) Execute(db *badger.DB) error { +func (c CreateSubnetCommand) Execute(db *badger.DB, interfaces map[string]string) error { + localIface, ok := interfaces[c.IfaceType] + if !ok { + return fmt.Errorf("unknown iface_type %q: not found in config", c.IfaceType) + } kv.AddInDB(db, "subnet/"+c.Name+"/state", "creating") kv.AddInDB(db, "subnet/"+c.Name+"/vpc", c.VPC) kv.AddInDB(db, "subnet/"+c.Name+"/vxlan_id", strconv.Itoa(c.VxlanID)) - kv.AddInDB(db, "subnet/"+c.Name+"/local_ip", c.LocalIP) + kv.AddInDB(db, "subnet/"+c.Name+"/local_iface", localIface) kv.AddInDB(db, "subnet/"+c.Name+"/gateway_ip", c.GatewayIP) kv.AddInDB(db, "subnet/"+c.Name+"/cidr", c.CIDR) return subnet.CreateSubnet(db, c.Name) @@ -33,7 +37,7 @@ type DeleteSubnetCommand struct { Name string } -func (c DeleteSubnetCommand) Execute(db *badger.DB) error { +func (c DeleteSubnetCommand) Execute(db *badger.DB, _ map[string]string) error { kv.AddInDB(db, "subnet/"+c.Name+"/state", "deleting") if err := subnet.DeleteSubnet(db, c.Name); err != nil { fmt.Println(err) diff --git a/internal/dispatcher/vpc_commands.go b/internal/dispatcher/vpc_commands.go index 195b014..2c316a3 100644 --- a/internal/dispatcher/vpc_commands.go +++ b/internal/dispatcher/vpc_commands.go @@ -10,7 +10,7 @@ type CreateVPCCommand struct { Name string } -func (c CreateVPCCommand) Execute(db *badger.DB) error { +func (c CreateVPCCommand) Execute(db *badger.DB, _ map[string]string) error { kv.AddInDB(db, "vpc/"+c.Name+"/state", "creating") return vpc.CreateVPC(db, c.Name) } @@ -19,7 +19,7 @@ type DeleteVPCCommand struct { Name string } -func (c DeleteVPCCommand) Execute(db *badger.DB) error { +func (c DeleteVPCCommand) Execute(db *badger.DB, _ map[string]string) error { kv.AddInDB(db, "vpc/"+c.Name+"/state", "deleting") if err := vpc.DeleteVPC(db, c.Name); err != nil { return err diff --git a/internal/netif/vxlan.go b/internal/netif/vxlan.go index eacae7c..6523f37 100644 --- a/internal/netif/vxlan.go +++ b/internal/netif/vxlan.go @@ -1,20 +1,22 @@ package netif import ( - "net" - "github.com/vishvananda/netlink" ) -func CreateVxlan(name string, vxlanID int, localIP net.IP) error { +func CreateVxlan(name string, vxlanID int, localIface string) error { + link, err := netlink.LinkByName(localIface) + if err != nil { + return err + } vxlan := &netlink.Vxlan{ LinkAttrs: netlink.LinkAttrs{ Name: name, }, - VxlanId: vxlanID, - Port: 4789, - SrcAddr: localIP, - Learning: false, + VxlanId: vxlanID, + Port: 4789, + VtepDevIndex: link.Attrs().Index, + Learning: false, } return netlink.LinkAdd(vxlan) } diff --git a/internal/subnet/create.go b/internal/subnet/create.go index 9bfe02a..1ed514e 100644 --- a/internal/subnet/create.go +++ b/internal/subnet/create.go @@ -40,13 +40,9 @@ func CreateSubnet(db *badger.DB, subnetName string) error { return fmt.Errorf("parse vxlan_id: %w", err) } - localIPStr, err := kv.GetFromDB(db, "subnet/"+subnetName+"/local_ip") + localIface, err := kv.GetFromDB(db, "subnet/"+subnetName+"/local_iface") if err != nil { - return fmt.Errorf("get local_ip: %w", err) - } - localIP := net.ParseIP(localIPStr) - if localIP == nil { - return fmt.Errorf("invalid local_ip: %s", localIPStr) + return fmt.Errorf("get local_iface: %w", err) } gatewayIPStr, err := kv.GetFromDB(db, "subnet/"+subnetName+"/gateway_ip") @@ -90,7 +86,7 @@ func CreateSubnet(db *badger.DB, subnetName string) error { } // vxlan - if err := netif.CreateVxlan(vxlanIface, vxlanID, localIP); err != nil { + if err := netif.CreateVxlan(vxlanIface, vxlanID, localIface); err != nil { return fmt.Errorf("create vxlan: %w", err) } From 8724570c816122be1c0bec4c457353d7240c2fca Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Tue, 21 Apr 2026 21:32:59 +0200 Subject: [PATCH 20/23] f-21: code: swap from interface only to full conf Signed-off-by: GnomeZworc --- cmd/agent/main.go | 2 +- internal/dispatcher/dispatcher.go | 15 ++++++++------- internal/dispatcher/subnet_commands.go | 7 ++++--- internal/dispatcher/vpc_commands.go | 5 +++-- 4 files changed, 16 insertions(+), 13 deletions(-) diff --git a/cmd/agent/main.go b/cmd/agent/main.go index faa6139..dd6fd6d 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -36,7 +36,7 @@ func main() { apiAddr := fmt.Sprintf("%s:%d", cfg.Api.Address, cfg.Api.Port) promAddr := fmt.Sprintf("%s:%d", cfg.Prometheus.Address, cfg.Prometheus.Port) - d := dispatcher.New(q, db, cfg.Interfaces) + d := dispatcher.New(q, db, cfg) go agentapi.New(d, db).Start(apiAddr) go promserver.Start(promAddr, registry) diff --git a/internal/dispatcher/dispatcher.go b/internal/dispatcher/dispatcher.go index f240245..8e94827 100644 --- a/internal/dispatcher/dispatcher.go +++ b/internal/dispatcher/dispatcher.go @@ -3,27 +3,28 @@ package dispatcher import ( "log" + configuration "git.g3e.fr/syonad/two/internal/config/agent" "git.g3e.fr/syonad/two/pkg/worker" "github.com/dgraph-io/badger/v4" ) type Command interface { - Execute(db *badger.DB, interfaces map[string]string) error + Execute(db *badger.DB, cfg *configuration.Config) error } type Dispatcher struct { - queue *worker.Queue - db *badger.DB - interfaces map[string]string + queue *worker.Queue + db *badger.DB + cfg *configuration.Config } -func New(queue *worker.Queue, db *badger.DB, interfaces map[string]string) *Dispatcher { - return &Dispatcher{queue: queue, db: db, interfaces: interfaces} +func New(queue *worker.Queue, db *badger.DB, cfg *configuration.Config) *Dispatcher { + return &Dispatcher{queue: queue, db: db, cfg: cfg} } func (d *Dispatcher) Dispatch(cmd Command) { d.queue.Submit(func() { - if err := cmd.Execute(d.db, d.interfaces); err != nil { + if err := cmd.Execute(d.db, d.cfg); err != nil { log.Printf("command error (%T): %v", cmd, err) } }) diff --git a/internal/dispatcher/subnet_commands.go b/internal/dispatcher/subnet_commands.go index dcb0398..c2a0cff 100644 --- a/internal/dispatcher/subnet_commands.go +++ b/internal/dispatcher/subnet_commands.go @@ -5,6 +5,7 @@ import ( "os" "strconv" + configuration "git.g3e.fr/syonad/two/internal/config/agent" "git.g3e.fr/syonad/two/internal/subnet" "git.g3e.fr/syonad/two/pkg/db/kv" "github.com/dgraph-io/badger/v4" @@ -19,8 +20,8 @@ type CreateSubnetCommand struct { CIDR string } -func (c CreateSubnetCommand) Execute(db *badger.DB, interfaces map[string]string) error { - localIface, ok := interfaces[c.IfaceType] +func (c CreateSubnetCommand) Execute(db *badger.DB, cfg *configuration.Config) error { + localIface, ok := cfg.Interfaces[c.IfaceType] if !ok { return fmt.Errorf("unknown iface_type %q: not found in config", c.IfaceType) } @@ -37,7 +38,7 @@ type DeleteSubnetCommand struct { Name string } -func (c DeleteSubnetCommand) Execute(db *badger.DB, _ map[string]string) error { +func (c DeleteSubnetCommand) Execute(db *badger.DB, _ *configuration.Config) error { kv.AddInDB(db, "subnet/"+c.Name+"/state", "deleting") if err := subnet.DeleteSubnet(db, c.Name); err != nil { fmt.Println(err) diff --git a/internal/dispatcher/vpc_commands.go b/internal/dispatcher/vpc_commands.go index 2c316a3..b2687fc 100644 --- a/internal/dispatcher/vpc_commands.go +++ b/internal/dispatcher/vpc_commands.go @@ -1,6 +1,7 @@ package dispatcher import ( + configuration "git.g3e.fr/syonad/two/internal/config/agent" "git.g3e.fr/syonad/two/internal/vpc" "git.g3e.fr/syonad/two/pkg/db/kv" "github.com/dgraph-io/badger/v4" @@ -10,7 +11,7 @@ type CreateVPCCommand struct { Name string } -func (c CreateVPCCommand) Execute(db *badger.DB, _ map[string]string) error { +func (c CreateVPCCommand) Execute(db *badger.DB, _ *configuration.Config) error { kv.AddInDB(db, "vpc/"+c.Name+"/state", "creating") return vpc.CreateVPC(db, c.Name) } @@ -19,7 +20,7 @@ type DeleteVPCCommand struct { Name string } -func (c DeleteVPCCommand) Execute(db *badger.DB, _ map[string]string) error { +func (c DeleteVPCCommand) Execute(db *badger.DB, _ *configuration.Config) error { kv.AddInDB(db, "vpc/"+c.Name+"/state", "deleting") if err := vpc.DeleteVPC(db, c.Name); err != nil { return err From 28afabbd635b2015507fe93ccd151d0f19f3cb7b Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Tue, 21 Apr 2026 21:38:46 +0200 Subject: [PATCH 21/23] f-21: code: add default interface Signed-off-by: GnomeZworc --- conf/agent/config.exemple.yml | 4 +++- internal/config/agent/struct.go | 4 +++- internal/dispatcher/subnet_commands.go | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/conf/agent/config.exemple.yml b/conf/agent/config.exemple.yml index 5bd1dfd..bc1d437 100644 --- a/conf/agent/config.exemple.yml +++ b/conf/agent/config.exemple.yml @@ -1,7 +1,9 @@ database: path: "/var/lib/two/data/" +default_interface: br-000000 + interfaces: vms: br-000000 internet: br-000000 - admin: br-000000 \ No newline at end of file + admin: br-000000 diff --git a/internal/config/agent/struct.go b/internal/config/agent/struct.go index 21dde0d..1c9fc9f 100644 --- a/internal/config/agent/struct.go +++ b/internal/config/agent/struct.go @@ -20,7 +20,8 @@ type Config struct { Count int `mapstructure:"count"` BufferSize int `mapstructure:"buffer_size"` } `mapstructure:"worker"` - Interfaces map[string]string `mapstructure:"interfaces"` + DefaultInterface string `mapstructure:"default_interface"` + Interfaces map[string]string `mapstructure:"interfaces"` } func LoadConfig(path string) (*Config, error) { @@ -35,6 +36,7 @@ func LoadConfig(path string) (*Config, error) { v.SetDefault("prometheus.port", 9090) v.SetDefault("worker.count", 4) v.SetDefault("worker.buffer_size", 100) + v.SetDefault("default_interface", "br-000000") v.ReadInConfig() diff --git a/internal/dispatcher/subnet_commands.go b/internal/dispatcher/subnet_commands.go index c2a0cff..0d471c3 100644 --- a/internal/dispatcher/subnet_commands.go +++ b/internal/dispatcher/subnet_commands.go @@ -23,7 +23,7 @@ type CreateSubnetCommand struct { func (c CreateSubnetCommand) Execute(db *badger.DB, cfg *configuration.Config) error { localIface, ok := cfg.Interfaces[c.IfaceType] if !ok { - return fmt.Errorf("unknown iface_type %q: not found in config", c.IfaceType) + localIface = cfg.DefaultInterface } kv.AddInDB(db, "subnet/"+c.Name+"/state", "creating") kv.AddInDB(db, "subnet/"+c.Name+"/vpc", c.VPC) From 4470af0e9ed869ca22b843e14dab63b4dc286625 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Tue, 21 Apr 2026 21:43:17 +0200 Subject: [PATCH 22/23] f-21: api: update api Signed-off-by: GnomeZworc --- api/agent.yaml | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/api/agent.yaml b/api/agent.yaml index be328d0..2b3acc7 100644 --- a/api/agent.yaml +++ b/api/agent.yaml @@ -127,6 +127,12 @@ paths: application/json: schema: $ref: "#/components/schemas/Subnet" + "400": + description: Missing required field or unknown iface_type + content: + application/json: + schema: + $ref: "#/components/schemas/Error" "409": description: Subnet already exists content: @@ -219,7 +225,7 @@ components: SubnetCreateRequest: type: object - required: [name, vpc, vxlan_id, local_ip, gateway_ip, cidr] + required: [name, vpc, vxlan_id, gateway_ip, cidr] properties: name: type: string @@ -233,11 +239,10 @@ components: type: integer description: VXLAN VNI identifier example: 100 - local_ip: + iface_type: type: string - format: ipv4 - description: Local VTEP IP address - example: "10.0.0.5" + description: Interface type key defined in the agent config (e.g. vms, internet, admin). Falls back to default_interface if omitted or unknown. + example: vms gateway_ip: type: string format: ipv4 @@ -264,9 +269,10 @@ components: vxlan_id: type: integer example: 100 - local_ip: + local_iface: type: string - example: "10.0.0.5" + description: Resolved interface name + example: br-000000 gateway_ip: type: string example: "10.10.10.1" From 25aebcc123c0718104c909078cd482c1113c42e1 Mon Sep 17 00:00:00 2001 From: GnomeZworc Date: Tue, 21 Apr 2026 21:52:03 +0200 Subject: [PATCH 23/23] f-21: vpc: change to be ok in the name Signed-off-by: GnomeZworc --- api/agent.yaml | 7 ++++--- internal/vpc/create.go | 25 +++++++++---------------- internal/vpc/delete.go | 6 +++++- 3 files changed, 18 insertions(+), 20 deletions(-) diff --git a/api/agent.yaml b/api/agent.yaml index 2b3acc7..1d3a77f 100644 --- a/api/agent.yaml +++ b/api/agent.yaml @@ -209,15 +209,16 @@ components: properties: name: type: string - description: Unique name for the VPC - example: vpc1 + description: Unique name for the VPC, must follow the format vp-[id] + pattern: '^vp-.+' + example: vp-00001 VPC: type: object properties: name: type: string - example: vpc1 + example: vp-00001 state: type: string enum: [creating, created, deleting, deleted] diff --git a/internal/vpc/create.go b/internal/vpc/create.go index a6e6aaa..148f70c 100644 --- a/internal/vpc/create.go +++ b/internal/vpc/create.go @@ -1,6 +1,8 @@ package vpc import ( + "strings" + "git.g3e.fr/syonad/two/internal/netif" "git.g3e.fr/syonad/two/internal/netns" "git.g3e.fr/syonad/two/pkg/db/kv" @@ -9,49 +11,40 @@ import ( ) func CreateVPC(db *badger.DB, name string) error { - // missing - // search data in db - // change state in db - - // create netns if state, err := kv.GetFromDB(db, "vpc/"+name+"/state"); err != nil { return err } else if state == "creating" { + vpcID := strings.SplitN(name, "-", 2)[1] + if err := netns.Create(name); err != nil { return err } - // create veth public for this netns - if err := netif.CreateVethToNetns("vp-"+name+"-e", "vp-public-i", "/var/run/netns/"+name, 9000); err != nil { + if err := netif.CreateVethToNetns("vp-"+vpcID+"-e", "vp-"+vpcID+"-i", "/var/run/netns/"+name, 9000); err != nil { return err } - // create public bridge in netns if err := netns.Call(name, func() error { return netif.CreateBridge("br-public", 1500) }); err != nil { return err } - // set veth to ext public bridge - if err := netif.BridgeSetMaster("vp-"+name+"-e", "br-public"); err != nil { + if err := netif.BridgeSetMaster("vp-"+vpcID+"-e", "br-public"); err != nil { return err } - // set veth to int public bridge if err := netns.Call(name, func() error { - return netif.BridgeSetMaster("vp-public-i", "br-public") + return netif.BridgeSetMaster("vp-"+vpcID+"-i", "br-public") }); err != nil { return err } - // set set ext veth up - if err := netif.LinkSetUp("vp-" + name + "-e"); err != nil { + if err := netif.LinkSetUp("vp-" + vpcID + "-e"); err != nil { return err } - // set set int veth up if err := netns.Call(name, func() error { - return netif.LinkSetUp("vp-public-i") + return netif.LinkSetUp("vp-" + vpcID + "-i") }); err != nil { return err } diff --git a/internal/vpc/delete.go b/internal/vpc/delete.go index 10c863d..dbd3a59 100644 --- a/internal/vpc/delete.go +++ b/internal/vpc/delete.go @@ -1,6 +1,8 @@ package vpc import ( + "strings" + "git.g3e.fr/syonad/two/internal/netif" "git.g3e.fr/syonad/two/internal/netns" "git.g3e.fr/syonad/two/pkg/db/kv" @@ -12,7 +14,9 @@ func DeleteVPC(db *badger.DB, name string) error { if state, err := kv.GetFromDB(db, "vpc/"+name+"/state"); err != nil { return err } else if state == "deleting" { - if err := netif.DeleteLink("vp-" + name + "-e"); err != nil { + vpcID := strings.SplitN(name, "-", 2)[1] + + if err := netif.DeleteLink("vp-" + vpcID + "-e"); err != nil { return err }