You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.5 KiB

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
}