forked from waj/dockerdev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
monitor.go
59 lines (48 loc) · 1.4 KB
/
monitor.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
package main
import (
"log"
"os"
docker "github.com/fsouza/go-dockerclient"
)
func main() {
cli, err := docker.NewClientFromEnv()
if err != nil {
log.Fatal(err)
}
listener := make(chan *docker.APIEvents, 10)
filters := map[string][]string{
"type": {"container"},
"event": {"create"},
}
opts := docker.EventsOptions{Filters: filters}
err = cli.AddEventListenerWithOptions(opts, listener)
if err != nil {
log.Fatal(err)
}
domain := os.Getenv("DOMAIN_TLD")
log.Println("Listening events")
for {
event := <-listener
containerName := event.Actor.Attributes["name"]
log.Printf("New container (%s) created\n", containerName)
project, hasProject := event.Actor.Attributes["com.docker.compose.project"]
service, hasService := event.Actor.Attributes["com.docker.compose.service"]
oneoff := event.Actor.Attributes["com.docker.compose.oneoff"]
if hasProject && hasService {
config := docker.NetworkConnectionOptions{Container: event.Actor.ID}
if oneoff == "False" {
alias := service + "." + project + "." + domain
log.Printf("Attaching %s to the shared network with alias %s\n", containerName, alias)
config.EndpointConfig = &docker.EndpointConfig{
Aliases: []string{alias},
}
} else {
log.Printf("Attaching %s to the shared network\n", event.Actor.ID)
}
err := cli.ConnectNetwork("shared", config)
if err != nil {
log.Fatal(err)
}
}
}
}