-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
270 lines (227 loc) · 6.88 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package main
import (
"context"
"flag"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/route53"
"github.com/aws/aws-sdk-go-v2/service/route53/types"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/rs/zerolog"
)
var (
updateDuration = prometheus.NewCounter(prometheus.CounterOpts{
Name: "update_route53_duration_total",
Help: "Duration for updating Route53",
})
dnsName = "" // DNS_NAME environment variable
dnsTTL = uint64(300) // DNS_TTL environment variable
hostedZoneId = "" // HOSTED_ZONE_ID environment variable
checkIPURL = "http://checkip.amazonaws.com/" // CHECK_IP environment variable
sleepPeriod = 5 * time.Minute // SLEEP_PERIOD environment variable
logger zerolog.Logger
)
func init() {
prometheus.MustRegister(updateDuration)
}
func updateRoute53(svc *route53.Client) {
logger := logger // local copy of logger
// Fetch current IP address
resp, err := http.Get(checkIPURL)
if err != nil {
logger.Err(err).Msg("unable to fetch current address")
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
logger.Err(err).Msg("unable to read response body")
return
}
// Validate IP address
ipstr := strings.TrimSpace(string(body))
ip := net.ParseIP(ipstr)
if ip == nil {
logger.Error().
Str("address", ipstr).
Msg("unable to parse address")
return
}
logger = logger.With().Str("currentAddress", ipstr).Logger()
// Fetch current value of record in AWS Route53
currentRecordValue, currentRecordTTL, err := getCurrentRecordValue(svc)
if err != nil {
logger.Err(err).Msg("unable to get current record value")
return
}
logger = logger.With().
Str("currentRecordValue", currentRecordValue).
Uint64("currentRecordTTL", currentRecordTTL).Logger()
// Check if the current IP is different from the record value
if currentRecordValue == ipstr &&
currentRecordTTL == dnsTTL {
logger.Info().Msg("address has not changed")
return
}
// Update the record in AWS Route53
input := &route53.ChangeResourceRecordSetsInput{
ChangeBatch: &types.ChangeBatch{
Changes: []types.Change{
{
Action: types.ChangeActionUpsert,
ResourceRecordSet: &types.ResourceRecordSet{
Name: aws.String(dnsName),
Type: types.RRTypeA,
TTL: aws.Int64(int64(dnsTTL)),
ResourceRecords: []types.ResourceRecord{{Value: aws.String(ipstr)}},
},
},
},
},
HostedZoneId: aws.String("/hostedzone/" + hostedZoneId),
}
changeOutput, err := svc.ChangeResourceRecordSets(context.TODO(), input)
if err != nil {
logger.Err(err).Msg("unable to change record sets")
return
}
logger = logger.With().Str("change", *changeOutput.ChangeInfo.Id).Logger()
logger.Info().Msg("change submitted")
// Wait until the changes are INSYNC
for {
resp, err := svc.GetChange(context.TODO(), &route53.GetChangeInput{
Id: aws.String(*changeOutput.ChangeInfo.Id),
})
if err != nil {
logger.Err(err).Msg("unable to get change status")
break
}
if resp.ChangeInfo.Status == types.ChangeStatusInsync {
// Fetch current value of record again to confirm the change
updatedRecordValue, updatedRecordTTL, err := getCurrentRecordValue(svc)
if err != nil {
logger.Err(err).Msg("unable to get updated record value")
return
}
logger.Info().
Str("updatedRecordValue", updatedRecordValue).
Uint64("updatedRecordTTL", updatedRecordTTL).
Msg("change propagated")
break
}
// Wait 10 seconds before checking again
time.Sleep(10 * time.Second)
}
}
func getCurrentRecordValue(svc *route53.Client) (string, uint64, error) {
listInput := &route53.ListResourceRecordSetsInput{
HostedZoneId: aws.String("/hostedzone/" + hostedZoneId),
}
listOutput, err := svc.ListResourceRecordSets(context.TODO(), listInput)
if err != nil {
return "", 0, err
}
var currentRecordValue string
var currentRecordTTL uint64
for _, recordSet := range listOutput.ResourceRecordSets {
if *recordSet.Name == (dnsName+".") && recordSet.Type == types.RRTypeA {
currentRecordValue = *recordSet.ResourceRecords[0].Value
currentRecordTTL = uint64(*recordSet.TTL)
break
}
}
return currentRecordValue, currentRecordTTL, nil
}
func main() {
var err error
console := flag.Bool("console", false, "enable console logging")
port := flag.Uint("port", 8080, "port for health check/metrics server")
flag.Parse()
if *console {
logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout}).With().Timestamp().Logger()
} else {
logger = zerolog.New(os.Stdout).With().Timestamp().Logger()
}
if *port < 1 || *port > 65535 {
logger.Fatal().Msg("invalid port number")
}
dnsName = os.Getenv("DNS_NAME")
if dnsName == "" {
logger.Fatal().Msg("missing DNS_NAME environment variable")
}
dnsTTLStr := os.Getenv("DNS_TTL")
if dnsTTLStr != "" {
dnsTTL, err = strconv.ParseUint(dnsTTLStr, 10, 32)
if err != nil {
logger.Fatal().Msg("invalid DNS_TTL environment variable")
}
}
hostedZoneId = os.Getenv("HOSTED_ZONE_ID")
if hostedZoneId == "" {
logger.Fatal().Msg("missing HOSTED_ZONE_ID environment variable")
}
tmpCheckIPURL := os.Getenv("CHECK_IP")
if tmpCheckIPURL != "" {
_, err := url.Parse(tmpCheckIPURL)
if err != nil {
logger.Fatal().Msg("invalid CHECK_IP environment variable")
}
checkIPURL = tmpCheckIPURL
}
sleepPeriodStr := os.Getenv("SLEEP_PERIOD")
if sleepPeriodStr != "" {
sleepPeriod, err = time.ParseDuration(sleepPeriodStr)
if err != nil {
logger.Fatal().Msg("invalid SLEEP_PERIOD environment variable")
}
}
logger = logger.With().
Str("dnsName", dnsName).
Str("hostedZoneId", hostedZoneId).
Logger()
// Log startup message
logger.Info().
Str("checkIPURL", checkIPURL).
Str("sleepPeriod", sleepPeriod.String()).
Uint64("dnsTTL", dnsTTL).
Msg("starting route53-updater...")
// Load AWS configuration
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
logger.Err(err).Msg("unable to load aws configuration")
}
// Create Route53 client
svc := route53.NewFromConfig(cfg)
// Start health check server
go func() {
http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "text/plain")
fmt.Fprint(w, "200 OK")
})
// Add Prometheus metrics endpoint
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(fmt.Sprintf(":%d", *port), nil)
}()
// Start the main loop
for {
// Start the duration timer
start := time.Now()
// Update Route53
updateRoute53(svc)
// Record the duration
updateDuration.Add(float64(time.Since(start).Seconds()))
// Wait before checking again
time.Sleep(sleepPeriod)
}
}