-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpublisher.go
More file actions
298 lines (276 loc) · 7.96 KB
/
publisher.go
File metadata and controls
298 lines (276 loc) · 7.96 KB
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
package server
import (
"fmt"
"log"
"net"
"net/http"
"regexp"
"strconv"
"sync"
"time"
"github.com/coreos/go-etcd/etcd"
"github.com/fsouza/go-dockerclient"
)
const (
appNameRegex string = `([a-z0-9-]+)_v([1-9][0-9]*).(cmd|web).([1-9][0-9])*`
)
// Server is the main entrypoint for a publisher. It listens on a docker client for events
// and publishes their host:port to the etcd client.
type Server struct {
DockerClient *docker.Client
EtcdClient *etcd.Client
host string
logLevel string
}
var safeMap = struct {
sync.RWMutex
data map[string]string
}{data: make(map[string]string)}
// New returns a new instance of Server.
func New(dockerClient *docker.Client, etcdClient *etcd.Client, host, logLevel string) *Server {
return &Server{
DockerClient: dockerClient,
EtcdClient: etcdClient,
host: host,
logLevel: logLevel,
}
}
// Listen adds an event listener to the docker client and publishes containers that were started.
func (s *Server) Listen(ttl time.Duration) {
listener := make(chan *docker.APIEvents)
// TODO: figure out why we need to sleep for 10 milliseconds
// https://github.com/fsouza/go-dockerclient/blob/0236a64c6c4bd563ec277ba00e370cc753e1677c/event_test.go#L43
defer func() { time.Sleep(10 * time.Millisecond); s.DockerClient.RemoveEventListener(listener) }()
if err := s.DockerClient.AddEventListener(listener); err != nil {
log.Fatal(err)
}
for {
select {
case event := <-listener:
if event.Status == "start" {
container, err := s.getContainer(event.ID)
if err != nil {
log.Println(err)
continue
}
s.publishContainer(container, ttl)
} else if event.Status == "stop" {
s.removeContainer(event.ID)
}
}
}
}
// Poll lists all containers from the docker client every time the TTL comes up and publishes them to etcd
func (s *Server) Poll(ttl time.Duration) {
containers, err := s.DockerClient.ListContainers(docker.ListContainersOptions{})
if err != nil {
log.Fatal(err)
}
for _, container := range containers {
// send container to channel for processing
s.publishContainer(&container, ttl)
}
}
// getContainer retrieves a container from the docker client based on id
func (s *Server) getContainer(id string) (*docker.APIContainers, error) {
containers, err := s.DockerClient.ListContainers(docker.ListContainersOptions{})
if err != nil {
return nil, err
}
for _, container := range containers {
// send container to channel for processing
if container.ID == id {
return &container, nil
}
}
return nil, fmt.Errorf("could not find container with id %v", id)
}
// publishContainer publishes the docker container to etcd.
func (s *Server) publishContainer(container *docker.APIContainers, ttl time.Duration) {
r := regexp.MustCompile(appNameRegex)
for _, name := range container.Names {
// HACK: remove slash from container name
// see https://github.com/docker/docker/issues/7519
containerName := name[1:]
match := r.FindStringSubmatch(containerName)
if match == nil {
continue
}
appName := match[1]
appPath := fmt.Sprintf("%s/%s", appName, containerName)
keyPath := fmt.Sprintf("/deis/services/%s", appPath)
for _, p := range container.Ports {
var delay int
var timeout int
var err error
// lowest port wins (docker sorts the ports)
// TODO (bacongobbler): support multiple exposed ports
port := strconv.Itoa(int(p.PublicPort))
hostAndPort := s.host + ":" + port
if s.IsPublishableApp(containerName) && s.IsPortOpen(hostAndPort) {
configKey := fmt.Sprintf("/deis/config/%s/", appName)
// check if the user specified a healthcheck URL
healthcheckURL := s.getEtcd(configKey + "healthcheck_url")
initialDelay := s.getEtcd(configKey + "healthcheck_initial_delay")
if initialDelay != "" {
delay, err = strconv.Atoi(initialDelay)
if err != nil {
log.Println(err)
delay = 0
}
} else {
delay = 0
}
healthcheckTimeout := s.getEtcd(configKey + "healthcheck_timeout")
if healthcheckTimeout != "" {
timeout, err = strconv.Atoi(healthcheckTimeout)
if err != nil {
log.Println(err)
timeout = 1
}
} else {
timeout = 1
}
if healthcheckURL != "" {
if !s.HealthCheckOK("http://"+hostAndPort+healthcheckURL, delay, timeout) {
continue
}
}
s.setEtcd(keyPath, hostAndPort, uint64(ttl.Seconds()))
safeMap.Lock()
safeMap.data[container.ID] = appPath
safeMap.Unlock()
}
break
}
}
}
// removeContainer remove a container published by this component
func (s *Server) removeContainer(event string) {
safeMap.RLock()
appPath := safeMap.data[event]
safeMap.RUnlock()
if appPath != "" {
keyPath := fmt.Sprintf("/deis/services/%s", appPath)
log.Printf("stopped %s\n", keyPath)
s.removeEtcd(keyPath, false)
}
}
// IsPublishableApp determines if the application should be published to etcd.
func (s *Server) IsPublishableApp(name string) bool {
r := regexp.MustCompile(appNameRegex)
match := r.FindStringSubmatch(name)
if match == nil {
return false
}
appName := match[1]
version, err := strconv.Atoi(match[2])
if err != nil {
log.Println(err)
return false
}
if version >= latestRunningVersion(s.EtcdClient, appName) {
return true
}
return false
}
// IsPortOpen checks if the given port is accepting tcp connections
func (s *Server) IsPortOpen(hostAndPort string) bool {
portOpen := false
conn, err := net.Dial("tcp", hostAndPort)
if err == nil {
portOpen = true
defer conn.Close()
}
return portOpen
}
func (s *Server) HealthCheckOK(url string, delay, timeout int) bool {
// sleep for the initial delay
time.Sleep(time.Duration(delay) * time.Second)
client := http.Client{
Timeout: time.Duration(timeout) * time.Second,
}
resp, err := client.Get(url)
if err != nil {
log.Printf("an error occurred while performing a health check at %s (%v)\n", url, err)
return false
}
if resp.StatusCode != http.StatusOK {
log.Printf("healthcheck failed for %s (expected %d, got %d)\n", url, http.StatusOK, resp.StatusCode)
}
return resp.StatusCode == http.StatusOK
}
// latestRunningVersion retrieves the highest version of the application published
// to etcd. If no app has been published, returns 0.
func latestRunningVersion(client *etcd.Client, appName string) int {
r := regexp.MustCompile(appNameRegex)
if client == nil {
// FIXME: client should only be nil during tests. This should be properly refactored.
if appName == "ceci-nest-pas-une-app" {
return 3
}
return 0
}
resp, err := client.Get(fmt.Sprintf("/deis/services/%s", appName), false, true)
if err != nil {
// no app has been published here (key not found) or there was an error
return 0
}
var versions []int
for _, node := range resp.Node.Nodes {
match := r.FindStringSubmatch(node.Key)
// account for keys that may not be an application container
if match == nil {
continue
}
version, err := strconv.Atoi(match[2])
if err != nil {
log.Println(err)
return 0
}
versions = append(versions, version)
}
return max(versions)
}
// max returns the maximum value in n
func max(n []int) int {
val := 0
for _, i := range n {
if i > val {
val = i
}
}
return val
}
// getEtcd retrieves the etcd key's value. Returns an empty string if the key was not found.
func (s *Server) getEtcd(key string) string {
if s.logLevel == "debug" {
log.Println("get", key)
}
resp, err := s.EtcdClient.Get(key, false, false)
if err != nil {
return ""
}
if resp != nil && resp.Node != nil {
return resp.Node.Value
}
return ""
}
// setEtcd sets the corresponding etcd key with the value and ttl
func (s *Server) setEtcd(key, value string, ttl uint64) {
if _, err := s.EtcdClient.Set(key, value, ttl); err != nil {
log.Println(err)
}
if s.logLevel == "debug" {
log.Println("set", key, "->", value)
}
}
// removeEtcd removes the corresponding etcd key
func (s *Server) removeEtcd(key string, recursive bool) {
if _, err := s.EtcdClient.Delete(key, recursive); err != nil {
log.Println(err)
}
if s.logLevel == "debug" {
log.Println("del", key)
}
}