From b80dc84a266a67c7d804f8371513d67a99695663 Mon Sep 17 00:00:00 2001 From: Alejandro Mery Date: Sat, 26 Aug 2023 16:54:49 +0000 Subject: [PATCH] zones: introduce WireguardConfigWriters Signed-off-by: Alejandro Mery --- pkg/zones/wireguard.go | 82 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/pkg/zones/wireguard.go b/pkg/zones/wireguard.go index fb46865..c886c22 100644 --- a/pkg/zones/wireguard.go +++ b/pkg/zones/wireguard.go @@ -10,6 +10,10 @@ var ( _ WireguardConfigPruner = (*Zone)(nil) _ WireguardConfigPruner = (*Machine)(nil) + _ WireguardConfigWriter = (*Zones)(nil) + _ WireguardConfigWriter = (*Zone)(nil) + _ WireguardConfigWriter = (*Machine)(nil) + _ WireguardKeysWriter = (*Zones)(nil) _ WireguardKeysWriter = (*Zone)(nil) _ WireguardKeysWriter = (*Machine)(nil) @@ -60,6 +64,84 @@ func (m *Machine) PruneWireguardConfig(ring int) error { return nil } +// A WireguardConfigWriter rewrites all wgN.conf on all machines under +// its scope attached to that ring +type WireguardConfigWriter interface { + WriteWireguardConfig(ring int) error +} + +// WriteWireguardConfig rewrites all wgN.conf on all machines +// attached to that ring +func (m *Zones) WriteWireguardConfig(ring int) error { + switch ring { + case 0: + return writeWireguardConfig(m, m, ring) + case 1: + var err error + m.ForEachZone(func(z *Zone) bool { + err = writeWireguardConfig(m, z, ring) + return err != nil + }) + return err + default: + return fs.ErrInvalid + } +} + +// WriteWireguardConfig rewrites all wgN.conf on all machines +// on the Zone attached to that ring +func (z *Zone) WriteWireguardConfig(ring int) error { + switch ring { + case 0: + return writeWireguardConfig(z.zones, z.zones, ring) + case 1: + return writeWireguardConfig(z.zones, z, ring) + default: + return fs.ErrInvalid + } +} + +func writeWireguardConfig(z ZoneIterator, m MachineIterator, ring int) error { + r, err := NewRing(z, m, ring) + if err != nil { + return err + } + + r.ForEachMachine(func(p *Machine) bool { + err = p.writeWireguardRingConfig(r) + return err != nil + }) + + return err +} + +// WriteWireguardConfig rewrites the wgN.conf file of this Machine +// if enabled +func (m *Machine) WriteWireguardConfig(ring int) error { + r, err := NewRing(m.zone.zones, m.zone, ring) + if err != nil { + return err + } + + return m.writeWireguardRingConfig(r) +} + +func (m *Machine) writeWireguardRingConfig(r *Ring) error { + wg, err := r.ExportConfig(m) + if err != nil { + return nil + } + + f, err := m.CreateTruncFile("wg%v.conf", r.ID) + if err != nil { + return err + } + defer f.Close() + + _, err = wg.WriteTo(f) + return err +} + // A WireguardKeysWriter writes the Wireguard Keys for all machines // under its scope for the specified ring type WireguardKeysWriter interface {