This repository has been archived on 2024-04-02. You can view files and clone it, but cannot push or open issues or pull requests.
ddnser/main.go

88 lines
1.8 KiB
Go
Raw Normal View History

2023-01-10 01:09:35 +00:00
package main
2023-01-10 03:23:32 +00:00
import (
2023-01-11 23:38:19 +00:00
"context"
2023-01-10 03:23:32 +00:00
"log"
2023-01-11 23:38:19 +00:00
"os"
"os/exec"
"strings"
2023-01-12 00:59:37 +00:00
"sync"
2023-01-11 23:38:19 +00:00
"time"
2023-01-10 03:23:32 +00:00
)
2023-01-11 23:38:19 +00:00
type refreshChan chan string
2023-01-10 01:09:35 +00:00
func main() {
2023-01-11 23:38:19 +00:00
if len(os.Args) < 2 {
log.Fatal("Must provide config file path as first argument")
2023-01-10 03:23:32 +00:00
}
2023-01-11 23:38:19 +00:00
config, err := LoadConfig(os.Args[1])
2023-01-10 03:23:32 +00:00
if err != nil {
log.Fatal(err)
}
2023-01-10 01:09:35 +00:00
2023-01-11 23:38:19 +00:00
refr := make(refreshChan)
errch := make(chan error)
go poller(config.Every, refr)
go ipPoller(refr, errch)
for {
select {
case reason := <-refr:
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(10)*time.Second)
defer cancel()
log.Printf("Running because of %s", reason)
2023-01-12 00:59:37 +00:00
var wg sync.WaitGroup
wg.Add(len(config.Domains))
2023-01-11 23:38:19 +00:00
for _, d := range config.Domains {
2023-01-12 00:59:37 +00:00
go func(d Domain, wg *sync.WaitGroup) {
record, err := d.NameServer.SetRecord(ctx, d.Name, config.Ip)
if err != nil {
2023-05-09 12:34:38 +00:00
log.Printf("[%s] error: %s", d.Name, err.Error())
2023-01-12 00:59:37 +00:00
// TODO: Reportar errores
return
}
log.Printf("[%s] Set to %s", d.Name, record)
wg.Done()
}(d, &wg)
2023-01-11 23:38:19 +00:00
}
case err := <-errch:
log.Fatal(err)
}
}
}
func poller(every int, refr refreshChan) {
for {
time.Sleep(time.Duration(every) * time.Minute)
refr <- "poll"
}
}
func ipPoller(refr refreshChan, errch chan error) {
var lastWatched string
for {
cmd := exec.Command("ip", "address")
out, err := cmd.Output()
if err != nil {
errch <- err
return
}
var addrs string
lines := strings.Split(string(out), "\n")
for _, line := range lines {
prefix := " inet "
if strings.Index(line, prefix) == 0 {
last := strings.Index(line[len(prefix):], "/")
ip := line[len(prefix) : len(prefix)+last]
addrs = addrs + ip + "/"
}
}
if addrs != lastWatched {
refr <- "ip changed"
lastWatched = addrs
}
time.Sleep(time.Duration(2) * time.Second)
}
2023-01-10 01:09:35 +00:00
}