-
Notifications
You must be signed in to change notification settings - Fork 14
/
main.go
240 lines (198 loc) · 6.51 KB
/
main.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package main
import (
"context"
"encoding/json"
"errors"
"github.com/cromefire/fritzbox-cloudflare-dyndns/pkg/cloudflare"
"github.com/cromefire/fritzbox-cloudflare-dyndns/pkg/dyndns"
"github.com/cromefire/fritzbox-cloudflare-dyndns/pkg/polling"
"github.com/cromefire/fritzbox-cloudflare-dyndns/pkg/util"
"github.com/joho/godotenv"
"github.com/prometheus/client_golang/prometheus/promhttp"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
)
func main() {
// Load any env variables defined in .env.dev files
_ = godotenv.Load(".env", ".env.dev")
rootLogger := slog.Default()
updater, updateStatus := newUpdater(rootLogger)
updater.StartWorker()
ctx, cancel := context.WithCancelCause(context.Background())
ipv6LocalAddress := os.Getenv("DEVICE_LOCAL_ADDRESS_IPV6")
var localIp net.IP
if ipv6LocalAddress != "" {
localIp = net.ParseIP(ipv6LocalAddress)
if localIp == nil {
rootLogger.Error("Failed to parse IP from DEVICE_LOCAL_ADDRESS_IPV6, exiting")
return
}
rootLogger.Info("Using the IPv6 Prefix to construct the IPv6 Address")
}
bind := os.Getenv("METRICS_BIND")
pollStatus := polling.StartPollServer(updater.In, &localIp, rootLogger)
pushStatus := startPushServer(updater.In, &localIp, rootLogger, cancel)
status := util.Status{
Push: pushStatus,
Poll: pollStatus,
Updates: updateStatus,
}
if bind != "" {
token := readSecret("METRICS_TOKEN")
startMetricsServer(bind, rootLogger, status, token, cancel)
}
// Create a OS signal shutdown channel
shutdown := make(chan os.Signal)
signal.Notify(shutdown, syscall.SIGTERM)
signal.Notify(shutdown, syscall.SIGINT)
// Wait for either the context to finish or the shutdown signal
select {
case <-ctx.Done():
rootLogger.Error("Context closed", util.ErrorAttr(context.Cause(ctx)))
os.Exit(1)
case <-shutdown:
break
}
rootLogger.Info("Shutdown detected")
}
func newUpdater(logger *slog.Logger) (*cloudflare.Updater, []*util.UpdateStatus) {
const subsystem = "cf_updater"
logger = logger.With(util.SubsystemAttr(subsystem))
u := cloudflare.NewUpdater(slog.Default().With(util.SubsystemAttr(subsystem)), subsystem)
token := readSecret("CLOUDFLARE_API_TOKEN")
email := os.Getenv("CLOUDFLARE_API_EMAIL")
key := readSecret("CLOUDFLARE_API_KEY")
if token == "" {
if email == "" || key == "" {
logger.Info("Env CLOUDFLARE_API_TOKEN not found, disabling Cloudflare updates", util.SubsystemAttr(subsystem))
return u, nil
} else {
logger.Warn("Using deprecated credentials via the API key")
}
}
ipv4Zone := os.Getenv("CLOUDFLARE_ZONES_IPV4")
ipv6Zone := os.Getenv("CLOUDFLARE_ZONES_IPV6")
if ipv4Zone == "" && ipv6Zone == "" {
logger.Warn("Env CLOUDFLARE_ZONES_IPV4 and CLOUDFLARE_ZONES_IPV6 not found, disabling Cloudflare updates", util.SubsystemAttr(subsystem))
return u, nil
}
if ipv4Zone != "" {
u.SetIPv4Zones(ipv4Zone)
}
if ipv6Zone != "" {
u.SetIPv6Zones(ipv6Zone)
}
var err error
var status []*util.UpdateStatus
if token != "" {
err, status = u.InitWithToken(token)
} else {
err, status = u.InitWithKey(email, key)
}
if err != nil {
logger.Error("Failed to init Cloudflare updater, disabling Cloudflare updates")
os.Exit(1)
}
return u, status
}
func startPushServer(out chan<- *net.IP, localIp *net.IP, logger *slog.Logger, cancel context.CancelCauseFunc) *util.PushStatus {
const subsystem = "push_server"
logger = logger.With(util.SubsystemAttr(subsystem))
bind := os.Getenv("DYNDNS_SERVER_BIND")
if bind == "" {
logger.Info("Env DYNDNS_SERVER_BIND not found, disabling DynDns server")
return nil
}
status := util.PushStatus{
Succeeded: true,
}
server := dyndns.NewServer(out, localIp, logger, subsystem, &status)
server.Username = os.Getenv("DYNDNS_SERVER_USERNAME")
server.Password = readSecret("DYNDNS_SERVER_PASSWORD")
pushMux := http.NewServeMux()
pushMux.HandleFunc("/ip", server.Handler)
s := &http.Server{
Addr: bind,
ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelError),
Handler: pushMux,
}
go func() {
err := s.ListenAndServe()
cancel(errors.Join(errors.New("http server error"), err))
}()
logger.Info("DynDns server started", slog.String("addr", bind))
return &status
}
func startMetricsServer(bind string, logger *slog.Logger, status util.Status, token string, cancel context.CancelCauseFunc) {
const subsystem = "metrics"
logger = logger.With(util.SubsystemAttr(subsystem))
metricsMux := http.NewServeMux()
metricsMux.Handle("/metrics", promhttp.Handler())
metricsMux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if status.Poll != nil && !status.Poll.Succeeded {
w.WriteHeader(http.StatusServiceUnavailable)
} else if status.Push != nil && !status.Push.Succeeded {
w.WriteHeader(http.StatusServiceUnavailable)
} else if status.Updates != nil {
anyUnsuccessful := false
for _, u := range status.Updates {
if !u.Succeeded {
anyUnsuccessful = true
break
}
}
if anyUnsuccessful {
w.WriteHeader(http.StatusServiceUnavailable)
} else {
w.WriteHeader(http.StatusOK)
}
}
encoder := json.NewEncoder(w)
err := encoder.Encode(status)
if err != nil {
logger.Error("Failed to encode health check response", util.ErrorAttr(err))
return
}
})
metricsMux.HandleFunc("/liveness", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
metricServer := &http.Server{
Addr: bind,
ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelError),
}
if token == "" {
metricServer.Handler = metricsMux
} else {
tokenHandler := util.NewTokenHandler(metricsMux, token)
metricServer.Handler = tokenHandler
}
go func() {
err := metricServer.ListenAndServe()
cancel(errors.Join(errors.New("metrics http server error"), err))
}()
logger.Info("metrics server started", slog.String("addr", bind))
}
func readSecret(envName string) string {
secret := os.Getenv(envName)
if secret != "" {
slog.Info("Secret passed via environment variable " + envName + ". It's recommended to pass secrets via files, see https://github.com/cromefire/fritzbox-cloudflare-dyndns?tab=readme-ov-file#passing-secrets.")
return secret
}
passwordFilePath := os.Getenv(envName + "_FILE")
if passwordFilePath != "" {
content, err := os.ReadFile(passwordFilePath)
if err != nil {
slog.Error("Failed to read secret from file "+passwordFilePath, util.ErrorAttr(err))
} else {
secret = strings.TrimSuffix(strings.TrimSuffix(string(content), "\r\n"), "\n")
}
}
return secret
}