-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
505 lines (418 loc) · 11.5 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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
// Copyright 2014 The Hanoverd Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"time"
"golang.org/x/sys/unix"
"github.com/docker/go-connections/nat"
"github.com/sensiblecodeio/barrier"
"github.com/sensiblecodeio/hookbot/pkg/listen"
"github.com/urfave/cli"
"github.com/sensiblecodeio/hanoverd/pkg/builder"
"github.com/sensiblecodeio/hanoverd/pkg/iptables"
"github.com/sensiblecodeio/hanoverd/pkg/opts"
"github.com/sensiblecodeio/hanoverd/pkg/source"
"github.com/sensiblecodeio/hanoverd/pkg/util"
)
// DockerErrorStatus returns the HTTP status code represented by `err` or Status
// OK if no error or 0 if err != nil and is not a docker error.
func DockerErrorStatus(err error) int {
log.Printf("DockerErrorStatus: %T", err)
if err == nil {
return http.StatusOK
}
return 0
}
type Options struct {
env, publish, volumes, mounts []string
containerArgs []string
ports nat.PortSet
portBindings nat.PortMap
statusURI string
disableOverlap bool
overlapGraceDuration time.Duration
}
type UpdateEvent struct {
Payload []byte // input
OutputStream io.Writer
Obtained barrier.Barrier
BuildComplete chan<- struct{}
}
// Determine if stdin is connected without blocking
func IsStdinReadable() bool {
unix.SetNonblock(int(os.Stdin.Fd()), true)
_, err := os.Stdin.Read([]byte{0})
unix.SetNonblock(int(os.Stdin.Fd()), false)
return err != io.EOF
}
func main() {
app := cli.NewApp()
app.Name = "hanoverd"
app.Usage = "handover docker containers"
// Use `hanoverd version` rather than `hanoverd -v`
app.HideVersion = true
// Made by `go generate` populating version.go via `git describe`.
app.Version = Version
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "disable-overlap",
Usage: "shut down old container before starting new one",
},
cli.StringSliceFlag{
Name: "env, e",
Usage: "environment variables to pass (reads from env if = omitted)",
Value: &cli.StringSlice{},
},
cli.StringSliceFlag{
Name: "publish, p",
Usage: "ports to publish (same syntax as docker)",
Value: &cli.StringSlice{},
},
cli.StringSliceFlag{
Name: "volume, v",
Usage: "Bind mount a volume",
Value: &cli.StringSlice{},
},
cli.StringSliceFlag{
Name: "mount, m",
Usage: "Supply mounts",
Value: &cli.StringSlice{},
},
cli.StringFlag{
Name: "status-uri",
Usage: "specify URI which returns 200 OK when functioning correctly",
Value: "/",
},
cli.StringFlag{
Name: "hookbot",
Usage: "url of hookbot websocket endpoint to monitor for updates",
EnvVar: "HOOKBOT_URL",
},
cli.DurationFlag{
Name: "overlap-grace-duration",
Usage: "length of time to wait before killing a superceded container",
Value: 1 * time.Second,
},
}
app.Action = ActionRun
app.Commands = []cli.Command{
{
Name: "builder",
Action: builder.Action,
Flags: []cli.Flag{
cli.StringFlag{
Name: "listen",
Usage: "url of hookbot websocket endpoint to monitor for updates",
EnvVar: "HOOKBOT_MONITOR_URL",
},
cli.StringFlag{
Name: "docker-notify",
Usage: "url of hookbot pub endpoint to notify on complete build",
EnvVar: "HOOKBOT_DOCKER_NOTIFY_URL",
},
},
},
{
Name: "version",
Action: cli.ShowVersion,
},
}
app.RunAndExitOnError()
}
func ActionRun(c *cli.Context) {
var err error
options := Options{}
options.volumes = c.StringSlice("volume")
options.mounts = c.StringSlice("mount")
options.env = makeEnv(c.StringSlice("env"))
options.statusURI = c.String("status-uri")
options.disableOverlap = c.Bool("disable-overlap")
options.overlapGraceDuration = c.Duration("overlap-grace-duration")
containerName := "hanoverd"
var imageSource source.ImageSource
if c.GlobalString("hookbot") != "" {
hookbotURL := c.GlobalString("hookbot")
containerName, imageSource, err = source.GetSourceFromHookbot(hookbotURL)
if err != nil {
log.Fatalf("Failed to parse hookbot source: %v", err)
}
options.containerArgs = c.Args()
} else if len(c.Args()) == 0 {
imageSource = &source.CwdSource{}
} else {
first := c.Args().First()
args := c.Args()[1:]
if first == "@" {
// If the first arg is "@", then use the Cwd
imageSource = &source.CwdSource{}
} else {
// The argument is a repository[:tag] to pull and run.
imageSource = source.DockerPullSourceFromImage(first)
}
options.containerArgs = args
}
if imageSource == nil {
log.Fatalf("No image source specified")
}
if err := iptables.CheckIPTables(); err != nil {
log.Fatal("Unable to run `iptables -L`, see README (", err, ")")
}
options.ports, options.portBindings, err = nat.ParsePortSpecs(c.StringSlice("publish"))
if err != nil {
log.Fatalln("--publish:", err)
}
log.Println("Hanoverd")
var wg sync.WaitGroup
defer wg.Wait()
// Fired when we're signalled to exit
var dying barrier.Barrier
defer dying.Fall()
if IsStdinReadable() {
log.Println("Press CTRL-D to exit")
go func() {
defer dying.Fall()
defer log.Println("Stdin closed, exiting...")
// Await Stdin closure, don't care about errors
_, _ = io.Copy(ioutil.Discard, os.Stdin)
}()
}
events := make(chan *UpdateEvent, 1)
originalEvent := &UpdateEvent{}
events <- originalEvent
// SIGHUP handler
go func() {
sig := make(chan os.Signal)
signal.Notify(sig, unix.SIGHUP)
for value := range sig {
log.Printf("Received signal %s", value)
// Resend the original event
events <- originalEvent
}
}()
// SIGTERM, SIGINT handler
go func() {
defer dying.Fall()
var value os.Signal
defer log.Printf("Received signal %v", value)
sig := make(chan os.Signal)
signal.Notify(sig, unix.SIGTERM, unix.SIGINT)
value = <-sig
}()
if c.GlobalString("hookbot") != "" {
go MonitorHookbot(c.GlobalString("hookbot"), events)
}
go loop(containerName, imageSource, &wg, &dying, options, events)
<-dying.Barrier()
}
func MonitorHookbot(target string, notify chan<- *UpdateEvent) {
finish := make(chan struct{})
header := http.Header{}
events, errs := listen.RetryingWatch(target, header, finish)
log.Println("Monitoring hookbot")
go func() {
for err := range errs {
log.Printf("Error in MonitorHookbot: %v", err)
}
}()
for payload := range events {
log.Printf("Signalled via hookbot")
// data := map[string]string{}
// err := json.Unmarshal(ev, &data)
// if err != nil {
// log.Printf("Failed to parse message: %v", err)
// continue
// }
done := make(chan struct{})
outBound := &UpdateEvent{}
outBound.BuildComplete = done
outBound.Payload = payload
// outBound.Source.Type = GithubRepository
// outBound.Source.githubURL = "github.com/sensiblecodeio/hookbot"
// outBound.Source.githubRef = data["SHA"]
notify <- outBound
<-outBound.Obtained.Barrier()
// <-done
log.Printf("--- Build completed %v ---", "TODO(pwaller): Determine name from payload")
}
}
// Make an env []string from a list of options specified on the cmdline.
func makeEnv(opts []string) []string {
var env []string
for _, envVar := range opts {
if strings.Contains(envVar, "=") {
env = append(env, envVar)
} else {
env = append(env, fmt.Sprint(envVar, "=", os.Getenv(envVar)))
}
}
return env
}
// Main loop managing the lifecycle of all containers.
func loop(
containerName string,
imageSource source.ImageSource,
wg *sync.WaitGroup,
dying *barrier.Barrier,
options Options,
events <-chan *UpdateEvent,
) {
client, err := util.DockerClient()
if err != nil {
dying.Fall()
log.Println("Connecting to Docker failed:", err)
return
}
flips := make(chan *Container)
go flipper(wg, options, flips)
var i int
supercede := func() {}
for event := range events {
name := fmt.Sprint(containerName, "-", i)
i++
log.Printf("New container starting: %q", name)
if options.disableOverlap {
log.Printf("Overlap switched off, killing old")
flips <- nil
}
c := NewContainer(client, name, wg)
c.Args = options.containerArgs
c.Env = options.env
c.Volumes = options.volumes
var mountOpts opts.MountOpt
for _, mount := range options.mounts {
mountOpts.Set(mount) // note: set is really 'append'.
}
c.Mounts = mountOpts.Value()
c.StatusURI = options.statusURI
c.Obtained.Forward(&event.Obtained)
// Global exit should cause container exit
dying.Forward(&c.Closing)
// Cancel an existing startup, if there is one.
supercede()
supercede = c.Superceded.Fall
wg.Add(1)
go func(c *Container) {
defer wg.Done()
if imageSource == nil {
log.Printf("No image source specified")
c.Failed.Fall()
return
}
status, err := c.Run(imageSource, event.Payload)
if err != nil {
log.Println("Container run failed:", strings.TrimSpace(err.Error()))
return
}
log.Println("container", c.Name, "quit, exit status:", status)
}(c)
wg.Add(1)
go func(c *Container) {
defer wg.Done()
log.Printf("Awaiting container fate: %q %q", c.Name, c.StatusURI)
select {
case <-c.Failed.Barrier():
log.Println("Container failed before going live:", c.Name)
c.Closing.Fall()
return
case <-c.Superceded.Barrier():
log.Println("Container superceded before going live:", c.Name)
c.Closing.Fall()
return
case <-c.Closing.Barrier():
log.Println("Container closed before going live:", c.Name)
return
case <-c.Ready.Barrier():
}
log.Println("Container going live:", c.Name)
flips <- c
}(c)
}
}
// Manage firewall flips
func flipper(
wg *sync.WaitGroup,
options Options,
newContainers <-chan *Container,
) {
var live *Container
for container := range newContainers {
if container == nil {
// A nil container is an instruction to just kill the
// running container. (e.g, for --disable-overlap)
if live != nil {
live.Closing.Fall()
}
live = nil
continue
}
err := flip(wg, options, container)
if err != nil {
container.Failed.Fall()
// Don't flip the firewall rules if there was a problem.
continue
}
if live != nil {
go func(live *Container) {
time.Sleep(options.overlapGraceDuration)
live.Closing.Fall()
}(live)
}
live = container
}
}
// Make container receive live traffic
func flip(wg *sync.WaitGroup, options Options, container *Container) error {
removal := []func() error{}
defer func() {
// Block main exit until firewall rule has been removed
wg.Add(1)
go func() {
defer wg.Done()
<-container.Closing.Barrier()
for _, remove := range removal {
err := remove()
if err != nil {
log.Printf("flip: removal failed: %v", err)
}
}
}()
}()
for internalPort, bindings := range options.portBindings {
if mappedPort, ok := container.MappedPort(internalPort.Int()); ok {
for _, binding := range bindings {
var public int
_, err := fmt.Sscan(binding.HostPort, &public)
if err != nil {
// If no public port specified, use same port as internal port
public = internalPort.Int()
}
ipAddress := container.containerInfo.NetworkSettings.IPAddress
remove, err := iptables.ConfigureRedirect(public, mappedPort, ipAddress, internalPort.Int())
if err != nil {
// Firewall rule didn't get applied.
err := fmt.Errorf(
"flip: ConfigureRedirect (public: %v, private: %v) failed: %q",
public, internalPort, err)
container.err(err)
return err
}
removal = append(removal, remove)
}
} else {
err := fmt.Errorf("Docker image not exposing port %v!", internalPort)
container.err(err)
return err
}
}
return nil
}