forked from gliderlabs/registrator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
registrator.go
162 lines (134 loc) · 4.12 KB
/
registrator.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
package main
import (
"errors"
"flag"
"log"
"os"
"time"
dockerapi "github.com/fsouza/go-dockerclient"
"github.com/gliderlabs/pkg/usage"
"github.com/dtmistry/registrator/bridge"
)
var Version string
var versionChecker = usage.NewChecker("registrator", Version)
var hostIp = flag.String("ip", "", "IP for ports mapped to the host")
var internal = flag.Bool("internal", false, "Use internal ports instead of published ones")
var refreshInterval = flag.Int("ttl-refresh", 0, "Frequency with which service TTLs are refreshed")
var refreshTtl = flag.Int("ttl", 0, "TTL for services (default is no expiry)")
var forceTags = flag.String("tags", "", "Append tags for all registered services")
var resyncInterval = flag.Int("resync", 0, "Frequency with which services are resynchronized")
var deregister = flag.String("deregister", "always", "Deregister exited services \"always\" or \"on-success\"")
var retryAttempts = flag.Int("retry-attempts", 0, "Max retry attempts to establish a connection with the backend. Use -1 for infinite retries")
var retryInterval = flag.Int("retry-interval", 2000, "Interval (in millisecond) between retry-attempts.")
var serviceName = flag.String("service", "", "Name of the service to register with the backend")
func getopt(name, def string) string {
if env := os.Getenv(name); env != "" {
return env
}
return def
}
func assert(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
if len(os.Args) == 2 && os.Args[1] == "--version" {
versionChecker.PrintVersion()
os.Exit(0)
}
log.Printf("Starting registrator %s ...", Version)
flag.Parse()
if *hostIp != "" {
log.Println("Forcing host IP to", *hostIp)
}
if (*refreshTtl == 0 && *refreshInterval > 0) || (*refreshTtl > 0 && *refreshInterval == 0) {
assert(errors.New("-ttl and -ttl-refresh must be specified together or not at all"))
} else if *refreshTtl > 0 && *refreshTtl <= *refreshInterval {
assert(errors.New("-ttl must be greater than -ttl-refresh"))
}
if *retryInterval <= 0 {
assert(errors.New("-retry-interval must be greater than 0"))
}
docker, err := dockerapi.NewClient(getopt("DOCKER_HOST", "unix:///tmp/docker.sock"))
assert(err)
if *deregister != "always" && *deregister != "on-success" {
assert(errors.New("-deregister must be \"always\" or \"on-success\""))
}
b, err := bridge.New(docker, flag.Arg(0), bridge.Config{
HostIp: *hostIp,
Internal: *internal,
ForceTags: *forceTags,
RefreshTtl: *refreshTtl,
RefreshInterval: *refreshInterval,
DeregisterCheck: *deregister,
Service: *serviceName,
})
assert(err)
attempt := 0
for *retryAttempts == -1 || attempt <= *retryAttempts {
log.Printf("Connecting to backend (%v/%v)", attempt, *retryAttempts)
err = b.Ping()
if err == nil {
break
}
if err != nil && attempt == *retryAttempts {
assert(err)
}
time.Sleep(time.Duration(*retryInterval) * time.Millisecond)
attempt++
}
// Start event listener before listing containers to avoid missing anything
events := make(chan *dockerapi.APIEvents)
assert(docker.AddEventListener(events))
if *serviceName != "" {
log.Printf("Listening for Docker events from %s ...", *serviceName)
} else {
log.Println("Listening for Docker events ...")
}
b.Sync(false)
quit := make(chan struct{})
// Start the TTL refresh timer
if *refreshInterval > 0 {
ticker := time.NewTicker(time.Duration(*refreshInterval) * time.Second)
go func() {
for {
select {
case <-ticker.C:
b.Refresh()
case <-quit:
ticker.Stop()
return
}
}
}()
}
// Start the resync timer if enabled
if *resyncInterval > 0 {
resyncTicker := time.NewTicker(time.Duration(*resyncInterval) * time.Second)
go func() {
for {
select {
case <-resyncTicker.C:
b.Sync(true)
case <-quit:
resyncTicker.Stop()
return
}
}
}()
}
// Process Docker events
for msg := range events {
switch msg.Status {
case "start":
go b.Add(msg.ID, msg.From)
case "die":
go b.RemoveOnExit(msg.ID, msg.From)
case "stop", "kill":
go b.Remove(msg.ID, msg.From)
}
}
close(quit)
log.Fatal("Docker event loop closed") // todo: reconnect?
}