feat(cluster): PG Logical Replication + VIP/Keepalived + config_hash sync (v1.2.1–1.2.2)
- PG Logical Replication: edgeguard_shared PUBLICATION auf Primary, edgeguard_sub SUBSCRIPTION auf Secondary. Nur geteilte Config-Tabellen werden repliziert; node-eigene Daten (network_interfaces, ip_addresses, static_routes, cluster_settings, dns_settings, ntp_settings) bleiben lokal — OPNsense-Muster. - cluster-init-replication: Erstellt PUBLICATION, Rolle + pg_hba-Einträge (logical + replication), WAL-Level auf logical. - cluster-setup-standby: Erstellt SUBSCRIPTION (copy_data=true), pollt pg_subscription_rel bis alle Tabellen sync = 'r', rendert dann Configs. - promote: manueller Failover via pg_promote() + touch recovery.signal. - VIP/Keepalived: cluster_settings-Tabelle (vip_address, vip_interface, vrrp_router_id), /cluster/vip-settings API, Keepalived-Config-Generator mit VRRP + check_script + notify-Skripten in /usr/lib/edgeguard/scripts/. - config_hash sync: Secondary pusht alle 5 Min seinen Hash via mTLS an Primary (PushSelfToPrimary). Heartbeat schreibt nur LOCAL, daher ohne aktiven Push wäre Primary-Sicht des Secondary-Hash stale gewesen. - runSecondaryConfigRender: Goroutine auf Secondary rendert HAProxy+nftables neu wenn config_hash sich ändert (Logical-Replication-Nachzügler). - confighash: node-spezifische Tabellen aus hashSpec entfernt. - postinst: Keepalived-Skripte installieren, sudoers für keepalived. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
455
cmd/edgeguard-ctl/cluster_replication.go
Normal file
455
cmd/edgeguard-ctl/cluster_replication.go
Normal file
@@ -0,0 +1,455 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/cluster/clustertls"
|
||||
)
|
||||
|
||||
const (
|
||||
pgVersion = "16"
|
||||
pgCluster = "main"
|
||||
pgDataDir = "/var/lib/postgresql/16/main"
|
||||
pgHBAPath = "/etc/postgresql/16/main/pg_hba.conf"
|
||||
pgConfD = "/etc/postgresql/16/main/conf.d"
|
||||
egReplSecret = "/var/lib/edgeguard/pg-replication-secret"
|
||||
egReplUser = "edgeguard_replicator"
|
||||
egPubName = "edgeguard_shared"
|
||||
egSubName = "edgeguard_sub"
|
||||
|
||||
// Tabellen die NODE-SPEZIFISCH sind und NICHT repliziert werden.
|
||||
// Jede Node hat eigene Interfaces, IPs, Routen, VIP-Einstellungen,
|
||||
// Listener-Adressen, Token-Tracking und Audit-Log.
|
||||
// Analog zu OPNsense: Interface-IPs und Hostname bleiben immer lokal.
|
||||
)
|
||||
|
||||
// localOnlyTables listet alle Tabellen die nicht in die Replikations-
|
||||
// Publication aufgenommen werden. Alles andere wird automatisch repliziert.
|
||||
var localOnlyTables = []string{
|
||||
"ha_nodes", // Node-Identität, Status
|
||||
"network_interfaces", // Eigene Interfaces (eth0, eth1 …)
|
||||
"ip_addresses", // Eigene IP-Adressen (unterschiedlich pro Node!)
|
||||
"static_routes", // Node-spezifisches Routing
|
||||
"cluster_settings", // VIP-Interface kann pro Node unterschiedlich sein
|
||||
"dns_settings", // listen_addresses ist node-spezifisch
|
||||
"ntp_settings", // listen_addresses ist node-spezifisch
|
||||
"system_settings", // Hostname, Maintenance-Mode etc.
|
||||
"join_tokens_used", // Token-Tracking nur auf Primary relevant
|
||||
"audit_log", // Lokales Audit-Protokoll
|
||||
"alert_events", // Lokale Laufzeit-Events
|
||||
"backups", // Backup-Historie ist per-Node
|
||||
"goose_db_version", // Migration-Tracking, internes Tool-State
|
||||
}
|
||||
|
||||
// cmdClusterInitReplication richtet PG auf dieser Node als Logical-Replication-
|
||||
// Primary ein. Idempotent — kann gefahrlos mehrfach laufen.
|
||||
//
|
||||
// Ablauf:
|
||||
// 1. edgeguard_replicator-Rolle anlegen/aktualisieren
|
||||
// 2. Passwort → /var/lib/edgeguard/pg-replication-secret
|
||||
// 3. conf.d/edgeguard-replication.conf mit wal_level=logical schreiben
|
||||
// 4. pg_hba.conf für Replikations-Verbindungen aktualisieren
|
||||
// 5. SELECT-Grants auf alle geteilten Tabellen
|
||||
// 6. PUBLICATION erstellen (alle Tabellen außer localOnlyTables)
|
||||
// 7. PG reload
|
||||
func cmdClusterInitReplication(args []string) int {
|
||||
fs := flag.NewFlagSet("cluster-init-replication", flag.ContinueOnError)
|
||||
fs.SetOutput(os.Stderr)
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 2
|
||||
}
|
||||
|
||||
// 1. Passwort generieren
|
||||
pass, err := generatePassword(32)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cluster-init-replication: generate password:", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
// 2. edgeguard_replicator-Rolle anlegen/updaten
|
||||
roleSQL := fmt.Sprintf(`DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '%s') THEN
|
||||
CREATE ROLE %s REPLICATION LOGIN PASSWORD '%s';
|
||||
ELSE
|
||||
ALTER ROLE %s PASSWORD '%s';
|
||||
END IF;
|
||||
END
|
||||
$$`, egReplUser, egReplUser, pass, egReplUser, pass)
|
||||
if err := psqlExec(roleSQL); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cluster-init-replication: create replication role:", err)
|
||||
return 1
|
||||
}
|
||||
fmt.Printf("✓ Replication-Rolle %q angelegt/aktualisiert\n", egReplUser)
|
||||
|
||||
// 3. Passwort speichern
|
||||
if err := os.MkdirAll(filepath.Dir(egReplSecret), 0o750); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cluster-init-replication: mkdir:", err)
|
||||
return 1
|
||||
}
|
||||
if err := os.WriteFile(egReplSecret, []byte(pass), 0o600); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cluster-init-replication: write secret:", err)
|
||||
return 1
|
||||
}
|
||||
fmt.Printf("✓ Replication-Secret gespeichert: %s\n", egReplSecret)
|
||||
|
||||
// 4. conf.d/edgeguard-replication.conf schreiben
|
||||
// wal_level=logical ist eine Obermenge von replica — unterstützt
|
||||
// sowohl Logical Replication als auch ggfs. physisches WAL-Archiving.
|
||||
if err := os.MkdirAll(pgConfD, 0o755); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cluster-init-replication: conf.d mkdir:", err)
|
||||
return 1
|
||||
}
|
||||
replConf := `# EdgeGuard Logical Replication — automatisch generiert
|
||||
# Nicht manuell bearbeiten; wird von edgeguard-ctl cluster-init-replication verwaltet.
|
||||
wal_level = logical
|
||||
max_wal_senders = 5
|
||||
max_replication_slots = 5
|
||||
max_logical_replication_workers = 4
|
||||
wal_keep_size = 512MB
|
||||
`
|
||||
confPath := filepath.Join(pgConfD, "edgeguard-replication.conf")
|
||||
if err := os.WriteFile(confPath, []byte(replConf), 0o644); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cluster-init-replication: write postgresql conf:", err)
|
||||
return 1
|
||||
}
|
||||
fmt.Printf("✓ %s geschrieben (wal_level=logical)\n", confPath)
|
||||
|
||||
// 5. pg_hba.conf aktualisieren
|
||||
if err := ensureHBAReplication(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cluster-init-replication: pg_hba.conf:", err)
|
||||
return 1
|
||||
}
|
||||
fmt.Printf("✓ %s aktualisiert\n", pgHBAPath)
|
||||
|
||||
// 6. PG reload (damit wal_level + pg_hba aktiv werden)
|
||||
if out, err := exec.Command("pg_ctlcluster", pgVersion, pgCluster, "reload").CombinedOutput(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "cluster-init-replication: pg reload failed: %v\n%s\n", err, out)
|
||||
return 1
|
||||
}
|
||||
fmt.Printf("✓ PostgreSQL %s/%s neu geladen\n", pgVersion, pgCluster)
|
||||
|
||||
// 7. SELECT-Grants: edgeguard_replicator muss alle zu replizierenden
|
||||
// Tabellen lesen können. DEFAULT PRIVILEGES sichert zukünftige Tabellen.
|
||||
grantSQL := fmt.Sprintf(`
|
||||
GRANT SELECT ON ALL TABLES IN SCHEMA public TO %s;
|
||||
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO %s;
|
||||
`, egReplUser, egReplUser)
|
||||
if err := psqlDBExec("edgeguard", grantSQL); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cluster-init-replication: grant SELECT:", err)
|
||||
return 1
|
||||
}
|
||||
fmt.Printf("✓ SELECT auf alle Tabellen für %q gewährt\n", egReplUser)
|
||||
|
||||
// 8. PUBLICATION erstellen — alle public-Tabellen außer localOnlyTables.
|
||||
// Idempotent: DROP IF EXISTS + CREATE.
|
||||
if err := createPublication(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cluster-init-replication: create publication:", err)
|
||||
return 1
|
||||
}
|
||||
fmt.Printf("✓ PUBLICATION %q erstellt\n", egPubName)
|
||||
|
||||
fmt.Println()
|
||||
fmt.Println("Nächste Schritte:")
|
||||
fmt.Println(" 1) Auf dem Secondary: edgeguard-ctl cluster-setup-standby <primary-ip>")
|
||||
fmt.Println(" 2) Cluster-Settings (VIP) auf BEIDEN Nodes separat konfigurieren")
|
||||
fmt.Println(" → Settings → Cluster → VIP/Keepalived")
|
||||
return 0
|
||||
}
|
||||
|
||||
// createPublication baut die PUBLICATION dynamisch aus allen Tabellen
|
||||
// im public-Schema minus localOnlyTables. Idempotent: löscht eine
|
||||
// bestehende Publication gleichen Namens zuerst.
|
||||
func createPublication() error {
|
||||
// Alle Tabellen im public-Schema ermitteln
|
||||
listSQL := `SELECT tablename FROM pg_tables WHERE schemaname = 'public' ORDER BY tablename`
|
||||
out, err := psqlDBRun("edgeguard", []string{"-tA", "-c", listSQL})
|
||||
if err != nil {
|
||||
return fmt.Errorf("list tables: %w", err)
|
||||
}
|
||||
|
||||
excluded := make(map[string]bool)
|
||||
for _, t := range localOnlyTables {
|
||||
excluded[t] = true
|
||||
}
|
||||
|
||||
var tables []string
|
||||
for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
|
||||
t := strings.TrimSpace(line)
|
||||
if t == "" || excluded[t] {
|
||||
continue
|
||||
}
|
||||
tables = append(tables, t)
|
||||
}
|
||||
if len(tables) == 0 {
|
||||
return fmt.Errorf("keine Tabellen für Publication gefunden")
|
||||
}
|
||||
|
||||
dropSQL := fmt.Sprintf("DROP PUBLICATION IF EXISTS %s;", egPubName)
|
||||
if err := psqlDBExec("edgeguard", dropSQL); err != nil {
|
||||
return fmt.Errorf("drop old publication: %w", err)
|
||||
}
|
||||
|
||||
createSQL := fmt.Sprintf("CREATE PUBLICATION %s FOR TABLE %s;",
|
||||
egPubName, strings.Join(tables, ", "))
|
||||
if err := psqlDBExec("edgeguard", createSQL); err != nil {
|
||||
return fmt.Errorf("create publication: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensureHBAReplication fügt Einträge für die Replikations-Verbindung
|
||||
// in pg_hba.conf ein. Für Logical Replication brauchen wir einen
|
||||
// normalen "host edgeguard"-Eintrag (nicht "host replication").
|
||||
// Idempotent via Marker-Kommentar.
|
||||
func ensureHBAReplication() error {
|
||||
data, err := os.ReadFile(pgHBAPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read: %w", err)
|
||||
}
|
||||
const marker = "# EdgeGuard replication"
|
||||
if strings.Contains(string(data), marker) {
|
||||
return nil
|
||||
}
|
||||
// Logical Replication: Subscriber verbindet sich auf die DB (nicht "replication"-Typ)
|
||||
// Physical/WAL-Archiving: "replication"-Typ bleibt für Kompatibilität
|
||||
entry := fmt.Sprintf(`
|
||||
%s
|
||||
host edgeguard %s 0.0.0.0/0 scram-sha-256
|
||||
host edgeguard %s ::/0 scram-sha-256
|
||||
host replication %s 0.0.0.0/0 scram-sha-256
|
||||
host replication %s ::/0 scram-sha-256
|
||||
`, marker, egReplUser, egReplUser, egReplUser, egReplUser)
|
||||
f, err := os.OpenFile(pgHBAPath, os.O_APPEND|os.O_WRONLY, 0o640)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
_, err = f.WriteString(entry)
|
||||
return err
|
||||
}
|
||||
|
||||
// cmdClusterSetupStandby richtet diesen Node als Logical-Replication-
|
||||
// Subscriber ein. Der Secondary behält seine eigene beschreibbare PG-
|
||||
// Instanz — nur die geteilten Tabellen werden vom Primary repliziert.
|
||||
// Node-spezifische Tabellen (Interfaces, IPs, Routen, VIP-Settings …)
|
||||
// bleiben lokal und werden NICHT überschrieben. Analog zu OPNsense's
|
||||
// HA-Sync: Interface-IPs und Hostname bleiben immer per-Node konfiguriert.
|
||||
//
|
||||
// Voraussetzungen:
|
||||
// - cluster-join erfolgreich (TLS-Certs in /var/lib/edgeguard/cluster-tls/)
|
||||
// - Primary hat cluster-init-replication ausgeführt
|
||||
// - Dieser Node hat edgeguard-api schon gelaufen (Migrations ausgeführt)
|
||||
//
|
||||
// Ablauf:
|
||||
// 1. Replication-Credentials via mTLS vom Primary holen
|
||||
// 2. Bestehende Subscription löschen (idempotent)
|
||||
// 3. SUBSCRIPTION auf Primary erstellen (copy_data=true → Initialkopiierung)
|
||||
// 4. Warten bis Initialkopiierung abgeschlossen
|
||||
// 5. render-config ausführen damit Service-Configs den neuen Stand reflektieren
|
||||
func cmdClusterSetupStandby(args []string) int {
|
||||
fs := flag.NewFlagSet("cluster-setup-standby", flag.ContinueOnError)
|
||||
agentPort := fs.Int("agent-port", 8443, "mTLS agent port on primary")
|
||||
tlsDir := fs.String("tls-dir", clustertls.DefaultDir, "Verzeichnis mit ca.crt + peer.{crt,key}")
|
||||
fs.SetOutput(os.Stderr)
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 2
|
||||
}
|
||||
if fs.NArg() < 1 {
|
||||
fmt.Fprintln(os.Stderr, "usage: edgeguard-ctl cluster-setup-standby <primary-ip-or-host>")
|
||||
return 2
|
||||
}
|
||||
primaryHost := fs.Arg(0)
|
||||
|
||||
// 1. Replication-Credentials vom Primary holen
|
||||
creds, err := fetchReplicationCreds(primaryHost, *agentPort, *tlsDir)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "cluster-setup-standby: replication-creds: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
fmt.Printf("✓ Replication-Credentials von %s:%d erhalten\n", primaryHost, *agentPort)
|
||||
|
||||
// 2. Bestehende Subscription löschen (idempotent)
|
||||
dropSQL := fmt.Sprintf(`
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (SELECT FROM pg_subscription WHERE subname = '%s') THEN
|
||||
ALTER SUBSCRIPTION %s DISABLE;
|
||||
ALTER SUBSCRIPTION %s SET (slot_name = NONE);
|
||||
DROP SUBSCRIPTION %s;
|
||||
END IF;
|
||||
END $$;`, egSubName, egSubName, egSubName, egSubName)
|
||||
if err := psqlDBExec("edgeguard", dropSQL); err != nil {
|
||||
// Nicht fatal — wenn PG noch keine Subscription kennt ist das OK
|
||||
fmt.Printf(" → keine bestehende Subscription gefunden (ok)\n")
|
||||
} else {
|
||||
fmt.Println("✓ Bestehende Subscription entfernt")
|
||||
}
|
||||
|
||||
// 3. SUBSCRIPTION erstellen
|
||||
// sslmode=require: Verbindung zwischen Cluster-Nodes soll immer verschlüsselt sein.
|
||||
// copy_data=true: Initialkopiierung aller geteilten Tabellen vom Primary.
|
||||
connStr := fmt.Sprintf(
|
||||
"host=%s port=%d user=%s password=%s dbname=edgeguard sslmode=require",
|
||||
creds.Host, creds.Port, creds.User, creds.Password,
|
||||
)
|
||||
createSQL := fmt.Sprintf(
|
||||
"CREATE SUBSCRIPTION %s CONNECTION '%s' PUBLICATION %s WITH (copy_data = true, enabled = true);",
|
||||
egSubName, connStr, egPubName,
|
||||
)
|
||||
if err := psqlDBExec("edgeguard", createSQL); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "cluster-setup-standby: create subscription: %v\n", err)
|
||||
return 1
|
||||
}
|
||||
fmt.Printf("✓ SUBSCRIPTION %q erstellt — Initialkopiierung läuft\n", egSubName)
|
||||
|
||||
// 4. Warten bis Initialkopiierung abgeschlossen
|
||||
fmt.Print("→ Warte auf Initialkopiierung")
|
||||
deadline := time.Now().Add(5 * time.Minute)
|
||||
for time.Now().Before(deadline) {
|
||||
pendingSQL := fmt.Sprintf(`
|
||||
SELECT COUNT(*) FROM pg_subscription_rel
|
||||
WHERE srsubid = (SELECT oid FROM pg_subscription WHERE subname = '%s')
|
||||
AND srsubstate != 'r';`, egSubName)
|
||||
out, err := psqlDBRun("edgeguard", []string{"-tA", "-c", pendingSQL})
|
||||
if err == nil && strings.TrimSpace(string(out)) == "0" {
|
||||
break
|
||||
}
|
||||
fmt.Print(".")
|
||||
time.Sleep(3 * time.Second)
|
||||
}
|
||||
fmt.Println()
|
||||
|
||||
// Finale Prüfung
|
||||
checkSQL := fmt.Sprintf(`
|
||||
SELECT COUNT(*) FROM pg_subscription_rel
|
||||
WHERE srsubid = (SELECT oid FROM pg_subscription WHERE subname = '%s')
|
||||
AND srsubstate != 'r';`, egSubName)
|
||||
if out, err := psqlDBRun("edgeguard", []string{"-tA", "-c", checkSQL}); err == nil {
|
||||
if n := strings.TrimSpace(string(out)); n != "0" {
|
||||
fmt.Fprintf(os.Stderr,
|
||||
"cluster-setup-standby: %s Tabellen noch nicht synchronisiert — prüfe PG-Logs\n", n)
|
||||
fmt.Println(" → Subscription läuft trotzdem weiter im Hintergrund")
|
||||
} else {
|
||||
fmt.Println("✓ Alle geteilten Tabellen synchronisiert")
|
||||
}
|
||||
}
|
||||
|
||||
// 5. render-config ausführen
|
||||
fmt.Println("→ Service-Configs neu rendern...")
|
||||
if out, err := exec.Command("edgeguard-ctl", "render-config", "--no-reload").CombinedOutput(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "cluster-setup-standby: render-config: %v\n%s\n", err, out)
|
||||
fmt.Println(" → Manuell nachholen: edgeguard-ctl render-config")
|
||||
} else {
|
||||
fmt.Print(string(out))
|
||||
fmt.Println("✓ Service-Configs aktualisiert")
|
||||
}
|
||||
|
||||
fmt.Println()
|
||||
fmt.Println("✓ Logical Replication eingerichtet.")
|
||||
fmt.Println()
|
||||
fmt.Println("Was repliziert wird (automatisch, in Echtzeit):")
|
||||
fmt.Println(" Domains, Backends, Firewall-Rules, WireGuard, DNS-Zones,")
|
||||
fmt.Println(" TLS-Certs, Users, Forward-Proxy, NTP-Pools, ...")
|
||||
fmt.Println()
|
||||
fmt.Println("Was NICHT repliziert wird (bleibt pro Node konfiguriert):")
|
||||
fmt.Println(" Netzwerk-Interfaces, IP-Adressen, Routen,")
|
||||
fmt.Println(" Cluster-Settings (VIP-Interface!), DNS/NTP-Listen-Adressen")
|
||||
fmt.Println()
|
||||
fmt.Println("Nächste Schritte:")
|
||||
fmt.Println(" 1) sudo systemctl restart edgeguard-api")
|
||||
fmt.Println(" 2) VIP/Keepalived auf BEIDEN Nodes separat konfigurieren:")
|
||||
fmt.Println(" Settings → Cluster → VIP/Keepalived")
|
||||
fmt.Println(" 3) Bei Failover: edgeguard-ctl promote (auf dem Secondary)")
|
||||
return 0
|
||||
}
|
||||
|
||||
// pgReplicationCreds sind die Credentials die der Primary via mTLS zurückgibt.
|
||||
type pgReplicationCreds struct {
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
User string `json:"user"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
// fetchReplicationCreds ruft GET /agent/cluster/pg-replication-info via mTLS ab.
|
||||
func fetchReplicationCreds(host string, agentPort int, tlsDir string) (*pgReplicationCreds, error) {
|
||||
caPath := filepath.Join(tlsDir, "ca.crt")
|
||||
certPath := filepath.Join(tlsDir, "peer.crt")
|
||||
keyPath := filepath.Join(tlsDir, "peer.key")
|
||||
|
||||
caCert, err := os.ReadFile(caPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read ca.crt: %w", err)
|
||||
}
|
||||
pool := x509.NewCertPool()
|
||||
pool.AppendCertsFromPEM(caCert)
|
||||
|
||||
cert, err := tls.LoadX509KeyPair(certPath, keyPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load peer cert: %w", err)
|
||||
}
|
||||
|
||||
client := &http.Client{
|
||||
Timeout: 15 * time.Second,
|
||||
Transport: &http.Transport{
|
||||
TLSClientConfig: &tls.Config{
|
||||
RootCAs: pool,
|
||||
Certificates: []tls.Certificate{cert},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("https://%s:%d/agent/cluster/pg-replication-info", host, agentPort)
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("GET %s: %w", url, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("GET %s: HTTP %d", url, resp.StatusCode)
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Data pgReplicationCreds `json:"data"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return nil, fmt.Errorf("decode response: %w", err)
|
||||
}
|
||||
return &result.Data, nil
|
||||
}
|
||||
|
||||
// generatePassword erzeugt ein kryptographisch sicheres Passwort.
|
||||
func generatePassword(n int) (string, error) {
|
||||
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
buf := make([]byte, n)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
for i, b := range buf {
|
||||
buf[i] = charset[int(b)%len(charset)]
|
||||
}
|
||||
return string(buf), nil
|
||||
}
|
||||
|
||||
// psqlDBExec führt SQL in der angegebenen Datenbank als postgres-Superuser aus.
|
||||
func psqlDBExec(db, sql string) error {
|
||||
_, err := psqlDBRun(db, []string{"-v", "ON_ERROR_STOP=1", "-c", sql})
|
||||
return err
|
||||
}
|
||||
|
||||
// psqlDBRun führt psql-Kommandos gegen eine bestimmte Datenbank aus.
|
||||
func psqlDBRun(db string, args []string) ([]byte, error) {
|
||||
baseArgs := []string{"-d", db}
|
||||
return psqlRun(append(baseArgs, args...))
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
// Command edgeguard-ctl is the admin CLI for setup, migrations and
|
||||
// (later) cluster ops. v1 wires migrate + initdb so postinst can
|
||||
// initialise a fresh node; cluster-* and promote remain stubs until
|
||||
// Phase 3.
|
||||
// cluster ops. v1.2 implements PG streaming replication setup,
|
||||
// VIP/Keepalived config and manual failover (promote).
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -11,7 +10,7 @@ import (
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/services/setup"
|
||||
)
|
||||
|
||||
var version = "1.1.162"
|
||||
var version = "1.2.3"
|
||||
|
||||
const usage = `edgeguard-ctl — EdgeGuard CLI
|
||||
|
||||
@@ -25,23 +24,25 @@ Commands:
|
||||
migrate check Validate embedded migrations (no DB connect)
|
||||
migrate dump [dir] Write embedded SQL files to dir (default: ./migrations)
|
||||
initdb Create PostgreSQL role + database (idempotent)
|
||||
render-config Regenerate haproxy / nftables configs from PG (--no-reload, --only=)
|
||||
render-config Regenerate all configs from PG (--no-reload, --only=svc)
|
||||
Services: haproxy nftables squid wireguard unbound chrony keepalived
|
||||
wg-import [--path <dir>] [iface…]
|
||||
Import /etc/wireguard/*.conf files into the DB.
|
||||
Without iface arguments: imports all .conf files.
|
||||
With iface args: imports only the named interfaces.
|
||||
reset-password Generate a one-time token for the /reset-password UI flow
|
||||
cluster-join <primary> --token <…>
|
||||
Provision Cluster-TLS material on this node by
|
||||
exchanging the join-token at the primary's
|
||||
/api/v1/cluster/issue-cert endpoint. Writes
|
||||
ca.crt + peer.{crt,key} into /var/lib/edgeguard/
|
||||
cluster-tls/. PG-Basebackup + KeyDB replica
|
||||
setup remain manual until Phase 3.5.
|
||||
cluster-renew-self Re-issue this node's peer.{crt,key} using the
|
||||
local cluster CA (founder/single-node only).
|
||||
1-year validity. Restart edgeguard-api after.
|
||||
promote Promote this node's PG to primary (Phase 3, not yet implemented)
|
||||
Provision Cluster-TLS material; writes ca.crt + peer.{crt,key}
|
||||
cluster-init-replication Richtet PG Logical Replication auf dem Primary ein.
|
||||
Erstellt edgeguard_replicator-Rolle, setzt wal_level=logical,
|
||||
erstellt PUBLICATION edgeguard_shared (alle geteilten Tabellen).
|
||||
Auf dem Primary ausführen bevor der Secondary joined.
|
||||
cluster-setup-standby <ip> Richtet diesen Node als Logical-Replication-Subscriber ein.
|
||||
Erstellt SUBSCRIPTION gegen den Primary (Initialkopiierung
|
||||
aller geteilten Tabellen). Node-eigene Daten (Interfaces,
|
||||
IPs, Routen, VIP-Settings) bleiben unangetastet.
|
||||
Voraussetzung: cluster-join + cluster-init-replication.
|
||||
cluster-renew-self Re-issue this node's peer.{crt,key} using the local cluster CA.
|
||||
promote Promote diesen PG-Standby zum Primary (manueller Failover).
|
||||
Kein Auto-Promote — Split-Brain-Schutz durch manuelle Entscheidung.
|
||||
dump-config Print effective config (Phase 3, not yet implemented)
|
||||
`
|
||||
|
||||
@@ -69,7 +70,13 @@ func main() {
|
||||
os.Exit(cmdClusterJoin(os.Args[2:]))
|
||||
case "cluster-renew-self":
|
||||
os.Exit(cmdClusterRenewSelf(os.Args[2:]))
|
||||
case "cluster-leave", "promote", "dump-config":
|
||||
case "cluster-init-replication":
|
||||
os.Exit(cmdClusterInitReplication(os.Args[2:]))
|
||||
case "cluster-setup-standby":
|
||||
os.Exit(cmdClusterSetupStandby(os.Args[2:]))
|
||||
case "promote":
|
||||
os.Exit(cmdPromote(os.Args[2:]))
|
||||
case "cluster-leave", "dump-config":
|
||||
fmt.Fprintf(os.Stderr, "edgeguard-ctl: %q is a Phase-3 stub — not yet implemented\n", os.Args[1])
|
||||
os.Exit(1)
|
||||
default:
|
||||
|
||||
154
cmd/edgeguard-ctl/promote.go
Normal file
154
cmd/edgeguard-ctl/promote.go
Normal file
@@ -0,0 +1,154 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/cluster"
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/database"
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/keepalived"
|
||||
)
|
||||
|
||||
// cmdPromote promotes this node's PostgreSQL instance from Hot-Standby
|
||||
// to Primary. Manual failover — keine automatische Promotion, um Split-Brain
|
||||
// in 2-Node-Clustern ohne externen Quorum zu verhindern.
|
||||
//
|
||||
// Ablauf:
|
||||
// 1. Prüfen ob standby.signal vorhanden (wir sind wirklich Standby)
|
||||
// 2. pg_ctlcluster promote → PG wird Primary
|
||||
// 3. Warten bis pg_is_in_recovery() = false
|
||||
// 4. ha_nodes.pg_role auf 'primary' setzen
|
||||
// 5. KeyDB cluster:pg-primary-url auf lokal setzen
|
||||
// 6. keepalived.conf neu rendern (Primary bekommt Priorität 200)
|
||||
// 7. keepalived reload
|
||||
func cmdPromote(args []string) int {
|
||||
// 1. Standby-Signal prüfen
|
||||
signalPath := filepath.Join(pgDataDir, "standby.signal")
|
||||
if _, err := os.Stat(signalPath); os.IsNotExist(err) {
|
||||
fmt.Fprintf(os.Stderr,
|
||||
"promote: %s nicht gefunden — diese Node ist kein PG-Standby oder wurde bereits promoted.\n",
|
||||
signalPath)
|
||||
return 1
|
||||
}
|
||||
|
||||
fmt.Println("→ Promoting PostgreSQL zu Primary...")
|
||||
if out, err := exec.Command("pg_ctlcluster", pgVersion, pgCluster, "promote").
|
||||
CombinedOutput(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "promote: pg_ctlcluster promote: %v\n%s\n", err, out)
|
||||
return 1
|
||||
}
|
||||
fmt.Println("✓ pg_ctlcluster promote gesendet")
|
||||
|
||||
// 2. Warten bis PG wirklich Primary ist (pg_is_in_recovery = false)
|
||||
fmt.Print("→ Warte auf PG Primary-Mode")
|
||||
deadline := time.Now().Add(60 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
out, err := psqlRun([]string{"-tA", "-c", "SELECT pg_is_in_recovery();"})
|
||||
if err == nil && strings.TrimSpace(string(out)) == "f" {
|
||||
break
|
||||
}
|
||||
fmt.Print(".")
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
fmt.Println()
|
||||
// Nochmal prüfen
|
||||
out, err := psqlRun([]string{"-tA", "-c", "SELECT pg_is_in_recovery();"})
|
||||
if err != nil || strings.TrimSpace(string(out)) != "f" {
|
||||
fmt.Fprintln(os.Stderr, "promote: PG ist nach 60s noch in recovery — prüfe PG-Logs")
|
||||
return 1
|
||||
}
|
||||
fmt.Println("✓ PostgreSQL ist jetzt Primary")
|
||||
|
||||
// 3. ha_nodes.pg_role + role aktualisieren
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
pool, err := database.Open(ctx, database.ConnStringFromEnv())
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "promote: db connect:", err)
|
||||
fmt.Println(" → ha_nodes manuell updaten: UPDATE ha_nodes SET pg_role='primary', role='primary' WHERE id='<local-id>';")
|
||||
} else {
|
||||
defer pool.Close()
|
||||
localID, err := loadLocalID()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "promote: local node ID:", err)
|
||||
} else {
|
||||
_, err = pool.Exec(ctx, `UPDATE ha_nodes SET pg_role='primary', role='primary', status='online', updated_at=NOW() WHERE id=$1`, localID)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "promote: update ha_nodes:", err)
|
||||
} else {
|
||||
fmt.Println("✓ ha_nodes.pg_role = 'primary' gesetzt")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. KeyDB cluster:pg-primary-url updaten
|
||||
if err := updateKeyDBPrimaryURL(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "promote: KeyDB update: %v\n", err)
|
||||
fmt.Println(" → Manuell: redis-cli SET cluster:pg-primary-url 'postgres://edgeguard@/edgeguard'")
|
||||
} else {
|
||||
fmt.Println("✓ KeyDB cluster:pg-primary-url aktualisiert")
|
||||
}
|
||||
|
||||
// 5. Keepalived.conf neu rendern (Primary = Priorität 200)
|
||||
if pool != nil {
|
||||
localID, _ := loadLocalID()
|
||||
kg := keepalived.New(pool, localID)
|
||||
renderCtx, renderCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer renderCancel()
|
||||
if err := kg.Render(renderCtx); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "promote: keepalived render: %v\n", err)
|
||||
fmt.Println(" → Manuell: edgeguard-ctl render-config --only=keepalived")
|
||||
} else {
|
||||
fmt.Println("✓ keepalived.conf neu gerendert (Priority 200)")
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println()
|
||||
fmt.Println("✓ Promotion abgeschlossen. Diese Node ist jetzt der primäre EdgeGuard-Knoten.")
|
||||
fmt.Println()
|
||||
fmt.Println("Empfohlene Nachschritte:")
|
||||
fmt.Println(" 1) sudo systemctl restart edgeguard-api (falls noch nicht laufend)")
|
||||
fmt.Println(" 2) Alte Primary-Node nach Recovery als neuen Standby einrichten:")
|
||||
fmt.Println(" edgeguard-ctl cluster-setup-standby <diese-node-ip>")
|
||||
return 0
|
||||
}
|
||||
|
||||
// loadLocalID liest die Node-ID aus /var/lib/edgeguard/node.conf.
|
||||
func loadLocalID() (string, error) {
|
||||
c, err := cluster.LoadLocalConfig("")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if c.NodeID == "" {
|
||||
return "", fmt.Errorf("NODE_ID in node.conf ist leer")
|
||||
}
|
||||
return c.NodeID, nil
|
||||
}
|
||||
|
||||
// updateKeyDBPrimaryURL schreibt den lokalen PG-DSN als cluster:pg-primary-url
|
||||
// in KeyDB, damit alle Nodes im Cluster Writes an diese Node schicken.
|
||||
func updateKeyDBPrimaryURL() error {
|
||||
// edgeguard-api nutzt Unix-Socket-Auth, der DSN ist immer lokal.
|
||||
const localDSN = "postgres://edgeguard@/edgeguard?host=/var/run/postgresql"
|
||||
out, err := exec.Command("redis-cli",
|
||||
"-s", "/var/run/keydb/keydb.sock",
|
||||
"SET", "cluster:pg-primary-url", localDSN,
|
||||
).CombinedOutput()
|
||||
if err != nil {
|
||||
// Fallback: Standard-Port
|
||||
out2, err2 := exec.Command("redis-cli",
|
||||
"-p", "6379",
|
||||
"SET", "cluster:pg-primary-url", localDSN,
|
||||
).CombinedOutput()
|
||||
if err2 != nil {
|
||||
return fmt.Errorf("%v: %s / %v: %s", err, out, err2, out2)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -12,6 +12,8 @@ import (
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/database"
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/firewall"
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/haproxy"
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/cluster"
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/keepalived"
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/services/configorch"
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/services/secrets"
|
||||
"git.netcell-it.de/projekte/edgeguard-native/internal/squid"
|
||||
@@ -64,7 +66,16 @@ func cmdRenderConfig(args []string) int {
|
||||
fw.SkipReload = true
|
||||
}
|
||||
|
||||
// keepalived: Node-ID aus node.conf für Prioritäts-Berechnung
|
||||
var ka configgen.Generator
|
||||
if lc, err := cluster.LoadLocalConfig(""); err == nil && lc.NodeID != "" {
|
||||
ka = keepalived.New(pool, lc.NodeID)
|
||||
}
|
||||
|
||||
gens := []configgen.Generator{hap, fw, sq, wg, ub, cn}
|
||||
if ka != nil {
|
||||
gens = append(gens, ka)
|
||||
}
|
||||
|
||||
results, runErr := configorch.Run(ctx, gens, only)
|
||||
fmt.Print(configorch.Summarise(results))
|
||||
|
||||
Reference in New Issue
Block a user