From 589fb2f0e1ac3fe06165972edfa7f6041e7e9a13 Mon Sep 17 00:00:00 2001 From: Alejandro Mery Date: Tue, 22 Aug 2023 17:50:38 +0000 Subject: [PATCH] zones: set zoneID based on wireguard config files Signed-off-by: Alejandro Mery --- pkg/zones/machine_rings.go | 66 ++++++++++++++++++++++++++++++++++++++ pkg/zones/machine_scan.go | 6 ++++ 2 files changed, 72 insertions(+) create mode 100644 pkg/zones/machine_rings.go diff --git a/pkg/zones/machine_rings.go b/pkg/zones/machine_rings.go new file mode 100644 index 0000000..d871599 --- /dev/null +++ b/pkg/zones/machine_rings.go @@ -0,0 +1,66 @@ +package zones + +import ( + "bytes" + "fmt" + "os" + + "darvaza.org/core" + + "git.jpi.io/amery/jpictl/pkg/wireguard" +) + +// GetWireguardConfig reads a wgN.conf file +func (m *Machine) GetWireguardConfig(ring int) (*wireguard.Config, error) { + data, err := m.ReadFile("wg%v.conf", ring) + if err != nil { + return nil, err + } + + r := bytes.NewReader(data) + return wireguard.NewConfigFromReader(r) +} + +func (m *Machine) tryApplyWireguardConfig(ring int) error { + wg, err := m.GetWireguardConfig(ring) + switch { + case os.IsNotExist(err): + return nil + case err != nil: + return err + default: + return m.applyWireguardConfig(ring, wg) + } +} + +func (m *Machine) applyWireguardConfig(ring int, wg *wireguard.Config) error { + addr := wg.GetAddress() + zoneID, nodeID, ok := Rings[ring].Decode(addr) + if !ok { + return fmt.Errorf("%s: invalid wg%v address: %s", m.Name, ring, addr) + } + + if err := m.applyZoneNodeID(zoneID, nodeID); err != nil { + err = core.Wrapf(err, "%s: wg%v:%s", m.Name, ring, addr) + return err + } + + return nil +} + +func (m *Machine) applyZoneNodeID(zoneID, nodeID int) error { + switch { + case zoneID == 0: + return fmt.Errorf("invalid %s", "zoneID") + case nodeID == 0: + return fmt.Errorf("invalid %s", "nodeID") + case m.ID() != nodeID: + return fmt.Errorf("invalid %s: %v ≠ %v", "zoneID", m.ID(), nodeID) + case m.zone.ID != 0 && m.zone.ID != zoneID: + return fmt.Errorf("invalid %s: %v ≠ %v", "zoneID", m.zone.ID, zoneID) + case m.zone.ID == 0: + m.zone.ID = zoneID + } + + return nil +} diff --git a/pkg/zones/machine_scan.go b/pkg/zones/machine_scan.go index 732fe45..5f88ae0 100644 --- a/pkg/zones/machine_scan.go +++ b/pkg/zones/machine_scan.go @@ -26,5 +26,11 @@ func (m *Machine) updatePublicAddresses() error { } func (m *Machine) scan() error { + for i := 0; i < RingsCount; i++ { + if err := m.tryApplyWireguardConfig(i); err != nil { + return err + } + } + return m.updatePublicAddresses() }