Signed-off-by: Alejandro Mery <amery@jpi.io>
This commit is contained in:
2023-09-11 21:42:56 +00:00
parent 85b0766418
commit 5019ef26ad
8 changed files with 483 additions and 1 deletions
+31
View File
@@ -0,0 +1,31 @@
// Package dns manages DNS entries for the cluster
package dns
import "net/netip"
// A Config defines a Region
type Config struct {
// Name is the identifier of this Region
Name string
// Regions are a list of (sub)regions that belong to this Region
Regions []string
// Zones are a list of Zones that directly belong to this Region
Zones []string
}
type Region struct {
Name string
}
type Zone struct {
Name string
Machines map[int]*Machine
}
type Machine struct {
ID int
Active bool
Addrs []netip.Addr
}
+31
View File
@@ -0,0 +1,31 @@
package dns
import (
"context"
"io/fs"
"net/netip"
)
func (mgr *Manager) AddHost(_ context.Context, zone string, id int, active bool, addrs ...netip.Addr) error {
if zone == "" || id <= 0 {
return fs.ErrInvalid
}
z, ok := mgr.zones[zone]
if !ok {
z = &Zone{
Name: zone,
Machines: make(map[int]*Machine),
}
mgr.zones[zone] = z
}
z.Machines[id] = &Machine{
ID: id,
Active: active,
Addrs: addrs,
}
return nil
}
+127
View File
@@ -0,0 +1,127 @@
package dns
import (
"errors"
"strings"
"sync"
"darvaza.org/core"
"darvaza.org/slog"
"golang.org/x/net/publicsuffix"
"git.jpi.io/amery/jpictl/pkg/cluster"
)
// Manager is a DNS Manager instance
type Manager struct {
mu sync.Mutex
domain string
suffix string
zones map[string]*Zone
p Provider
l slog.Logger
}
// ManagerOption configures a Manager
type ManagerOption func(*Manager) error
func newErrorManagerOption(err error, hint string) ManagerOption {
return func(*Manager) error {
if hint != "" {
err = core.Wrap(err, hint)
}
return err
}
}
// WithProvider attaches a libdns Provider to the Manager
func WithProvider(p Provider) ManagerOption {
var err error
if p == nil {
p, err = DefaultDNSProvider()
}
if err != nil {
return newErrorManagerOption(err, "WithProvider")
}
return func(mgr *Manager) error {
mgr.p = p
return nil
}
}
// WithLogger attaches a logger to the Manager
func WithLogger(log slog.Logger) ManagerOption {
if log == nil {
log = cluster.DefaultLogger()
}
return func(mgr *Manager) error {
mgr.l = log
return nil
}
}
func (mgr *Manager) setDefaults() error {
var opts []ManagerOption
if mgr.p == nil {
opts = append(opts, WithProvider(nil))
}
if mgr.l == nil {
opts = append(opts, WithLogger(nil))
}
if mgr.domain == "" || mgr.suffix == "" {
return errors.New("domain not specified")
}
mgr.zones = make(map[string]*Zone)
for _, opt := range opts {
if err := opt(mgr); err != nil {
return err
}
}
return nil
}
// WithDomain specifies where the manager operates
func WithDomain(domain string) ManagerOption {
base, err := publicsuffix.EffectiveTLDPlusOne(domain)
if err != nil {
return newErrorManagerOption(err, "publicsuffix")
}
suffix := strings.TrimSuffix(domain, base)
if suffix != "" {
suffix = "." + suffix[:len(suffix)-1]
}
return func(mgr *Manager) error {
mgr.domain = base
mgr.suffix = suffix
return nil
}
}
// NewManager creates a DNS manager with the
func NewManager(opts ...ManagerOption) (*Manager, error) {
mgr := new(Manager)
for _, opt := range opts {
if err := opt(mgr); err != nil {
return nil, err
}
}
if err := mgr.setDefaults(); err != nil {
return nil, err
}
return mgr, nil
}
+36
View File
@@ -0,0 +1,36 @@
package dns
import (
"fmt"
"os"
"github.com/libdns/cloudflare"
"github.com/libdns/libdns"
)
const (
// CloudflareAPIToken is the environment variable
// containing the API Token
CloudflareAPIToken = "CLOUDFLARE_DNS_API_TOKEN"
)
// Provider manages DNS entries
type Provider interface {
libdns.RecordGetter
libdns.RecordDeleter
}
// DefaultDNSProvider returns a cloudflare DNS provider
// using an API Token from env [CloudflareAPIToken]
func DefaultDNSProvider() (*cloudflare.Provider, error) {
s := os.Getenv(CloudflareAPIToken)
if s == "" {
return nil, fmt.Errorf("%q: %s", CloudflareAPIToken, "not found")
}
p := &cloudflare.Provider{
APIToken: s,
}
return p, nil
}
+134
View File
@@ -0,0 +1,134 @@
package dns
import (
"bytes"
"fmt"
"io"
"net/netip"
"sort"
"time"
"darvaza.org/core"
"github.com/libdns/libdns"
)
func (mgr *Manager) WriteTo(w io.Writer) (int64, error) {
var buf bytes.Buffer
var zones sort.StringSlice
// sort zones
for name := range mgr.zones {
zones = append(zones, name)
}
sort.Sort(zones)
for _, name := range zones {
z := mgr.zones[name]
if buf.Len() > 0 {
_, _ = buf.WriteRune('\n')
}
// servers
err := mgr.writeZoneMachinesToBuffer(&buf, name, z)
if err != nil {
return 0, err
}
}
return buf.WriteTo(w)
}
func (mgr *Manager) writeRecordsToBuffer(buf *bytes.Buffer, records ...libdns.Record) {
for _, rr := range records {
fqdn := fmt.Sprintf("%s.%s", rr.Name, mgr.domain)
_, _ = fmt.Fprintf(buf, "%s\t%v\tIN\t%s\t%v\n",
fqdn, int(rr.TTL/time.Second), rr.Type, rr.Value)
}
}
func (mgr *Manager) writeZoneMachinesToBuffer(buf *bytes.Buffer, zone_name string, z *Zone) error {
// title
_, _ = fmt.Fprintf(buf, ";\n; %s\n;\n", zone_name)
records := mgr.genMachineRecords(z)
mgr.writeRecordsToBuffer(buf, records...)
// zone alias
_, _ = fmt.Fprintf(buf, "; %s\n", zone_name)
records = mgr.genAliasRecords(zone_name, true, z)
mgr.Sort(records)
mgr.writeRecordsToBuffer(buf, records...)
return nil
}
func (mgr *Manager) genMachineRecords(z *Zone) []libdns.Record {
var out []libdns.Record
for _, p := range z.Machines {
pqdn := fmt.Sprintf("%s-%v%s", z.Name, p.ID, mgr.suffix)
for _, addr := range p.Addrs {
out = append(out, libdns.Record{
Name: pqdn,
Type: core.IIf(addr.Is6(), "AAAA", "A"),
TTL: time.Second,
Value: addr.String(),
})
}
}
mgr.Sort(out)
return out
}
func (mgr *Manager) genAliasRecords(name string, activeOnly bool, zones ...*Zone) []libdns.Record {
var out []libdns.Record
fqdn := fmt.Sprintf("%s%s", name, mgr.suffix)
for _, z := range zones {
for _, p := range z.Machines {
if p.Active || !activeOnly {
for _, addr := range p.Addrs {
out = append(out, libdns.Record{
Name: fqdn,
Type: core.IIf(addr.Is6(), "AAAA", "A"),
TTL: time.Second,
Value: addr.String(),
})
}
}
}
}
return out
}
func (mgr *Manager) Sort(records []libdns.Record) {
sort.SliceStable(records, func(i, j int) bool {
a := &records[i]
b := &records[j]
switch {
case a.Name < b.Name:
return true
case a.Name > b.Name:
return false
case a.Type < b.Type:
return true
case a.Type > b.Type:
return false
case a.Type == "A" || a.Type == "AAAA":
var aAddr, bAddr netip.Addr
aAddr.UnmarshalText([]byte(a.Value))
bAddr.UnmarshalText([]byte(b.Value))
return aAddr.Less(bAddr)
case a.Value < b.Value:
return true
default:
return false
}
})
}