-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
99 lines (81 loc) · 2.15 KB
/
app.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package mddns
import (
"context"
"github.com/mnavarrocarter/mddns/debug"
"github.com/mnavarrocarter/mddns/ip"
"github.com/mnavarrocarter/mddns/ip/ipify"
"github.com/mnavarrocarter/mddns/provider"
_ "github.com/mnavarrocarter/mddns/provider/google"
"github.com/mnavarrocarter/mddns/provider/system"
"github.com/sirupsen/logrus"
"net"
"os/signal"
"syscall"
"time"
)
type App struct {
ConfigFile string
Watch bool
Interval time.Duration
Debug int
}
func (a *App) Run() {
logger := logrus.New()
logger.Level = logrus.Level(a.Debug)
logger.Formatter = &logrus.TextFormatter{
ForceColors: true,
TimestampFormat: time.RFC3339,
FullTimestamp: true,
}
ctx := context.Background()
ctx, stop := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM)
defer stop()
debug.MutateDefaultClient(logger.Debugf)
schedule := ip.Scheduler(a.Interval)
back := ipify.NewBackend(nil)
updater, err := system.NewUpdater(a.ConfigFile, a.Watch, logger.Errorf)
if err != nil {
logger.Fatalf("provider error: %s", err.Error())
}
ips := generateIps(logger, schedule(back))
runLoop(ctx, logger, ips, updater)
}
func generateIps(logger *logrus.Logger, provider ip.Provider) <-chan net.IP {
ipChan := make(chan net.IP)
// This goroutine listens for new ip addresses and passes them to the ip channel
go func() {
logger.Infof("watching for ip changes")
for {
ctx := context.Background()
i, err := provider.GetIP(ctx)
if err != nil {
logger.Errorf("ip provider error: %s", err.Error())
continue
}
ipChan <- i
}
}()
return ipChan
}
func runLoop(ctx context.Context, logger *logrus.Logger, ips <-chan net.IP, updater provider.Updater) {
logger.Infof("starting the main loop")
defer func() {
logger.Infof("main loop stopped")
}()
// This loop checks for new ips or signals
for {
select {
case _ = <-ctx.Done():
logger.Warning("closing signal received")
return
case i := <-ips:
logger.Infof("new ip found: %s", i.String())
err := updater.Update(ctx, i)
if err != nil {
logger.Errorf("failed to update ip: %s", err.Error())
continue
}
logger.Infof("new ip updated: %s", i.String())
}
}
}