forked from dokku/dokku-event-listener
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
274 lines (234 loc) · 5.83 KB
/
main.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
271
272
273
274
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httputil"
"os"
"os/exec"
"strings"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
type Config struct {
Labels map[string]string
}
type HostConfig struct {
RestartPolicy RestartPolicy
}
type NetworkSettings struct {
IpAddress string
}
type RestartPolicy struct {
Name string
MaximumRetryCount int
}
type Container struct {
Config Config
Event jsonmessage.JSONMessage
HostConfig HostConfig
ID string
Name string
NetworkSettings NetworkSettings
RestartCount int
}
type containerMap map[string]*Container
// ShellCmd represents a shell command to be run
type ShellCmd struct {
Env map[string]string
Command *exec.Cmd
CommandString string
Args []string
ShowOutput bool
Error error
}
const APIVERSION = "1.40"
const DEBUG = true
var cm containerMap
// NewShellCmd returns a new ShellCmd struct
func NewShellCmd(command string) *ShellCmd {
items := strings.Split(command, " ")
cmd := items[0]
args := items[1:]
return &ShellCmd{
Command: exec.Command(cmd, args...),
CommandString: command,
Args: args,
ShowOutput: true,
}
}
// Execute is a lightweight wrapper around exec.Command
func (sc *ShellCmd) Execute() bool {
env := os.Environ()
for k, v := range sc.Env {
env = append(env, fmt.Sprintf("%s=%s", k, v))
}
sc.Command.Env = env
if sc.ShowOutput {
sc.Command.Stdout = os.Stdout
sc.Command.Stderr = os.Stderr
}
if err := sc.Command.Run(); err != nil {
sc.Error = err
return false
}
return true
}
func request(path string) (*http.Response, error) {
apiPath := fmt.Sprintf("/v%s%s", APIVERSION, path)
req, err := http.NewRequest("GET", apiPath, nil)
if err != nil {
return nil, err
}
conn, err := net.Dial("unix", "/var/run/docker.sock")
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 runCommand(args ...string) error {
cmd := NewShellCmd(strings.Join(args, " "))
cmd.ShowOutput = false
if cmd.Execute() {
return nil
}
return cmd.Error
}
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)
}
func watch(r io.Reader) {
cm = containerMap{}
dec := json.NewDecoder(r)
for {
event := jsonmessage.JSONMessage{}
if err := dec.Decode(&event); err != nil {
if err == io.EOF {
break
}
log.Fatal().
Str("error", err.Error()).
Msg("bad_message")
}
// skip non-container messages
if event.ID == "" {
continue
}
// handle removing deleted/destroyed containers
if event.Status == "delete" || event.Status == "destroy" {
if _, ok := cm[event.ID]; ok {
log.Info().
Str("container_id", event.ID[0:9]).
Msg("dead_container")
delete(cm, event.ID)
}
continue
}
container, err := getContainer(event)
if err != nil {
continue
}
appName, _ := container.Config.Labels["com.dokku.app-name"]
if appName == "" {
continue
}
if event.Status == "die" {
if container == nil {
continue
}
if container.HostConfig.RestartPolicy.Name == "no" {
continue
}
if container.RestartCount == container.HostConfig.RestartPolicy.MaximumRetryCount {
log.Info().
Str("container_id", event.ID[0:9]).
Str("app", appName).
Str("restart_policy", container.HostConfig.RestartPolicy.Name).
Int("restart_count", container.RestartCount).
Int("max_restart_count", container.HostConfig.RestartPolicy.MaximumRetryCount).
Msg("rebuilding_app")
if err := runCommand("dokku", "--quiet", "ps:rebuild", appName); err != nil {
log.Warn().
Str("container_id", event.ID[0:9]).
Str("app", appName).
Str("error", err.Error()).
Msg("rebuild_failed")
}
}
}
// skip non-start events
if event.Status != "start" && event.Status != "restart" {
continue
}
if _, ok := cm[event.ID]; !ok {
cm[event.ID] = container
log.Info().
Str("container_id", event.ID[0:9]).
Str("app", appName).
Str("ip_address", container.NetworkSettings.IpAddress).
Msg("new_container")
continue
}
existingContainer := cm[event.ID]
cm[event.ID] = container
// do nothing if the ip addresses match
if existingContainer.NetworkSettings.IpAddress == container.NetworkSettings.IpAddress {
continue
}
log.Info().
Str("container_id", event.ID[0:9]).
Str("app", appName).
Str("old_ip_address", existingContainer.NetworkSettings.IpAddress).
Str("new_ip_address", container.NetworkSettings.IpAddress).
Msg("reloading_nginx")
if err := runCommand("dokku", "--quiet", "nginx:build-config", appName); err != nil {
log.Warn().
Str("container_id", event.ID[0:9]).
Str("app", appName).
Str("error", err.Error()).
Msg("reload_failed")
}
}
}
func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
resp, err := request("/events")
if err != nil {
log.Fatal().
Str("error", err.Error()).
Msg("stream_failure")
}
defer resp.Body.Close()
watch(resp.Body)
}