-
Notifications
You must be signed in to change notification settings - Fork 8
/
dockerhook.go
136 lines (120 loc) · 3.04 KB
/
dockerhook.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
package main
import (
"log"
"os"
"flag"
"strings"
"fmt"
"path/filepath"
"os/exec"
"syscall"
"bytes"
"encoding/json"
"github.com/flynn/go-shlex"
dockerapi "github.com/fsouza/go-dockerclient"
)
var debug = flag.Bool("d", false, "debug mode displays handler output")
var shell = flag.Bool("s", false, "run handler via SHELL")
var skipInspect = map[string]bool {
"destroy": true,
"untag": true,
"delete": true,
}
func init() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %v [options] <hook-handler>\n\n", os.Args[0])
flag.PrintDefaults()
}
}
func assert(err error) {
if err != nil {
log.Fatal("fatal: ", err)
}
}
func getopt(name, def string) string {
if env := os.Getenv(name); env != "" {
return env
}
return def
}
func exitStatus(err error) (int, error) {
if err != nil {
if exiterr, ok := err.(*exec.ExitError); ok {
// There is no platform independent way to retrieve
// the exit code, but the following will work on Unix
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
return int(status.ExitStatus()), nil
}
}
return 0, err
}
return 0, nil
}
func inspect(docker *dockerapi.Client, id string) *bytes.Buffer {
var b bytes.Buffer
container, err := docker.InspectContainer(id)
if err != nil {
log.Println("warn: unable to inspect container:", id[:12], err)
return &b
}
data, err := json.Marshal(container)
if err != nil {
log.Println("warn: unable to marshal container data:", id[:12], err)
return &b
}
b.Write(data)
return &b
}
func trigger(hook []string, event, id string, docker *dockerapi.Client) {
log.Println("info: trigger:", id[:12], event)
hook = append(hook, event, id)
var cmd *exec.Cmd
if *shell && os.Getenv("SHELL") != "" {
cmd = exec.Command(os.Getenv("SHELL"), "-c", strings.Join(hook, " "))
} else {
cmd = exec.Command(hook[0], hook[1:]...)
}
if !skipInspect[event] {
cmd.Stdin = inspect(docker, id)
}
if *debug {
cmd.Stdout = os.Stdout // TODO: wrap in log output
}
cmd.Stderr = os.Stderr // TODO: wrap in log output
status, err := exitStatus(cmd.Run())
if err != nil {
log.Println("error:", event, status, err)
}
}
func main() {
flag.Parse()
if flag.NArg() < 1 {
flag.Usage()
os.Exit(64)
}
hook, err := shlex.Split(flag.Arg(0))
if err != nil {
log.Fatalln("fatal: unable to parse handler command:", err)
}
hook[0], err = filepath.Abs(hook[0])
if err != nil {
log.Fatalln("fatal: invalid handler executable path:", err)
}
if os.Getenv("DOCKER_HOST") == "" {
assert(os.Setenv("DOCKER_HOST", "unix:///var/run/docker.sock"))
}
docker, err := dockerapi.NewClientFromEnv()
assert(err)
containers, err := docker.ListContainers(dockerapi.ListContainersOptions{})
assert(err)
for _, listing := range containers {
trigger(hook, "exists", listing.ID, docker)
}
events := make(chan *dockerapi.APIEvents)
assert(docker.AddEventListener(events))
log.Println("info: listening for Docker events...")
for msg := range events {
go trigger(hook, msg.Status, msg.ID, docker)
}
log.Fatal("fatal: docker event loop closed") // todo: reconnect?
}