forked from dokku/dokku-event-listener
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
233 lines (205 loc) · 5.58 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
package main
import (
"context"
"fmt"
"os"
"os/exec"
"strconv"
"strings"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/events"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
type containerMap map[string]*types.ContainerJSON
// 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
const DOKKU_APP_LABEL = "com.dokku.app-name"
var cm containerMap
var dockerClient *client.Client
// 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 runCommand(args ...string) error {
cmd := NewShellCmd(strings.Join(args, " "))
cmd.ShowOutput = false
if cmd.Execute() {
return nil
}
return cmd.Error
}
func registerContainers(ctx context.Context) error {
cm = containerMap{}
filters := filters.NewArgs(
filters.Arg("label", DOKKU_APP_LABEL),
)
containers, err := dockerClient.ContainerList(ctx, types.ContainerListOptions{
Filters: filters,
})
if err != nil {
return err
}
for _, container := range containers {
containerJSON, err := dockerClient.ContainerInspect(ctx, container.ID)
if err != nil {
return err
}
cm[container.ID] = &containerJSON
log.Info().
Str("container_id", container.ID[0:9]).
Str("app", containerJSON.Config.Labels[DOKKU_APP_LABEL]).
Str("ip_address", containerJSON.NetworkSettings.Networks["bridge"].IPAddress).
Msg("register_container")
}
return nil
}
func watchEvents(ctx context.Context, sinceTimestamp int64) {
filters := filters.NewArgs(
filters.Arg("type", events.ContainerEventType),
filters.Arg("label", DOKKU_APP_LABEL),
)
events, errors := dockerClient.Events(ctx, types.EventsOptions{
Since: strconv.FormatInt(sinceTimestamp, 10),
Filters: filters,
})
for {
select {
case err := <-errors:
log.Fatal().
Err(err).
Msg("events_failure")
case event := <-events:
handleEvent(ctx, event)
}
}
}
func handleEvent(ctx context.Context, event events.Message) (error) {
containerId := event.Actor.ID
containerShortId := containerId[0:9]
// handle removing deleted/destroyed containers
if event.Action == "delete" || event.Action == "destroy" {
if _, ok := cm[containerId]; ok {
log.Info().
Str("container_id", containerShortId).
Msg("dead_container")
delete(cm, containerId)
}
return nil
}
container, err := dockerClient.ContainerInspect(ctx, containerId)
if err != nil {
return err
}
appName := container.Config.Labels[DOKKU_APP_LABEL]
if event.Action == "die" {
if container.HostConfig.RestartPolicy.Name == "no" {
return nil
}
if container.RestartCount == container.HostConfig.RestartPolicy.MaximumRetryCount {
log.Info().
Str("container_id", containerShortId).
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", containerShortId).
Str("app", appName).
Str("error", err.Error()).
Msg("rebuild_failed")
return err
}
}
}
// skip non-start events
if event.Action != "start" && event.Action != "restart" {
return nil
}
if _, ok := cm[containerId]; !ok {
cm[containerId] = &container
log.Info().
Str("container_id", containerShortId).
Str("app", appName).
Str("ip_address", container.NetworkSettings.Networks["bridge"].IPAddress).
Msg("new_container")
return nil
}
existingContainer := cm[containerId]
cm[containerId] = &container
// do nothing if the ip addresses match
if existingContainer.NetworkSettings.Networks["bridge"].IPAddress == container.NetworkSettings.Networks["bridge"].IPAddress {
return nil
}
log.Info().
Str("container_id", containerShortId).
Str("app", appName).
Str("old_ip_address", existingContainer.NetworkSettings.Networks["bridge"].IPAddress).
Str("new_ip_address", container.NetworkSettings.Networks["bridge"].IPAddress).
Msg("reloading_nginx")
if err := runCommand("dokku", "--quiet", "nginx:build-config", appName); err != nil {
log.Warn().
Str("container_id", containerShortId).
Str("app", appName).
Str("error", err.Error()).
Msg("reload_failed")
}
return err
}
func main() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
var err error
dockerClient, err = client.NewClientWithOpts(client.WithVersion(APIVERSION))
if err != nil {
log.Fatal().
Err(err).
Msg("api_connect_failed")
}
ctx := context.Background()
startupTimestamp := time.Now().Unix()
if err := registerContainers(ctx); err != nil {
log.Fatal().
Err(err).
Msg("containers_init_failed")
}
watchEvents(ctx, startupTimestamp)
}