-
Notifications
You must be signed in to change notification settings - Fork 0
/
daemon.go
74 lines (64 loc) · 1.67 KB
/
daemon.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
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
"time"
"github.com/sirupsen/logrus"
)
type daemonOpt struct {
appConfig *AppConfig
logger *logrus.Logger
exit chan string
}
// runDaemon loops on updateIP until daemonOpt.exit channel is signaled.
func runDaemon(do *daemonOpt) {
dur, _ := do.appConfig.Duration(keyInterval.name, time.Minute*11)
if dur <= time.Second {
do.logger.Errorf("invalid interval (%v); defaulting to 11 minutes", dur)
dur = time.Minute * 11
}
hostname := do.appConfig.getKeyVal(keyHostname)
log := do.logger.WithFields(logrus.Fields{"interval": dur, "hostname": hostname})
log.Info("Dynip daemon starting")
ticker := time.NewTicker(dur)
defer ticker.Stop()
go signalMon(do.exit)
var err error
var result Result
var skip, skipCount int
var maxSkips = int((time.Hour * 24) / dur)
for {
select {
case msg := <-do.exit:
log.Info("Dynip daemon exiting: ", msg)
return
case <-ticker.C:
if skipCount >= skip {
skipCount = 0
log.Info("Dynip updating IP")
result, err = updateIP(do.appConfig, do.logger)
if err == nil {
skip = 0
log.WithFields(logrus.Fields{"result": result}).Info("ip update successful")
} else if skip < maxSkips {
skip++
log.WithFields(logrus.Fields{"result": result, "err": err}).Error("ip update failed")
}
} else {
skipCount++
log.WithFields(logrus.Fields{
"skips_remaining": skip - skipCount}).Info("Skipping due to previous errors")
}
}
}
}
func signalMon(exit chan<- string) {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
defer signal.Stop(c)
// block until signal
s := <-c
exit <- fmt.Sprintf("%v", s)
}