This repository has been archived by the owner on Aug 21, 2019. It is now read-only.
forked from blalor/docker-hosts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
69 lines (53 loc) · 1.53 KB
/
main.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
package main
import (
"os"
"log"
flags "github.com/jessevdk/go-flags"
dockerapi "github.com/fsouza/go-dockerclient"
)
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("docker-hosts: ", err)
}
}
type Options struct {
DomainName string `short:"d" long:"domain-name" description:"domain to append"`
File struct {
Filename string
} `positional-args:"true" required:"true" description:"the hosts file to write"`
}
func main() {
var opts Options
_, err := flags.Parse(&opts)
if err != nil {
os.Exit(1)
}
docker, err := dockerapi.NewClient(getopt("DOCKER_HOST", "unix:///var/run/docker.sock"))
assert(err)
hosts := NewHosts(docker, opts.File.Filename, opts.DomainName)
// set up to handle events early, so we don't miss anything while doing the
// initial population
events := make(chan *dockerapi.APIEvents)
assert(docker.AddEventListener(events))
containers, err := docker.ListContainers(dockerapi.ListContainersOptions{})
assert(err)
for _, listing := range containers {
go hosts.Add(listing.ID)
}
log.Println("docker-hosts: Listening for Docker events...")
for msg := range events {
switch msg.Status {
case "start":
go hosts.Add(msg.ID)
case "die":
go hosts.Remove(msg.ID)
}
}
log.Fatal("docker-hosts: docker event loop closed") // todo: reconnect?
}