From 1a47985bd75d26178f86b1ba17f52a901066bab0 Mon Sep 17 00:00:00 2001 From: Alejandro Mery Date: Tue, 12 Sep 2023 15:14:53 +0000 Subject: [PATCH] dns: Manager.WriteTo() generates BIND config, fully qualifies Signed-off-by: Alejandro Mery --- pkg/dns/record.go | 17 +++++++++++++ pkg/dns/write.go | 62 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 pkg/dns/write.go diff --git a/pkg/dns/record.go b/pkg/dns/record.go index 407844f..be97701 100644 --- a/pkg/dns/record.go +++ b/pkg/dns/record.go @@ -12,6 +12,10 @@ import ( "github.com/libdns/libdns" ) +func (mgr *Manager) fqdn(name string) string { + return fmt.Sprintf("%s.%s.", name, mgr.domain) +} + // SortAddrSlice sorts a slice of [netip.Addr] func SortAddrSlice(s []netip.Addr) []netip.Addr { sort.Slice(s, func(i, j int) bool { @@ -193,3 +197,16 @@ func (mgr *Manager) genZoneHostRecords(z *Zone) []AddrRecord { SortAddrRecords(out) return out } + +func (mgr *Manager) genRegionAddressesCached(name string, + zones map[string][]netip.Addr) []netip.Addr { + // + var addrs []netip.Addr + + for _, zoneName := range mgr.regions[name] { + addrs = append(addrs, zones[zoneName]...) + } + + SortAddrSlice(addrs) + return addrs +} diff --git a/pkg/dns/write.go b/pkg/dns/write.go new file mode 100644 index 0000000..5fdb05b --- /dev/null +++ b/pkg/dns/write.go @@ -0,0 +1,62 @@ +package dns + +import ( + "bytes" + "fmt" + "io" + "net/netip" +) + +// WriteTo writes the DNS data for the cluster +func (mgr *Manager) WriteTo(w io.Writer) (int64, error) { + var buf bytes.Buffer + + cache := make(map[string][]netip.Addr) + + // zones + for _, z := range mgr.zones { + mgr.writeZoneHosts(&buf, z) + + // zone alias + addrs := mgr.genZoneAddresses(z) + zoneName := z.Name + + rr := AddrRecord{ + Name: mgr.fqdn(zoneName + mgr.suffix), + Addr: addrs, + } + _, _ = rr.WriteTo(&buf) + + // and cache for regions + cache[zoneName] = addrs + } + + // regions, sorted + for _, name := range mgr.genRegionsSorted() { + addrs := mgr.genRegionAddressesCached(name, cache) + + mgr.writeRegionAddresses(&buf, name, addrs) + } + + return buf.WriteTo(w) +} + +func (mgr *Manager) writeZoneHosts(w io.Writer, z *Zone) { + _, _ = fmt.Fprintf(w, ";\n; %s\n;\n", z.Name) + + for _, rr := range mgr.genZoneHostRecords(z) { + rr.Name = mgr.fqdn(rr.Name) + _, _ = rr.WriteTo(w) + } +} + +func (mgr *Manager) writeRegionAddresses(w io.Writer, name string, addrs []netip.Addr) { + _, _ = fmt.Fprintf(w, "; %s\n", name) + + rr := AddrRecord{ + Name: mgr.fqdn(name + mgr.suffix), + Addr: addrs, + } + + _, _ = rr.WriteTo(w) +}