Compare commits
39 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6f5ca3f235 | |||
| 296d4007ff | |||
| 1a03404a07 | |||
| d2f0a0744b | |||
| 71a1d1a7c2 | |||
| de45fa6c30 | |||
| 6e46d23b45 | |||
| 94daf5ad59 | |||
| 0989dec5e8 | |||
| 216bf5aa29 | |||
| 9af88f6593 | |||
| af2d836000 | |||
| 1655ce85bc | |||
| 9c4f6d987d | |||
| fb82a7f358 | |||
| f63ce6c4e7 | |||
| 1885c76198 | |||
| 2224e70638 | |||
| 6ee848e6ca | |||
| 864eb02f9d | |||
| 9da2f8711f | |||
| 2a14205e7e | |||
| a5d9466fb8 | |||
| 3d638e9a85 | |||
| 60d3a2c290 | |||
| af90825f13 | |||
| b4f1d2e4d9 | |||
| acf9e0e81d | |||
| 3b43e0c9ea | |||
| 9762e78f5e | |||
| 3534e7b755 | |||
| b80dc84a26 | |||
| c0ef6ae9c4 | |||
| 58867031ea | |||
| b95d1f1878 | |||
| d38c909b0b | |||
| 7dd3ea8f96 | |||
| 07b4a22752 | |||
| 609f48a2d1 |
@@ -14,6 +14,8 @@ var cfg = &Config{
|
||||
}
|
||||
|
||||
// LoadZones loads all zones and machines in the config directory
|
||||
func (cfg *Config) LoadZones() (*zones.Zones, error) {
|
||||
return zones.New(cfg.Base, cfg.Domain)
|
||||
func (cfg *Config) LoadZones(resolve bool) (*zones.Zones, error) {
|
||||
return zones.New(cfg.Base, cfg.Domain,
|
||||
zones.ResolvePublicAddresses(resolve),
|
||||
)
|
||||
}
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@ var dumpCmd = &cobra.Command{
|
||||
var buf bytes.Buffer
|
||||
var enc Encoder
|
||||
|
||||
m, err := cfg.LoadZones()
|
||||
m, err := cfg.LoadZones(true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
+11
-2
@@ -11,15 +11,24 @@ var envCmd = &cobra.Command{
|
||||
Use: "env",
|
||||
Short: "generates environment variables for shell scripts",
|
||||
RunE: func(_ *cobra.Command, _ []string) error {
|
||||
m, err := cfg.LoadZones()
|
||||
m, err := cfg.LoadZones(false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return m.WriteEnv(os.Stdout)
|
||||
_, err = m.Env(*envExport).WriteTo(os.Stdout)
|
||||
return err
|
||||
},
|
||||
}
|
||||
|
||||
// Command Flags
|
||||
var (
|
||||
envExport *bool
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(envCmd)
|
||||
|
||||
envExport = envCmd.PersistentFlags().BoolP("export", "e", false,
|
||||
"export generated variables")
|
||||
}
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@ var writeCmd = &cobra.Command{
|
||||
Use: "write",
|
||||
Short: "rewrites all config files",
|
||||
RunE: func(_ *cobra.Command, _ []string) error {
|
||||
m, err := cfg.LoadZones()
|
||||
m, err := cfg.LoadZones(false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -1,17 +1,44 @@
|
||||
package wireguard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
"darvaza.org/core"
|
||||
"gopkg.in/gcfg.v1"
|
||||
)
|
||||
|
||||
var configTemplate = template.Must(template.New("config").Funcs(template.FuncMap{
|
||||
"PrefixJoin": func(a []netip.Prefix, sep string) string {
|
||||
s := make([]string, len(a))
|
||||
for i, p := range a {
|
||||
s[i] = p.String()
|
||||
}
|
||||
return strings.Join(s, sep)
|
||||
},
|
||||
}).Parse(`[Interface]
|
||||
{{if .Interface.Name}}# Name: {{.Interface.Name}}
|
||||
{{end -}}
|
||||
Address = {{.Interface.Address}}
|
||||
PrivateKey = {{.Interface.PrivateKey}}
|
||||
ListenPort = {{.Interface.ListenPort}}
|
||||
{{- range .Peer }}
|
||||
|
||||
[Peer]
|
||||
{{if .Name}}# Name: {{.Name}}
|
||||
{{end -}}
|
||||
PublicKey = {{.PublicKey}}
|
||||
Endpoint = {{.Endpoint}}
|
||||
AllowedIPs = {{ PrefixJoin .AllowedIPs ", "}}
|
||||
{{- end }}
|
||||
`))
|
||||
|
||||
// Config represents a wgN.conf file
|
||||
type Config struct {
|
||||
Interface InterfaceConfig
|
||||
@@ -28,8 +55,20 @@ func (f *Config) Peers() int {
|
||||
return len(f.Peer)
|
||||
}
|
||||
|
||||
// WriteTo writes a Wireguard [Config] onto the provided [io.Writer]
|
||||
func (f *Config) WriteTo(w io.Writer) (int64, error) {
|
||||
var buf bytes.Buffer
|
||||
|
||||
if err := configTemplate.Execute(&buf, f); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return buf.WriteTo(w)
|
||||
}
|
||||
|
||||
// InterfaceConfig represents the [Interface] section
|
||||
type InterfaceConfig struct {
|
||||
Name string
|
||||
Address netip.Addr
|
||||
PrivateKey PrivateKey
|
||||
ListenPort uint16
|
||||
@@ -37,6 +76,7 @@ type InterfaceConfig struct {
|
||||
|
||||
// PeerConfig represents a [Peer] section
|
||||
type PeerConfig struct {
|
||||
Name string
|
||||
PublicKey PublicKey
|
||||
Endpoint EndpointAddress
|
||||
AllowedIPs []netip.Prefix
|
||||
|
||||
@@ -51,12 +51,12 @@ func (pub PublicKey) String() string {
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalJSON encodes the key for JSON, omiting empty.
|
||||
// MarshalJSON encodes the key for JSON, omitting empty.
|
||||
func (key PrivateKey) MarshalJSON() ([]byte, error) {
|
||||
return encodeKeyJSON(key.String())
|
||||
}
|
||||
|
||||
// MarshalJSON encodes the key for JSON, omiting empty.
|
||||
// MarshalJSON encodes the key for JSON, omitting empty.
|
||||
func (pub PublicKey) MarshalJSON() ([]byte, error) {
|
||||
return encodeKeyJSON(pub.String())
|
||||
}
|
||||
@@ -70,12 +70,12 @@ func encodeKeyJSON(s string) ([]byte, error) {
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// MarshalYAML encodes the key for YAML, omiting empty.
|
||||
// MarshalYAML encodes the key for YAML, omitting empty.
|
||||
func (key PrivateKey) MarshalYAML() (any, error) {
|
||||
return encodeKeyYAML(key.String())
|
||||
}
|
||||
|
||||
// MarshalYAML encodes the key for YAML, omiting empty.
|
||||
// MarshalYAML encodes the key for YAML, omitting empty.
|
||||
func (pub PublicKey) MarshalYAML() (any, error) {
|
||||
return encodeKeyYAML(pub.String())
|
||||
}
|
||||
|
||||
+66
-55
@@ -7,21 +7,47 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// WriteEnv generates environment variables for shell scripts
|
||||
func (m *Zones) WriteEnv(w io.Writer) error {
|
||||
// Env is a shell environment factory for this cluster
|
||||
type Env struct {
|
||||
ZoneIterator
|
||||
|
||||
export bool
|
||||
}
|
||||
|
||||
// Env returns a shell environment factory
|
||||
func (m *Zones) Env(export bool) *Env {
|
||||
return &Env{
|
||||
ZoneIterator: m,
|
||||
export: export,
|
||||
}
|
||||
}
|
||||
|
||||
// Zones returns the list of Zone IDs
|
||||
func (m *Env) Zones() []int {
|
||||
var zones []int
|
||||
|
||||
m.ForEachZone(func(z *Zone) bool {
|
||||
zones = append(zones, z.ID)
|
||||
return false
|
||||
})
|
||||
|
||||
return zones
|
||||
}
|
||||
|
||||
// WriteTo generates environment variables for shell scripts
|
||||
func (m *Env) WriteTo(w io.Writer) (int64, error) {
|
||||
var buf bytes.Buffer
|
||||
|
||||
m.writeEnvVarFn(&buf, genEnvZones, "ZONES")
|
||||
m.writeEnvVarInts(&buf, m.Zones(), "ZONES")
|
||||
m.ForEachZone(func(z *Zone) bool {
|
||||
m.writeEnvZone(&buf, z)
|
||||
return false
|
||||
})
|
||||
|
||||
_, err := buf.WriteTo(w)
|
||||
return err
|
||||
return buf.WriteTo(w)
|
||||
}
|
||||
|
||||
func (m *Zones) writeEnvZone(w io.Writer, z *Zone) {
|
||||
func (m *Env) writeEnvZone(w io.Writer, z *Zone) {
|
||||
zoneID := z.ID
|
||||
|
||||
// ZONE{zoneID}
|
||||
@@ -31,25 +57,36 @@ func (m *Zones) writeEnvZone(w io.Writer, z *Zone) {
|
||||
m.writeEnvVar(w, z.Name, "ZONE%v_%s", zoneID, "NAME")
|
||||
|
||||
// ZONE{zoneID}_GW
|
||||
gatewayID := getRingZeroGatewayID(z)
|
||||
m.writeEnvVar(w, fmt.Sprintf("%v", gatewayID), "ZONE%v_%s", zoneID, "GW")
|
||||
|
||||
// ZONE{zoneID}_IP
|
||||
ip, _ := RingZeroAddress(zoneID, gatewayID)
|
||||
m.writeEnvVar(w, ip.String(), "ZONE%v_%s", zoneID, "IP")
|
||||
gateways, _ := z.GatewayIDs()
|
||||
m.writeEnvVarInts(w, gateways, "ZONE%v_%s", zoneID, "GW")
|
||||
}
|
||||
|
||||
func (m *Zones) writeEnvVarFn(w io.Writer, fn func(*Zones) string, name string, args ...any) {
|
||||
var value string
|
||||
func (m *Env) writeEnvVarInts(w io.Writer, value []int, name string, args ...any) {
|
||||
var s string
|
||||
|
||||
if fn != nil {
|
||||
value = fn(m)
|
||||
if n := len(value); n > 0 {
|
||||
var buf bytes.Buffer
|
||||
|
||||
for i, v := range value {
|
||||
if i != 0 {
|
||||
_, _ = fmt.Fprint(&buf, " ")
|
||||
}
|
||||
_, _ = fmt.Fprintf(&buf, "%v", v)
|
||||
}
|
||||
|
||||
s = buf.String()
|
||||
}
|
||||
|
||||
m.writeEnvVar(w, value, name, args...)
|
||||
m.writeEnvVar(w, s, name, args...)
|
||||
}
|
||||
|
||||
func (*Zones) writeEnvVar(w io.Writer, value string, name string, args ...any) {
|
||||
func (m *Env) writeEnvVar(w io.Writer, value string, name string, args ...any) {
|
||||
var prefix string
|
||||
|
||||
if m.export {
|
||||
prefix = "export "
|
||||
}
|
||||
|
||||
if len(args) > 0 {
|
||||
name = fmt.Sprintf(name, args...)
|
||||
}
|
||||
@@ -57,46 +94,20 @@ func (*Zones) writeEnvVar(w io.Writer, value string, name string, args ...any) {
|
||||
if name != "" {
|
||||
value = strings.TrimSpace(value)
|
||||
|
||||
_, _ = fmt.Fprintf(w, "%s=%q\n", name, value)
|
||||
_, _ = fmt.Fprintf(w, "%s%s=%q\n", prefix, name, value)
|
||||
}
|
||||
}
|
||||
|
||||
func genEnvZones(m *Zones) string {
|
||||
s := make([]string, 0, len(m.Zones))
|
||||
for _, z := range m.Zones {
|
||||
s = append(s, fmt.Sprintf("%v", z.ID))
|
||||
}
|
||||
|
||||
return strings.Join(s, " ")
|
||||
}
|
||||
|
||||
func genEnvZoneNodes(z *Zone) string {
|
||||
s := make([]string, 0, len(z.Machines))
|
||||
for _, p := range z.Machines {
|
||||
s = append(s, p.Name)
|
||||
}
|
||||
return strings.Join(s, " ")
|
||||
}
|
||||
|
||||
func getRingZeroGatewayID(z *Zone) int {
|
||||
var firstNodeID, gatewayID int
|
||||
|
||||
z.ForEachMachine(func(p *Machine) bool {
|
||||
if firstNodeID == 0 {
|
||||
firstNodeID = p.ID
|
||||
}
|
||||
|
||||
if p.IsGateway() {
|
||||
gatewayID = p.ID
|
||||
}
|
||||
|
||||
return gatewayID != 0
|
||||
})
|
||||
|
||||
switch {
|
||||
case gatewayID == 0:
|
||||
return firstNodeID
|
||||
default:
|
||||
return gatewayID
|
||||
if n := z.Len(); n > 0 {
|
||||
s := make([]string, 0, n)
|
||||
|
||||
z.ForEachMachine(func(p *Machine) bool {
|
||||
s = append(s, p.Name)
|
||||
return false
|
||||
})
|
||||
|
||||
return strings.Join(s, " ")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -43,6 +43,29 @@ func (m *Machine) IsGateway() bool {
|
||||
return ok
|
||||
}
|
||||
|
||||
// SetGateway enables/disables a Machine ring0 integration
|
||||
func (m *Machine) SetGateway(enabled bool) error {
|
||||
ri, found := m.getRingInfo(0)
|
||||
switch {
|
||||
case !found && !enabled:
|
||||
return nil
|
||||
case !found:
|
||||
var err error
|
||||
|
||||
if ri, err = m.createRingInfo(0, false); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
ri.Enabled = enabled
|
||||
return m.SyncWireguardConfig(0)
|
||||
}
|
||||
|
||||
// Zone indicates the [Zone] this machine belongs to
|
||||
func (m *Machine) Zone() int {
|
||||
return m.zone.ID
|
||||
}
|
||||
|
||||
func (m *Machine) getPeerByName(name string) (*Machine, bool) {
|
||||
return m.zone.zones.GetMachineByName(name)
|
||||
}
|
||||
|
||||
+20
-33
@@ -3,7 +3,6 @@ package zones
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
|
||||
"darvaza.org/core"
|
||||
@@ -73,38 +72,6 @@ func (m *Machine) tryReadWireguardKeys(ring int) error {
|
||||
}
|
||||
}
|
||||
|
||||
// WriteWireguardKeys writes the wgN.key/wgN.pub files
|
||||
func (m *Machine) WriteWireguardKeys(ring int) error {
|
||||
var err error
|
||||
var key, pub string
|
||||
var ri *RingInfo
|
||||
|
||||
ri, _ = m.getRingInfo(ring)
|
||||
if ri != nil {
|
||||
key = ri.Keys.PrivateKey.String()
|
||||
pub = ri.Keys.PublicKey.String()
|
||||
}
|
||||
|
||||
switch {
|
||||
case key == "":
|
||||
return fs.ErrNotExist
|
||||
case pub == "":
|
||||
pub = ri.Keys.PrivateKey.Public().String()
|
||||
}
|
||||
|
||||
err = m.WriteStringFile(key+"\n", "wg%v.key", ring)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = m.WriteStringFile(pub+"\n", "wg%v.pub", ring)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveWireguardKeys deletes wgN.key and wgN.pub from
|
||||
// the machine's config directory
|
||||
func (m *Machine) RemoveWireguardKeys(ring int) error {
|
||||
@@ -261,3 +228,23 @@ func (m *Machine) RemoveWireguardConfig(ring int) error {
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *Machine) createRingInfo(ring int, enabled bool) (*RingInfo, error) {
|
||||
keys, err := wireguard.NewKeyPair()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ri := &RingInfo{
|
||||
Ring: ring,
|
||||
Enabled: enabled,
|
||||
Keys: keys,
|
||||
}
|
||||
|
||||
err = m.applyRingInfo(ring, ri)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return ri, nil
|
||||
}
|
||||
|
||||
@@ -7,8 +7,9 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func (m *Machine) lookupNetIP() ([]netip.Addr, error) {
|
||||
timeout := 2 * time.Second
|
||||
// LookupNetIP uses the DNS Resolver to get the public addresses associated
|
||||
// to a Machine
|
||||
func (m *Machine) LookupNetIP(timeout time.Duration) ([]netip.Addr, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
|
||||
defer cancel()
|
||||
@@ -16,8 +17,9 @@ func (m *Machine) lookupNetIP() ([]netip.Addr, error) {
|
||||
return m.zone.zones.resolver.LookupNetIP(ctx, "ip", m.FullName())
|
||||
}
|
||||
|
||||
func (m *Machine) updatePublicAddresses() error {
|
||||
addrs, err := m.lookupNetIP()
|
||||
// UpdatePublicAddresses uses the DNS Resolver to set Machine.PublicAddresses
|
||||
func (m *Machine) UpdatePublicAddresses() error {
|
||||
addrs, err := m.LookupNetIP(2 * time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -52,12 +54,16 @@ func (m *Machine) setID() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Machine) scan() error {
|
||||
func (m *Machine) scan(opts *ScanOptions) error {
|
||||
for i := 0; i < RingsCount; i++ {
|
||||
if err := m.tryApplyWireguardConfig(i); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return m.updatePublicAddresses()
|
||||
if !opts.DontResolvePublicAddresses {
|
||||
return m.UpdatePublicAddresses()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package zones
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"path/filepath"
|
||||
|
||||
"darvaza.org/resolver"
|
||||
"github.com/hack-pad/hackpadfs/os"
|
||||
)
|
||||
|
||||
// A ScanOption preconfigures the Zones before scanning
|
||||
type ScanOption func(*Zones, *ScanOptions) error
|
||||
|
||||
// ScanOptions contains flags used by the initial scan
|
||||
type ScanOptions struct {
|
||||
// DontResolvePublicAddresses indicates we shouldn't
|
||||
// pre-populate Machine.PublicAddresses during the
|
||||
// initial scan
|
||||
DontResolvePublicAddresses bool
|
||||
}
|
||||
|
||||
// ResolvePublicAddresses instructs the scanner to use
|
||||
// the DNS resolver to get PublicAddresses of nodes.
|
||||
// Default is true
|
||||
func ResolvePublicAddresses(resolve bool) ScanOption {
|
||||
return func(m *Zones, opt *ScanOptions) error {
|
||||
opt.DontResolvePublicAddresses = !resolve
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// WithLookuper specifies what resolver.Lookuper to use to
|
||||
// find public addresses
|
||||
func WithLookuper(h resolver.Lookuper) ScanOption {
|
||||
return func(m *Zones, opt *ScanOptions) error {
|
||||
if h == nil {
|
||||
return fs.ErrInvalid
|
||||
}
|
||||
m.resolver = resolver.NewResolver(h)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// WithResolver specifies what resolver to use to find
|
||||
// public addresses. if nil is passed, the [net.Resolver] will be used.
|
||||
// The default is using Cloudflare's 1.1.1.1.
|
||||
func WithResolver(h resolver.Resolver) ScanOption {
|
||||
return func(m *Zones, opt *ScanOptions) error {
|
||||
if h == nil {
|
||||
h = resolver.SystemResolver(true)
|
||||
}
|
||||
|
||||
m.resolver = h
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Zones) setDefaults(opt *ScanOptions) error {
|
||||
if m.resolver == nil {
|
||||
h := resolver.NewCloudflareLookuper()
|
||||
|
||||
if err := WithLookuper(h)(m, opt); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewFS builds a [Zones] tree using the given directory
|
||||
func NewFS(dir fs.FS, domain string, opts ...ScanOption) (*Zones, error) {
|
||||
var scanOptions ScanOptions
|
||||
|
||||
z := &Zones{
|
||||
dir: dir,
|
||||
domain: domain,
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
if err := opt(z, &scanOptions); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := z.setDefaults(&scanOptions); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := z.scan(&scanOptions); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return z, nil
|
||||
}
|
||||
|
||||
// New builds a [Zones] tree using the given directory
|
||||
func New(dir, domain string, opts ...ScanOption) (*Zones, error) {
|
||||
dir, err := filepath.Abs(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
base, err := os.NewFS().Sub(dir[1:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return NewFS(base, domain, opts...)
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package zones
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net/netip"
|
||||
|
||||
"git.jpi.io/amery/jpictl/pkg/wireguard"
|
||||
@@ -179,3 +180,170 @@ func RingOneAddress(zoneID, nodeID int) (netip.Addr, bool) {
|
||||
return netip.AddrFrom4(a4), true
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
_ MachineIterator = (*Ring)(nil)
|
||||
_ ZoneIterator = (*Ring)(nil)
|
||||
)
|
||||
|
||||
// A Ring describes all peers on a ring
|
||||
type Ring struct {
|
||||
RingAddressEncoder
|
||||
ZoneIterator
|
||||
|
||||
Peers []*RingPeer
|
||||
}
|
||||
|
||||
// AddPeer adds a [Machine] to the ring
|
||||
func (r *Ring) AddPeer(p *Machine) bool {
|
||||
ri, ok := p.getRingInfo(r.ID)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
nodeID := p.ID
|
||||
zoneID := p.Zone()
|
||||
addr, _ := r.Encode(zoneID, nodeID)
|
||||
|
||||
rp := &RingPeer{
|
||||
Node: p,
|
||||
Address: addr,
|
||||
PrivateKey: ri.Keys.PrivateKey,
|
||||
PeerConfig: wireguard.PeerConfig{
|
||||
Name: fmt.Sprintf("%s-%v", p.Name, r.ID),
|
||||
PublicKey: ri.Keys.PublicKey,
|
||||
Endpoint: wireguard.EndpointAddress{
|
||||
Host: p.FullName(),
|
||||
Port: r.Port,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
switch {
|
||||
case r.ID == 0:
|
||||
r.setRingZeroAllowedIPs(rp)
|
||||
case p.IsGateway():
|
||||
r.setRingOneGatewayAllowedIPs(rp)
|
||||
default:
|
||||
r.setRingOneNodeAllowedIPs(rp)
|
||||
}
|
||||
|
||||
r.Peers = append(r.Peers, rp)
|
||||
return true
|
||||
}
|
||||
|
||||
func (r *Ring) setRingZeroAllowedIPs(rp *RingPeer) {
|
||||
zoneID, _, _ := r.Decode(rp.Address)
|
||||
|
||||
// everyone on ring0 is a gateway to ring1
|
||||
addr, _ := RingOneAddress(zoneID, 0)
|
||||
rp.AllowCIDR(addr, 12)
|
||||
|
||||
// peer
|
||||
rp.AllowCIDR(rp.Address, 32)
|
||||
}
|
||||
|
||||
func (r *Ring) setRingOneGatewayAllowedIPs(rp *RingPeer) {
|
||||
zoneID, _, _ := r.Decode(rp.Address)
|
||||
|
||||
// peer
|
||||
rp.AllowCIDR(rp.Address, 32)
|
||||
|
||||
// ring1 gateways connect to all other ring1 networks
|
||||
r.ForEachZone(func(z *Zone) bool {
|
||||
if z.ID != zoneID {
|
||||
addr, _ := r.Encode(z.ID, 0)
|
||||
rp.AllowCIDR(addr, 12)
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
// ring1 gateways also connect to all ring0 addresses
|
||||
r.ForEachZone(func(z *Zone) bool {
|
||||
z.ForEachMachine(func(p *Machine) bool {
|
||||
if p.IsGateway() {
|
||||
addr, _ := RingZeroAddress(z.ID, p.ID)
|
||||
rp.AllowCIDR(addr, 32)
|
||||
}
|
||||
return false
|
||||
})
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
func (*Ring) setRingOneNodeAllowedIPs(rp *RingPeer) {
|
||||
// only to the peer itself
|
||||
rp.AllowCIDR(rp.Address, 32)
|
||||
}
|
||||
|
||||
// ForEachMachine calls a function for each Machine in the ring
|
||||
// until instructed to terminate the loop
|
||||
func (r *Ring) ForEachMachine(fn func(*Machine) bool) {
|
||||
for _, pp := range r.Peers {
|
||||
if fn(pp.Node) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ExportConfig builds a wgN.conf for the specified machine on the ring
|
||||
func (r *Ring) ExportConfig(p *Machine) (*wireguard.Config, error) {
|
||||
var found bool
|
||||
|
||||
out := &wireguard.Config{
|
||||
Interface: wireguard.InterfaceConfig{
|
||||
ListenPort: r.Port,
|
||||
},
|
||||
}
|
||||
|
||||
for _, pp := range r.Peers {
|
||||
switch {
|
||||
case pp.Node == p:
|
||||
// current
|
||||
found = true
|
||||
out.Interface.Name = pp.PeerConfig.Name
|
||||
out.Interface.Address = pp.Address
|
||||
out.Interface.PrivateKey = pp.PrivateKey
|
||||
default:
|
||||
// peer
|
||||
pc := pp.PeerConfig
|
||||
out.Peer = append(out.Peer, pc)
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
return nil, fs.ErrNotExist
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// A RingPeer is a node on a [Ring]
|
||||
type RingPeer struct {
|
||||
Node *Machine
|
||||
|
||||
Address netip.Addr
|
||||
PrivateKey wireguard.PrivateKey
|
||||
PeerConfig wireguard.PeerConfig
|
||||
}
|
||||
|
||||
// AllowCIDR allows an IP range via this peer
|
||||
func (rp *RingPeer) AllowCIDR(addr netip.Addr, bits int) {
|
||||
cidr := netip.PrefixFrom(addr, bits)
|
||||
rp.PeerConfig.AllowedIPs = append(rp.PeerConfig.AllowedIPs, cidr)
|
||||
}
|
||||
|
||||
// NewRing composes a new Ring for Wireguard setup
|
||||
func NewRing(z ZoneIterator, m MachineIterator, ring int) (*Ring, error) {
|
||||
r := &Ring{
|
||||
RingAddressEncoder: Rings[ring],
|
||||
ZoneIterator: z,
|
||||
}
|
||||
|
||||
m.ForEachMachine(func(p *Machine) bool {
|
||||
r.AddPeer(p)
|
||||
return false
|
||||
})
|
||||
|
||||
return r, nil
|
||||
}
|
||||
|
||||
+58
-14
@@ -5,14 +5,15 @@ import (
|
||||
"sort"
|
||||
)
|
||||
|
||||
func (m *Zones) scan() error {
|
||||
for _, fn := range []func() error{
|
||||
func (m *Zones) scan(opts *ScanOptions) error {
|
||||
for _, fn := range []func(*ScanOptions) error{
|
||||
m.scanDirectory,
|
||||
m.scanMachines,
|
||||
m.scanZoneIDs,
|
||||
m.scanSort,
|
||||
m.scanGateways,
|
||||
} {
|
||||
if err := fn(); err != nil {
|
||||
if err := fn(opts); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -20,7 +21,7 @@ func (m *Zones) scan() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Zones) scanDirectory() error {
|
||||
func (m *Zones) scanDirectory(_ *ScanOptions) error {
|
||||
// each directory is a zone
|
||||
entries, err := fs.ReadDir(m.dir, ".")
|
||||
if err != nil {
|
||||
@@ -45,16 +46,16 @@ func (m *Zones) scanDirectory() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Zones) scanMachines() error {
|
||||
func (m *Zones) scanMachines(opts *ScanOptions) error {
|
||||
var err error
|
||||
m.ForEachMachine(func(p *Machine) bool {
|
||||
err = p.scan()
|
||||
err = p.scan(opts)
|
||||
return err != nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *Zones) scanZoneIDs() error {
|
||||
func (m *Zones) scanZoneIDs(_ *ScanOptions) error {
|
||||
var hasMissing bool
|
||||
var lastZoneID int
|
||||
|
||||
@@ -84,7 +85,7 @@ func (m *Zones) scanZoneIDs() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Zones) scanSort() error {
|
||||
func (m *Zones) scanSort(_ *ScanOptions) error {
|
||||
sort.SliceStable(m.Zones, func(i, j int) bool {
|
||||
id1 := m.Zones[i].ID
|
||||
id2 := m.Zones[j].ID
|
||||
@@ -92,12 +93,7 @@ func (m *Zones) scanSort() error {
|
||||
})
|
||||
|
||||
m.ForEachZone(func(z *Zone) bool {
|
||||
sort.SliceStable(z.Machines, func(i, j int) bool {
|
||||
id1 := z.Machines[i].ID
|
||||
id2 := z.Machines[j].ID
|
||||
return id1 < id2
|
||||
})
|
||||
|
||||
sort.Sort(z)
|
||||
return false
|
||||
})
|
||||
|
||||
@@ -115,6 +111,16 @@ func (m *Zones) scanSort() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Zones) scanGateways(_ *ScanOptions) error {
|
||||
var err error
|
||||
|
||||
m.ForEachZone(func(z *Zone) bool {
|
||||
_, _, err = z.GetGateway()
|
||||
return err != nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (z *Zone) scan() error {
|
||||
// each directory is a machine
|
||||
entries, err := fs.ReadDir(z.zones.dir, z.Name)
|
||||
@@ -139,3 +145,41 @@ func (z *Zone) scan() error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetGateway returns the first gateway found, if none
|
||||
// files will be created to enable the first [Machine] to
|
||||
// be one
|
||||
func (z *Zone) GetGateway() (*Machine, bool, error) {
|
||||
var first *Machine
|
||||
var gateway *Machine
|
||||
|
||||
z.zones.ForEachMachine(func(p *Machine) bool {
|
||||
switch {
|
||||
case p.IsGateway():
|
||||
// found
|
||||
gateway = p
|
||||
case first == nil:
|
||||
// remember
|
||||
first = p
|
||||
default:
|
||||
// keep looking
|
||||
}
|
||||
|
||||
return gateway != nil
|
||||
})
|
||||
|
||||
switch {
|
||||
case gateway != nil:
|
||||
// found one
|
||||
return gateway, false, nil
|
||||
case first != nil:
|
||||
// make one
|
||||
if err := first.SetGateway(true); err != nil {
|
||||
return first, false, err
|
||||
}
|
||||
return first, true, nil
|
||||
default:
|
||||
// Zone without nodes?
|
||||
panic("unreachable")
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -18,12 +18,12 @@ func (m *Zones) SyncAllWireguard() error {
|
||||
var err error
|
||||
|
||||
for ring := 0; ring < RingsCount; ring++ {
|
||||
err = m.PruneWireguardConfig(ring)
|
||||
err = m.WriteWireguardKeys(ring)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = m.WriteWireguardKeys(ring)
|
||||
err = m.SyncWireguardConfig(ring)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
package zones
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"os"
|
||||
)
|
||||
|
||||
var (
|
||||
_ WireguardConfigPruner = (*Zones)(nil)
|
||||
_ WireguardConfigPruner = (*Zone)(nil)
|
||||
_ WireguardConfigPruner = (*Machine)(nil)
|
||||
|
||||
_ WireguardConfigWriter = (*Zones)(nil)
|
||||
_ WireguardConfigWriter = (*Zone)(nil)
|
||||
_ WireguardConfigWriter = (*Machine)(nil)
|
||||
|
||||
_ WireguardConfigSyncer = (*Zones)(nil)
|
||||
_ WireguardConfigSyncer = (*Zone)(nil)
|
||||
_ WireguardConfigSyncer = (*Machine)(nil)
|
||||
|
||||
_ WireguardKeysWriter = (*Zones)(nil)
|
||||
_ WireguardKeysWriter = (*Zone)(nil)
|
||||
_ WireguardKeysWriter = (*Machine)(nil)
|
||||
)
|
||||
|
||||
// A WireguardConfigPruner deletes wgN.conf on all machines under
|
||||
// its scope with the specified ring disabled
|
||||
type WireguardConfigPruner interface {
|
||||
PruneWireguardConfig(ring int) error
|
||||
}
|
||||
|
||||
// PruneWireguardConfig removes wgN.conf files of machines with
|
||||
// the corresponding ring disabled on all zones
|
||||
func (m *Zones) PruneWireguardConfig(ring int) error {
|
||||
return pruneWireguardConfig(m, ring)
|
||||
}
|
||||
|
||||
// PruneWireguardConfig removes wgN.conf files of machines with
|
||||
// the corresponding ring disabled.
|
||||
func (z *Zone) PruneWireguardConfig(ring int) error {
|
||||
return pruneWireguardConfig(z, ring)
|
||||
}
|
||||
|
||||
func pruneWireguardConfig(m MachineIterator, ring int) error {
|
||||
var err error
|
||||
|
||||
m.ForEachMachine(func(p *Machine) bool {
|
||||
err = p.PruneWireguardConfig(ring)
|
||||
if os.IsNotExist(err) {
|
||||
// ignore
|
||||
err = nil
|
||||
}
|
||||
|
||||
return err != nil
|
||||
})
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// PruneWireguardConfig deletes the wgN.conf file if its
|
||||
// presence on the ring is disabled
|
||||
func (m *Machine) PruneWireguardConfig(ring int) error {
|
||||
_, ok := m.getRingInfo(ring)
|
||||
if !ok {
|
||||
return m.RemoveWireguardConfig(ring)
|
||||
}
|
||||
|
||||
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 WireguardConfigSyncer updates all wgN.conf on all machines under
|
||||
// its scope reflecting the state of the ring
|
||||
type WireguardConfigSyncer interface {
|
||||
SyncWireguardConfig(ring int) error
|
||||
}
|
||||
|
||||
// SyncWireguardConfig updates all wgN.conf files for the specified
|
||||
// ring
|
||||
func (m *Zones) SyncWireguardConfig(ring int) error {
|
||||
switch ring {
|
||||
case 0:
|
||||
return syncWireguardConfig(m, m, ring)
|
||||
case 1:
|
||||
var err error
|
||||
m.ForEachZone(func(z *Zone) bool {
|
||||
err = syncWireguardConfig(m, z, ring)
|
||||
return err != nil
|
||||
})
|
||||
return err
|
||||
default:
|
||||
return fs.ErrInvalid
|
||||
}
|
||||
}
|
||||
|
||||
// SyncWireguardConfig updates all wgN.conf files for the specified
|
||||
// ring
|
||||
func (z *Zone) SyncWireguardConfig(ring int) error {
|
||||
switch ring {
|
||||
case 0:
|
||||
return syncWireguardConfig(z.zones, z.zones, ring)
|
||||
case 1:
|
||||
return syncWireguardConfig(z.zones, z, ring)
|
||||
default:
|
||||
return fs.ErrInvalid
|
||||
}
|
||||
}
|
||||
|
||||
func syncWireguardConfig(z ZoneIterator, m MachineIterator, ring int) error {
|
||||
r, err := NewRing(z, m, ring)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
r.ForEachMachine(func(p *Machine) bool {
|
||||
if _, ok := p.getRingInfo(ring); ok {
|
||||
err = p.writeWireguardRingConfig(r)
|
||||
} else {
|
||||
err = p.RemoveWireguardConfig(ring)
|
||||
}
|
||||
return err != nil
|
||||
})
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// SyncWireguardConfig updates all wgN.conf files for the specified
|
||||
// ring
|
||||
func (m *Machine) SyncWireguardConfig(ring int) error {
|
||||
return m.zone.SyncWireguardConfig(ring)
|
||||
}
|
||||
|
||||
// A WireguardKeysWriter writes the Wireguard Keys for all machines
|
||||
// under its scope for the specified ring
|
||||
type WireguardKeysWriter interface {
|
||||
WriteWireguardKeys(ring int) error
|
||||
}
|
||||
|
||||
// WriteWireguardKeys rewrites all wgN.{key,pub} files
|
||||
func (m *Zones) WriteWireguardKeys(ring int) error {
|
||||
return writeWireguardKeys(m, ring)
|
||||
}
|
||||
|
||||
// WriteWireguardKeys rewrites all wgN.{key,pub} files on this zone
|
||||
func (z *Zone) WriteWireguardKeys(ring int) error {
|
||||
return writeWireguardKeys(z, ring)
|
||||
}
|
||||
|
||||
func writeWireguardKeys(m MachineIterator, ring int) error {
|
||||
var err error
|
||||
|
||||
m.ForEachMachine(func(p *Machine) bool {
|
||||
err = p.WriteWireguardKeys(ring)
|
||||
if os.IsNotExist(err) {
|
||||
// ignore
|
||||
err = nil
|
||||
}
|
||||
|
||||
return err != nil
|
||||
})
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// WriteWireguardKeys writes the wgN.key/wgN.pub files
|
||||
func (m *Machine) WriteWireguardKeys(ring int) error {
|
||||
var err error
|
||||
var key, pub string
|
||||
var ri *RingInfo
|
||||
|
||||
ri, _ = m.getRingInfo(ring)
|
||||
if ri != nil {
|
||||
key = ri.Keys.PrivateKey.String()
|
||||
pub = ri.Keys.PublicKey.String()
|
||||
}
|
||||
|
||||
switch {
|
||||
case key == "":
|
||||
return fs.ErrNotExist
|
||||
case pub == "":
|
||||
pub = ri.Keys.PrivateKey.Public().String()
|
||||
}
|
||||
|
||||
err = m.WriteStringFile(key+"\n", "wg%v.key", ring)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = m.WriteStringFile(pub+"\n", "wg%v.pub", ring)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package zones
|
||||
|
||||
import "os"
|
||||
|
||||
// PruneWireguardConfig removes wgN.conf files of machines with
|
||||
// the corresponding ring disabled.
|
||||
func (z *Zone) PruneWireguardConfig(ring int) error {
|
||||
var err error
|
||||
|
||||
z.ForEachMachine(func(p *Machine) bool {
|
||||
_, ok := p.getRingInfo(ring)
|
||||
if !ok {
|
||||
err = p.RemoveWireguardConfig(ring)
|
||||
}
|
||||
return err != nil
|
||||
})
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// WriteWireguardKeys rewrites all wgN.{key,pub} files on this zone
|
||||
func (z *Zone) WriteWireguardKeys(ring int) error {
|
||||
var err error
|
||||
|
||||
z.ForEachMachine(func(p *Machine) bool {
|
||||
err = p.WriteWireguardKeys(ring)
|
||||
if os.IsNotExist(err) {
|
||||
// ignore
|
||||
err = nil
|
||||
}
|
||||
|
||||
return err != nil
|
||||
})
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// PruneWireguardConfig removes wgN.conf files of machines with
|
||||
// the corresponding ring disabled on all zones
|
||||
func (m *Zones) PruneWireguardConfig(ring int) error {
|
||||
var err error
|
||||
|
||||
m.ForEachZone(func(z *Zone) bool {
|
||||
err = z.PruneWireguardConfig(ring)
|
||||
return err != nil
|
||||
})
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// WriteWireguardKeys rewrites all wgN.{key,pub} files
|
||||
func (m *Zones) WriteWireguardKeys(ring int) error {
|
||||
var err error
|
||||
|
||||
m.ForEachZone(func(z *Zone) bool {
|
||||
err = z.WriteWireguardKeys(ring)
|
||||
return err != nil
|
||||
})
|
||||
|
||||
return err
|
||||
}
|
||||
+111
-42
@@ -3,13 +3,86 @@ package zones
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/hack-pad/hackpadfs/os"
|
||||
"sort"
|
||||
|
||||
"darvaza.org/resolver"
|
||||
)
|
||||
|
||||
var (
|
||||
_ MachineIterator = Machines(nil)
|
||||
_ sort.Interface = Machines(nil)
|
||||
|
||||
_ MachineIterator = (*Zone)(nil)
|
||||
_ MachineIterator = (*Zones)(nil)
|
||||
_ ZoneIterator = (*Zones)(nil)
|
||||
)
|
||||
|
||||
// A MachineIterator is a set of Machines we can iterate on
|
||||
type MachineIterator interface {
|
||||
ForEachMachine(func(*Machine) bool)
|
||||
}
|
||||
|
||||
// A ZoneIterator is a set of Zones we can iterate on
|
||||
type ZoneIterator interface {
|
||||
ForEachZone(func(*Zone) bool)
|
||||
}
|
||||
|
||||
// Machines is a list of Machine objects
|
||||
type Machines []*Machine
|
||||
|
||||
// ForEachMachine calls a function for each Machine in the list
|
||||
// until instructed to terminate the loop
|
||||
func (m Machines) ForEachMachine(fn func(*Machine) bool) {
|
||||
for _, p := range m {
|
||||
if fn(p) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Len returns the number of machines in the list
|
||||
func (m Machines) Len() int {
|
||||
return len(m)
|
||||
}
|
||||
|
||||
// Less implements sort.Interface to sort the list
|
||||
func (m Machines) Less(i, j int) bool {
|
||||
a, b := m[i], m[j]
|
||||
za, zb := a.Zone(), b.Zone()
|
||||
|
||||
switch {
|
||||
case za == zb:
|
||||
return a.ID < b.ID
|
||||
default:
|
||||
return za < zb
|
||||
}
|
||||
}
|
||||
|
||||
// Swap implements sort.Interface to sort the list
|
||||
func (m Machines) Swap(i, j int) {
|
||||
m[i], m[j] = m[j], m[i]
|
||||
}
|
||||
|
||||
// FilterMachines produces a subset of the machines offered by the given
|
||||
// iterator fulfilling a condition
|
||||
func FilterMachines(m MachineIterator, cond func(*Machine) bool) (Machines, int) {
|
||||
var out []*Machine
|
||||
|
||||
if cond == nil {
|
||||
// unconditional
|
||||
cond = func(*Machine) bool { return true }
|
||||
}
|
||||
|
||||
m.ForEachMachine(func(p *Machine) bool {
|
||||
if cond(p) {
|
||||
out = append(out, p)
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
return out, len(out)
|
||||
}
|
||||
|
||||
// Zone represents one zone in a cluster
|
||||
type Zone struct {
|
||||
zones *Zones
|
||||
@@ -17,23 +90,51 @@ type Zone struct {
|
||||
ID int `toml:"id"`
|
||||
Name string `toml:"name"`
|
||||
|
||||
Machines []*Machine `toml:"machines"`
|
||||
Machines `toml:"machines"`
|
||||
}
|
||||
|
||||
func (z *Zone) String() string {
|
||||
return z.Name
|
||||
}
|
||||
|
||||
// ForEachMachine calls a function for each Machine in the zone
|
||||
// until instructed to terminate the loop
|
||||
func (z *Zone) ForEachMachine(fn func(*Machine) bool) {
|
||||
for _, p := range z.Machines {
|
||||
if fn(p) {
|
||||
return
|
||||
// SetGateway configures a machine to be the zone's ring0 gateway
|
||||
func (z *Zone) SetGateway(gatewayID int, enabled bool) error {
|
||||
var err error
|
||||
var found bool
|
||||
|
||||
z.ForEachMachine(func(p *Machine) bool {
|
||||
if p.ID == gatewayID {
|
||||
found = true
|
||||
err = p.SetGateway(enabled)
|
||||
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case !found:
|
||||
return fs.ErrNotExist
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// GatewayIDs returns the list of IDs of machines that act as ring0 gateways
|
||||
func (z *Zone) GatewayIDs() ([]int, int) {
|
||||
var out []int
|
||||
z.ForEachMachine(func(p *Machine) bool {
|
||||
if p.IsGateway() {
|
||||
out = append(out, p.ID)
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
return out, len(out)
|
||||
}
|
||||
|
||||
// Zones represents all zones in a cluster
|
||||
type Zones struct {
|
||||
dir fs.FS
|
||||
@@ -86,35 +187,3 @@ func (m *Zones) GetMachineByName(name string) (*Machine, bool) {
|
||||
|
||||
return out, out != nil
|
||||
}
|
||||
|
||||
// NewFS builds a [Zones] tree using the given directory
|
||||
func NewFS(dir fs.FS, domain string) (*Zones, error) {
|
||||
lockuper := resolver.NewCloudflareLookuper()
|
||||
|
||||
z := &Zones{
|
||||
dir: dir,
|
||||
resolver: resolver.NewResolver(lockuper),
|
||||
domain: domain,
|
||||
}
|
||||
|
||||
if err := z.scan(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return z, nil
|
||||
}
|
||||
|
||||
// New builds a [Zones] tree using the given directory
|
||||
func New(dir, domain string) (*Zones, error) {
|
||||
dir, err := filepath.Abs(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
base, err := os.NewFS().Sub(dir[1:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return NewFS(base, domain)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package zones
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
fs "github.com/hack-pad/hackpadfs"
|
||||
)
|
||||
|
||||
// OpenFile opens a file on the cluster's config directory with the specified flags
|
||||
func (m *Zones) OpenFile(name string, flags int, args ...any) (fs.File, error) {
|
||||
if len(args) > 0 {
|
||||
name = fmt.Sprintf(name, args...)
|
||||
}
|
||||
|
||||
return fs.OpenFile(m.dir, name, flags, 0644)
|
||||
}
|
||||
|
||||
// CreateTruncFile creates or truncates a file on the cluster's config directory
|
||||
func (m *Zones) CreateTruncFile(name string, args ...any) (io.WriteCloser, error) {
|
||||
return m.openWriter(name, os.O_CREATE|os.O_TRUNC, args...)
|
||||
}
|
||||
|
||||
// CreateFile creates a file on the cluster's config directory
|
||||
func (m *Zones) CreateFile(name string, args ...any) (io.WriteCloser, error) {
|
||||
return m.openWriter(name, os.O_CREATE, args...)
|
||||
}
|
||||
|
||||
func (m *Zones) openWriter(name string, flags int, args ...any) (io.WriteCloser, error) {
|
||||
f, err := m.OpenFile(name, os.O_WRONLY|flags, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return f.(io.WriteCloser), nil
|
||||
}
|
||||
|
||||
// ReadFile reads a file from the cluster's config directory
|
||||
func (m *Zones) ReadFile(name string, args ...any) ([]byte, error) {
|
||||
if len(args) > 0 {
|
||||
name = fmt.Sprintf(name, args...)
|
||||
}
|
||||
|
||||
return fs.ReadFile(m.dir, name)
|
||||
}
|
||||
Reference in New Issue
Block a user