-
Notifications
You must be signed in to change notification settings - Fork 0
/
docker_listener.go
110 lines (80 loc) · 2.37 KB
/
docker_listener.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
package main
import (
"fmt"
"strings"
docker "github.com/fsouza/go-dockerclient"
)
func (app *App) startDockerListener() {
fmt.Println("Starting docker events listener")
client, err := docker.NewClient("unix:///var/run/docker.sock")
if err != nil {
panic(err)
}
registerRunningContainers(app, client)
events := make(chan *docker.APIEvents)
err = client.AddEventListener(events)
if err != nil {
panic(err)
}
for event := range events {
if "start" == event.Action || "stop" == event.Action || "kill" == event.Action || "die" == event.Action {
domains := getDomains(client, event.ID)
if "start" == event.Action {
ip := getContainerIp(client, event.ID)
app.registerDomains(domains, ip)
app.emitter.Emit("container-start", domains, ip)
} else {
app.removeDomains(domains)
app.emitter.Emit("container-stop", domains)
}
app.emitter.Emit("domains-updated")
}
}
}
func registerRunningContainers(app *App, client *docker.Client) {
fmt.Println("Registering running containers")
containers, err := client.ListContainers(docker.ListContainersOptions{})
if err != nil {
panic(err)
}
for _, container := range containers {
domains := getDomains(client, container.ID)
ip := getContainerIp(client, container.ID)
app.registerDomains(domains, ip)
}
app.emitter.Emit("domains-updated")
}
func getDomains(client *docker.Client, ID string) []string {
domains := []string{}
container, _ := client.InspectContainer(ID)
if "" != container.Config.Domainname {
domains = append(domains, container.Config.Hostname+"."+container.Config.Domainname)
}
domains = append(domains, container.Name[1:]+".docker")
envDomains := getDomainsFromEnv(container.Config.Env)
for _, domain := range envDomains {
domains = append(domains, domain)
}
return domains
}
func getContainerIp(client *docker.Client, ID string) string {
container, _ := client.InspectContainer(ID)
return container.NetworkSettings.IPAddress
}
func getDomainsFromEnv(args []string) []string {
domains := []string{}
for _, arg := range args {
env := strings.Split(arg, "=")
if "DOMAIN_NAME" == env[0] || "DNSDOCK_ALIAS" == env[0] {
if strings.Contains(env[1], ",") {
splited := strings.Split(env[1], ",")
for _, domain := range splited {
domains = append(domains, domain)
}
} else {
domains = append(domains, env[1])
}
}
}
return domains
}