-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpublisher.go
More file actions
173 lines (161 loc) · 4.65 KB
/
publisher.go
File metadata and controls
173 lines (161 loc) · 4.65 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
package server
import (
"errors"
"fmt"
"log"
"os"
"regexp"
"strconv"
"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
}
// 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)
}
}
}
}
// 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, errors.New("could not find container")
}
// publishContainer publishes the docker container to etcd.
func (s *Server) publishContainer(container *docker.APIContainers, ttl time.Duration) {
r := regexp.MustCompile(appNameRegex)
host := os.Getenv("HOST")
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]
keyPath := fmt.Sprintf("/deis/services/%s/%s", appName, containerName)
for _, p := range container.Ports {
port := strconv.Itoa(int(p.PublicPort))
if s.IsPublishableApp(containerName) {
s.setEtcd(keyPath, host+":"+port, uint64(ttl.Seconds()))
}
// TODO: support multiple exposed ports
break
}
}
}
// 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
} else {
return false
}
}
// 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
}
// 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)
}
log.Println("set", key, "->", value)
}