-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
427 lines (352 loc) · 9.94 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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
package main
import (
"context"
"flag"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/route53"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/events"
"github.com/docker/docker/api/types/filters"
docker "github.com/docker/docker/client"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"io"
"io/ioutil"
"net/http"
"regexp"
"strings"
"sync"
)
func logAndFailIfError(err error) {
if err != nil {
log.Fatal(err)
}
}
const (
containerStart = "start"
containerStop = "die"
serviceLabelKey = "discovery.service.name"
taskArnLabelKey = "com.amazonaws.ecs.task-arn"
)
type worker struct {
id int
events <-chan events.Message
quit <-chan bool
failures chan<- error
processors map[string]processor
wg *sync.WaitGroup
}
type processor interface {
process(events.Message) error
}
func createProcessor(fn func(message events.Message) error) processor {
return &eventProcessor{
processFn: fn,
}
}
type eventProcessor struct {
processFn func(message events.Message) error
}
func (p *eventProcessor) process(e events.Message) error {
return p.processFn(e)
}
func newWorker(id int, events <-chan events.Message, quit <-chan bool, failures chan<- error,
processors map[string]processor, wg *sync.WaitGroup) *worker {
return &worker{
id: id,
events: events,
quit: quit,
failures: failures,
processors: processors,
wg: wg,
}
}
func (w *worker) Start() {
go func() {
defer w.wg.Done()
for {
select {
case e := <-w.events:
if p, ok := w.processors[e.Action]; ok {
log.Infof("Worker: %v handled: %+v", w.id, e)
if err := p.process(e); err != nil {
w.failures <- err
}
} else {
log.Infof("Ignoring event: %v", e.Action)
}
case value := <-w.quit:
log.Infof("Worker: %v is quitting, with value %v", w.id, value)
return
}
}
}()
}
func mapErrorChannel(dockerErrors <-chan error, failures <-chan error) <-chan bool {
quitChannel := make(chan bool)
go func() {
defer close(quitChannel)
for {
select {
case e := <-dockerErrors:
if e != io.EOF {
log.Info("Received error on events channel")
log.Error(e)
quitChannel <- true
return
}
case f := <-failures:
log.Errorf("Error occurred during processing: %+v", f)
quitChannel <- true
return
}
}
}()
return quitChannel
}
func getContainerEvents(client *docker.Client, ctx context.Context) (<-chan events.Message, <-chan error) {
eventFilter := filters.NewArgs()
eventFilter.Add("Type", events.ContainerEventType)
return client.Events(ctx, types.EventsOptions{Filters: eventFilter})
}
type predicate func(string) bool
func getLabelValue(container types.ContainerJSON, predicate predicate) (string, bool) {
for k, v := range container.Config.Labels {
if predicate(strings.ToLower(k)) {
return v, true
}
}
return "", false
}
var isServiceName predicate = func(k string) bool { return k == serviceLabelKey }
var isTaskArn predicate = func(k string) bool { return k == taskArnLabelKey }
var ipRegex = regexp.MustCompile(`"IPv4Addresses":\s*\[\s*"([^"]+)"\]`)
func getContainerIp(containerID string) (string, error) {
// ifconfig docker0 | grep -oP 'inet addr:\K\S+'
// run container with --add-host host:$(ifconfig docker0 | grep -oP 'inet addr:\K\S+')
resp, err := http.Get(fmt.Sprintf("http://host:51678/v1/tasks?dockerid=%v", containerID))
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
bodyStr := string(body)
matches := ipRegex.FindStringSubmatch(bodyStr)
if len(matches) == 0 {
return "", errors.New("No IP address field found")
}
return matches[1], nil
}
const defaultTTL = 0
const defaultWeight = 1
type hostedZone struct {
id string
name string
}
func (h *hostedZone) withServiceName(serviceName string) string {
return serviceName + "." + h.name
}
func createARecord(serviceName string, localIP string, hostedZone *hostedZone) error {
sess, err := session.NewSession()
if err != nil {
return err
}
r53 := route53.New(sess)
// This API call creates a new DNS record for this host
dnsName := hostedZone.withServiceName(serviceName)
params := &route53.ChangeResourceRecordSetsInput{
ChangeBatch: &route53.ChangeBatch{
Changes: []*route53.Change{
{
Action: aws.String(route53.ChangeActionUpsert),
ResourceRecordSet: &route53.ResourceRecordSet{
Name: aws.String(dnsName),
// It creates an A record with the IP of the host running the agent
Type: aws.String(route53.RRTypeA),
ResourceRecords: []*route53.ResourceRecord{
{
Value: aws.String(localIP),
},
},
SetIdentifier: aws.String(dnsName),
// TTL=0 to avoid DNS caches
TTL: aws.Int64(defaultTTL),
Weight: aws.Int64(defaultWeight),
},
},
},
Comment: aws.String("Host A Record Created"),
},
HostedZoneId: aws.String(hostedZone.id),
}
_, err = r53.ChangeResourceRecordSets(params)
if err == nil {
log.Info("Record " + dnsName + " created, resolves to " + localIP)
}
return err
}
func isMatch(rrs *route53.ResourceRecordSet, name string, ip string) bool {
return rrs != nil &&
rrs.Type != nil &&
*rrs.Type == route53.RRTypeA &&
*rrs.Name == name &&
*rrs.ResourceRecords[0].Value == ip
}
func deleteARecord(serviceName string, localIP string, hostedZone *hostedZone) error {
sess, err := session.NewSession()
if err != nil {
return err
}
r53 := route53.New(sess)
// This API call creates a new DNS record for this host
dnsName := hostedZone.withServiceName(serviceName)
paramsList := &route53.ListResourceRecordSetsInput{
HostedZoneId: aws.String(hostedZone.id), // Required
MaxItems: aws.String("100"),
StartRecordName: aws.String(dnsName),
StartRecordType: aws.String(route53.RRTypeA),
}
more := true
var recordSetToDelete *route53.ResourceRecordSet
resp, err := r53.ListResourceRecordSets(paramsList)
for more && recordSetToDelete == nil && err == nil {
for _, rrset := range resp.ResourceRecordSets {
if isMatch(rrset, dnsName, localIP) {
recordSetToDelete = rrset
}
}
more = resp.IsTruncated != nil && *resp.IsTruncated
if more {
paramsList.StartRecordIdentifier = resp.NextRecordIdentifier
resp, err = r53.ListResourceRecordSets(paramsList)
}
}
if err != nil {
return err
}
if recordSetToDelete == nil {
log.Error("Route53 record doesn't exist")
return nil
}
// This API call deletes the DNS record for the service for this docker ID
params := &route53.ChangeResourceRecordSetsInput{
ChangeBatch: &route53.ChangeBatch{
Comment: aws.String("Service Discovery Created Record"),
Changes: []*route53.Change{
{
Action: aws.String(route53.ChangeActionDelete),
ResourceRecordSet: recordSetToDelete,
},
},
},
HostedZoneId: aws.String(hostedZone.id),
}
_, err = r53.ChangeResourceRecordSets(params)
if err == nil {
log.Info("Record " + dnsName + " deleted")
}
return err
}
func getHostedZone(id string) (*hostedZone, error) {
sess, err := session.NewSession()
if err != nil {
return nil, err
}
r53 := route53.New(sess)
params := &route53.GetHostedZoneInput{
Id: aws.String(id),
}
hz, err := r53.GetHostedZone(params)
if err != nil {
return nil, err
}
return &hostedZone{
id: id,
name: aws.StringValue(hz.HostedZone.Name),
}, nil
}
func main() {
var hostedZoneId = flag.String("hostedZoneId", "", "hosted zone ID in which to register records")
flag.Parse()
if len(*hostedZoneId) == 0 {
logAndFailIfError(errors.New("hostedZoneId must be provided"))
}
hz, err := getHostedZone(*hostedZoneId)
if err != nil {
logAndFailIfError(err)
}
nWorkers := 5
wg := sync.WaitGroup{}
ctx, cancel := context.WithCancel(context.Background())
dockerClient, _ := docker.NewEnvClient()
eventChannel, errorChannel := getContainerEvents(dockerClient, ctx)
failureChannel := make(chan error, nWorkers)
quitChannel := mapErrorChannel(errorChannel, failureChannel)
startProcessor := createProcessor(func(e events.Message) error {
log.Info("Processing container start")
container, err := dockerClient.ContainerInspect(context.Background(), e.ID)
if err != nil {
return err
}
serviceName, ok := getLabelValue(container, isServiceName)
if !ok {
log.Info("Unable to find service name label. Skipping container")
return nil
}
taskArn, ok := getLabelValue(container, isTaskArn)
if !ok {
log.Info("Unable to find task arn. Skipping container")
return nil
}
log.Infof("Container for Service: %v with Task ARN: %v", serviceName, taskArn)
ip, err := getContainerIp(container.ID)
if err != nil {
log.Error("Unable to find container IP")
return err
}
log.Infof("Container IP: %v", ip)
return createARecord(serviceName, ip, hz)
})
stopProcessor := createProcessor(func(e events.Message) error {
log.Info("Processing container stop")
container, err := dockerClient.ContainerInspect(context.Background(), e.ID)
if err != nil {
return err
}
serviceName, ok := getLabelValue(container, isServiceName)
if !ok {
log.Info("Unable to find service name label. Skipping container")
return nil
}
taskArn, ok := getLabelValue(container, isTaskArn)
if !ok {
log.Info("Unable to find task arn. Skipping container")
return nil
}
log.Infof("Container for Service: %v with Task ARN: %v", serviceName, taskArn)
ip, err := getContainerIp(container.ID)
if err != nil {
log.Error("Unable to find container IP")
return err
}
return deleteARecord(serviceName, ip, hz)
})
processors := map[string]processor{
containerStart: startProcessor,
containerStop: stopProcessor,
}
for i := 0; i < nWorkers; i++ {
wg.Add(1)
log.Infof("Creating Worker: %v", i)
worker := newWorker(i, eventChannel, quitChannel, failureChannel, processors, &wg)
worker.Start()
}
wg.Wait()
cancel()
log.Info("All workers exited. Shutting down")
}