forked from nginx-proxy/docker-gen
/
docker-gen.go
456 lines (394 loc) · 10.6 KB
/
docker-gen.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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
package main
import (
"errors"
"flag"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
"github.com/BurntSushi/toml"
docker "github.com/fsouza/go-dockerclient"
)
type stringslice []string
var (
buildVersion string
version bool
watch bool
notifyCmd string
notifySigHUPContainerID string
onlyExposed bool
onlyPublished bool
configFiles stringslice
configs ConfigFile
interval int
endpoint string
tlsCert string
tlsKey string
tlsCaCert string
tlsVerify bool
tlsCertPath string
wg sync.WaitGroup
)
type Event struct {
ContainerID string `json:"id"`
Status string `json:"status"`
Image string `json:"from"`
}
type Address struct {
IP string
Port string
HostPort string
Proto string
HostIP string
}
type Volume struct {
Path string
HostPath string
ReadWrite bool
}
type RuntimeContainer struct {
ID string
Addresses []Address
Gateway string
Name string
Hostname string
Image DockerImage
Env map[string]string
Volumes map[string]Volume
Node SwarmNode
Labels map[string]string
IP string
}
type DockerImage struct {
Registry string
Repository string
Tag string
}
type SwarmNode struct {
ID string
Name string
Address Address
}
func (strings *stringslice) String() string {
return "[]"
}
func (strings *stringslice) Set(value string) error {
// TODO: Throw an error for duplicate `dest`
*strings = append(*strings, value)
return nil
}
func (i *DockerImage) String() string {
ret := i.Repository
if i.Registry != "" {
ret = i.Registry + "/" + i.Repository
}
if i.Tag != "" {
ret = ret + ":" + i.Tag
}
return ret
}
type Config struct {
Template string
Dest string
Watch bool
NotifyCmd string
NotifyContainers map[string]docker.Signal
OnlyExposed bool
OnlyPublished bool
Interval int
}
type ConfigFile struct {
Config []Config
}
type Context []*RuntimeContainer
func (c *Context) Env() map[string]string {
return splitKeyValueSlice(os.Environ())
}
func (c *ConfigFile) filterWatches() ConfigFile {
configWithWatches := []Config{}
for _, config := range c.Config {
if config.Watch {
configWithWatches = append(configWithWatches, config)
}
}
return ConfigFile{
Config: configWithWatches,
}
}
func (r *RuntimeContainer) Equals(o RuntimeContainer) bool {
return r.ID == o.ID && r.Image == o.Image
}
func (r *RuntimeContainer) PublishedAddresses() []Address {
mapped := []Address{}
for _, address := range r.Addresses {
if address.HostPort != "" {
mapped = append(mapped, address)
}
}
return mapped
}
func usage() {
println(`Usage: docker-gen [options] template [dest]
Generate files from docker container meta-data
Options:`)
flag.PrintDefaults()
println(`
Arguments:
template - path to a template to generate
dest - path to a write the template. If not specfied, STDOUT is used`)
println(`
Environment Variables:
DOCKER_HOST - default value for -endpoint
DOCKER_CERT_PATH - directory path containing key.pem, cert.pm and ca.pem
DOCKER_TLS_VERIFY - enable client TLS verification
`)
}
func tlsEnabled() bool {
for _, v := range []string{tlsCert, tlsCaCert, tlsKey} {
if e, err := pathExists(v); e && err == nil {
return true
}
}
return false
}
func NewDockerClient(endpoint string) (*docker.Client, error) {
if strings.HasPrefix(endpoint, "unix:") {
return docker.NewClient(endpoint)
} else if tlsVerify || tlsEnabled() {
if tlsVerify {
if e, err := pathExists(tlsCaCert); !e || err != nil {
return nil, errors.New("TLS verification was requested, but CA cert does not exist")
}
}
return docker.NewTLSClient(endpoint, tlsCert, tlsKey, tlsCaCert)
}
return docker.NewClient(endpoint)
}
func generateFromContainers(client *docker.Client) {
containers, err := getContainers(client)
if err != nil {
log.Printf("error listing containers: %s\n", err)
return
}
for _, config := range configs.Config {
changed := generateFile(config, containers)
if !changed {
log.Printf("Contents of %s did not change. Skipping notification '%s'", config.Dest, config.NotifyCmd)
continue
}
runNotifyCmd(config)
sendSignalToContainer(client, config)
}
}
func runNotifyCmd(config Config) {
if config.NotifyCmd == "" {
return
}
log.Printf("Running '%s'", config.NotifyCmd)
cmd := exec.Command("/bin/sh", "-c", config.NotifyCmd)
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("Error running notify command: %s, %s\n", config.NotifyCmd, err)
log.Print(string(out))
}
}
func sendSignalToContainer(client *docker.Client, config Config) {
if len(config.NotifyContainers) < 1 {
return
}
for container, signal := range config.NotifyContainers {
log.Printf("Sending container '%s' signal '%v'", container, signal)
killOpts := docker.KillContainerOptions{
ID: container,
Signal: signal,
}
if err := client.KillContainer(killOpts); err != nil {
log.Printf("Error sending signal to container: %s", err)
}
}
}
func loadConfig(file string) error {
_, err := toml.DecodeFile(file, &configs)
if err != nil {
return err
}
return nil
}
func generateAtInterval(client *docker.Client, configs ConfigFile) {
for _, config := range configs.Config {
if config.Interval == 0 {
continue
}
log.Printf("Generating every %d seconds", config.Interval)
wg.Add(1)
ticker := time.NewTicker(time.Duration(config.Interval) * time.Second)
quit := make(chan struct{})
configCopy := config
go func() {
defer wg.Done()
for {
select {
case <-ticker.C:
containers, err := getContainers(client)
if err != nil {
log.Printf("Error listing containers: %s\n", err)
continue
}
// ignore changed return value. always run notify command
generateFile(configCopy, containers)
runNotifyCmd(configCopy)
sendSignalToContainer(client, configCopy)
case <-quit:
ticker.Stop()
return
}
}
}()
}
}
func generateFromEvents(client *docker.Client, configs ConfigFile) {
configs = configs.filterWatches()
if len(configs.Config) == 0 {
return
}
wg.Add(1)
defer wg.Done()
for {
if client == nil {
var err error
endpoint, err := getEndpoint()
if err != nil {
log.Printf("Bad endpoint: %s", err)
time.Sleep(10 * time.Second)
continue
}
client, err = NewDockerClient(endpoint)
if err != nil {
log.Printf("Unable to connect to docker daemon: %s", err)
time.Sleep(10 * time.Second)
continue
}
generateFromContainers(client)
}
eventChan := make(chan *docker.APIEvents, 100)
defer close(eventChan)
watching := false
for {
if client == nil {
break
}
err := client.Ping()
if err != nil {
log.Printf("Unable to ping docker daemon: %s", err)
if watching {
client.RemoveEventListener(eventChan)
watching = false
client = nil
}
time.Sleep(10 * time.Second)
break
}
if !watching {
err = client.AddEventListener(eventChan)
if err != nil && err != docker.ErrListenerAlreadyExists {
log.Printf("Error registering docker event listener: %s", err)
time.Sleep(10 * time.Second)
continue
}
watching = true
log.Println("Watching docker events")
}
select {
case event := <-eventChan:
if event == nil {
if watching {
client.RemoveEventListener(eventChan)
watching = false
client = nil
}
break
}
if event.Status == "start" || event.Status == "stop" || event.Status == "die" {
log.Printf("Received event %s for container %s", event.Status, event.ID[:12])
generateFromContainers(client)
}
case <-time.After(10 * time.Second):
// check for docker liveness
}
}
}
}
func initFlags() {
certPath := filepath.Join(os.Getenv("DOCKER_CERT_PATH"))
if certPath == "" {
certPath = filepath.Join(os.Getenv("HOME"), ".docker")
}
flag.BoolVar(&version, "version", false, "show version")
flag.BoolVar(&watch, "watch", false, "watch for container changes")
flag.BoolVar(&onlyExposed, "only-exposed", false, "only include containers with exposed ports")
flag.BoolVar(&onlyPublished, "only-published", false,
"only include containers with published ports (implies -only-exposed)")
flag.StringVar(¬ifyCmd, "notify", "", "run command after template is regenerated (e.g `restart xyz`)")
flag.StringVar(¬ifySigHUPContainerID, "notify-sighup", "",
"send HUP signal to container. Equivalent to `docker kill -s HUP container-ID`")
flag.Var(&configFiles, "config", "config files with template directives. Config files will be merged if this option is specified multiple times.")
flag.IntVar(&interval, "interval", 0, "notify command interval (secs)")
flag.StringVar(&endpoint, "endpoint", "", "docker api endpoint (tcp|unix://..). Default unix:///var/run/docker.sock")
flag.StringVar(&tlsCert, "tlscert", filepath.Join(certPath, "cert.pem"), "path to TLS client certificate file")
flag.StringVar(&tlsKey, "tlskey", filepath.Join(certPath, "key.pem"), "path to TLS client key file")
flag.StringVar(&tlsCaCert, "tlscacert", filepath.Join(certPath, "ca.pem"), "path to TLS CA certificate file")
flag.BoolVar(&tlsVerify, "tlsverify", os.Getenv("DOCKER_TLS_VERIFY") != "", "verify docker daemon's TLS certicate")
flag.Usage = usage
flag.Parse()
}
func main() {
initFlags()
if version {
fmt.Println(buildVersion)
return
}
if flag.NArg() < 1 && len(configFiles) == 0 {
usage()
os.Exit(1)
}
if len(configFiles) > 0 {
for _, configFile := range configFiles {
err := loadConfig(configFile)
if err != nil {
log.Fatalf("error loading config %s: %s\n", configFile, err)
}
}
} else {
config := Config{
Template: flag.Arg(0),
Dest: flag.Arg(1),
Watch: watch,
NotifyCmd: notifyCmd,
NotifyContainers: make(map[string]docker.Signal),
OnlyExposed: onlyExposed,
OnlyPublished: onlyPublished,
Interval: interval,
}
if notifySigHUPContainerID != "" {
config.NotifyContainers[notifySigHUPContainerID] = docker.SIGHUP
}
configs = ConfigFile{
Config: []Config{config}}
}
endpoint, err := getEndpoint()
if err != nil {
log.Fatalf("Bad endpoint: %s", err)
}
client, err := NewDockerClient(endpoint)
if err != nil {
log.Fatalf("Unable to create docker client: %s", err)
}
generateFromContainers(client)
generateAtInterval(client, configs)
generateFromEvents(client, configs)
wg.Wait()
}