-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathspotter.go
270 lines (239 loc) · 5.95 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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/exec"
"strings"
"text/template"
"github.com/docker/docker/pkg/jsonmessage"
)
const APIVERSION = "1.23"
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 ContainerConfig struct {
Env []string
}
type Container struct {
Name string
ID string
Config ContainerConfig
Event jsonmessage.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 jsonmessage.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)
}
// leading slash is expected
func request(path string) (*http.Response, error) {
apiPath := fmt.Sprintf("/v%s%s", APIVERSION, path)
if *debug {
fmt.Printf("making API request: GET %s\n", apiPath)
}
req, err := http.NewRequest("GET", apiPath, 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 := jsonmessage.JSONMessage{}
if err := dec.Decode(&event); err != nil {
if err == io.EOF {
break
}
log.Fatalf("Couldn't decode message: %s", err)
}
if event.ID == "" {
if *debug {
log.Printf("skipping non-container message")
}
continue
}
if *debug {
log.Printf("< %s:%s", event.ID, event.Status)
}
if event.Status == "delete" || event.Status == "destroy" {
// we can't get the container if it is destroyed. Trying to do so just
// produces noise.
if *debug {
log.Printf("Skipping %s event for container %s", event.Status, event.ID)
}
continue
}
container, err := getContainer(event)
if err != nil {
log.Printf("Warning: Couldn't get container %s: %s", event.ID, err)
continue
}
if *debug {
log.Printf("Got container: %+v", container)
}
events := hm[event.ID]
if events == nil {
events = GetEvents(hm, container)
if events == nil {
events = hm["*"]
}
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)
}
}
}
}
func GetEvents(hooks hookMap, container *Container) map[string][][]*template.Template {
name := strings.TrimLeft(container.Name, "/")
for key, value := range hooks {
//if key is key/value pair search it in Env
if strings.Contains(key, "=") && contains(container.Config.Env, key) {
return value
//looks like key is container's name
} else if strings.HasPrefix(name, key) {
return value
}
}
return nil
}
//Check if source array contains target string
func contains(source []string, target string) bool {
for _, value := range source {
if value == target {
return true
}
}
return false
}