-
Notifications
You must be signed in to change notification settings - Fork 20
/
spy.go
70 lines (57 loc) · 1.63 KB
/
spy.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
package main
import (
dockerApi "github.com/fsouza/go-dockerclient"
"github.com/miekg/dns"
"log"
"regexp"
)
type Spy struct {
docker *dockerApi.Client
dns *DNS
}
func (s *Spy) Watch() {
s.registerRunningContainers()
events := make(chan *dockerApi.APIEvents)
s.docker.AddEventListener(events)
go s.readEventStream(events)
}
func (s *Spy) registerRunningContainers() {
containers, err := s.docker.ListContainers(dockerApi.ListContainersOptions{})
if err != nil {
log.Fatalf("Unable to register running containers: %v", err)
}
for _, listing := range containers {
s.mutateContainerInCache(listing.ID, listing.Status)
}
}
func (s *Spy) readEventStream(events chan *dockerApi.APIEvents) {
for msg := range events {
s.mutateContainerInCache(msg.ID, msg.Status)
}
}
func (s *Spy) mutateContainerInCache(id string, status string) {
container, err := s.docker.InspectContainer(id)
if err != nil {
log.Printf("Unable to inspect container %s, skipping", id)
return
}
name := container.Config.Hostname + "." + container.Config.Domainname + "."
var running = regexp.MustCompile("start|^Up.*$")
var stopping = regexp.MustCompile("die")
switch {
case running.MatchString(status):
log.Printf("Adding record for %v", name)
arpa, err := dns.ReverseAddr(container.NetworkSettings.IPAddress)
if err != nil {
log.Printf("Unable to create ARPA address. Reverse DNS lookup will be unavailable for this container.")
}
s.dns.cache.Set(name, &Record{
container.NetworkSettings.IPAddress,
arpa,
name,
})
case stopping.MatchString(status):
log.Printf("Removing record for %v", name)
s.dns.cache.Remove(name)
}
}