forked from discordianfish/docker-spotter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spotter.go
207 lines (188 loc) · 4.63 KB
/
spotter.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
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"github.com/dotcloud/docker/utils"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/exec"
"strings"
"text/template"
)
const APIVERSION = "1.8"
var (
proto = flag.String("proto", "unix", "protocol to use")
addr = flag.String("addr", "/var/run/docker.sock", "address to connect to")
since = flag.String("since", "1", "watch for events since given value in seconds since epoch")
replay = flag.String("replay", "", "file to use to simulate/replay events from. Format = docker events")
debug = flag.Bool("v", false, "verbose logging")
hm hookMap
)
type Container struct {
Name string
ID string
Event utils.JSONMessage
}
// id, event, command
type hookMap map[string]map[string][][]*template.Template
func (hm hookMap) String() string { return "" }
func (hm hookMap) Set(str string) error {
parts := strings.Split(str, ":")
if len(parts) < 3 {
return fmt.Errorf("Couldn't parse %s", str)
}
id := parts[0]
events := strings.Split(parts[1], ",")
command, err := parseTemplates(parts[2:])
if err != nil {
return err
}
if hm[id] == nil {
hm[id] = make(map[string][][]*template.Template)
}
for _, event := range events {
log.Printf("= %s:%s:%s", id, event, str)
hm[id][event] = append(hm[id][event], command)
}
return nil
}
func parseTemplates(templates []string) ([]*template.Template, error) {
tl := []*template.Template{}
for i, t := range templates {
tmpl, err := template.New(fmt.Sprintf("t-%d", i)).Parse(t)
if err != nil {
return nil, err
}
tl = append(tl, tmpl)
}
return tl, nil
}
func getContainer(event utils.JSONMessage) (*Container, error) {
resp, err := request("/containers/" + event.ID + "/json")
if err != nil {
return nil, fmt.Errorf("Couldn't find container for event %#v: %s", event, err)
}
defer resp.Body.Close()
container := &Container{}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
container.Event = event
container.ID = event.ID
return container, json.Unmarshal(body, &container)
}
func request(path string) (*http.Response, error) {
req, err := http.NewRequest("GET", path, nil)
if err != nil {
return nil, err
}
conn, err := net.Dial(*proto, *addr)
if err != nil {
return nil, err
}
clientconn := httputil.NewClientConn(conn, nil)
resp, err := clientconn.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode < 200 || resp.StatusCode >= 400 {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if len(body) == 0 {
return nil, fmt.Errorf("Error: %s", http.StatusText(resp.StatusCode))
}
return nil, fmt.Errorf("HTTP %s: %s", http.StatusText(resp.StatusCode), body)
}
return resp, nil
}
func main() {
hm = hookMap{}
flag.Var(&hm, "e", "Hook map with template text executed in docker event (see JSONMessage) context, format: container:event[,event]:command[:arg1:arg2...]")
flag.Parse()
if len(hm) == 0 {
fmt.Fprintf(os.Stderr, "Please set hooks via -e flag\n")
flag.PrintDefaults()
os.Exit(1)
}
v := url.Values{}
v.Set("since", *since)
resp, err := request("/events?" + v.Encode())
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if *replay != "" {
file, err := os.Open(*replay)
if err != nil {
log.Fatalf("Couldn't replay from file %s: %s", *replay, err)
}
watch(file)
} else {
watch(resp.Body)
}
}
func watch(r io.Reader) {
dec := json.NewDecoder(r)
for {
event := utils.JSONMessage{}
if err := dec.Decode(&event); err != nil {
if err == io.EOF {
break
}
log.Fatalf("Couldn't decode message: %s", err)
}
if *debug {
log.Printf("< %s:%s", event.ID, event.Status)
}
container, err := getContainer(event)
if err != nil {
log.Printf("Warning: Couldn't get container %s: %s", event.ID, err)
continue
}
events := hm[event.ID]
if events == nil {
events = hm[strings.TrimLeft(container.Name, "/")]
if events == nil {
continue
}
}
commands := events[event.Status]
if len(commands) == 0 {
continue
}
for _, command := range commands {
if len(command) == 0 {
continue
}
args := []string{}
for _, template := range command {
buf := bytes.NewBufferString("")
if err := template.Execute(buf, container); err != nil {
log.Fatalf("Couldn't render template: %s", err)
}
args = append(args, buf.String())
}
command := exec.Command(args[0], args[1:]...)
log.Printf("> %s [ %v ]", command.Path, command.Args[1:])
out, err := command.CombinedOutput()
if err != nil {
log.Printf("! ERROR %s: %s", err, out)
continue
}
if out != nil {
log.Printf("- %s", out)
}
}
}
}