forked from turnage/graw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
foreman.go
77 lines (67 loc) · 1.23 KB
/
foreman.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
package graw
import (
"log"
"github.com/mix/graw/botfaces"
"github.com/mix/graw/reddit"
)
func launch(
handler interface{},
kill chan bool,
errs <-chan error,
logger *log.Logger,
) (
func(),
func() error,
error,
) {
if setup, ok := handler.(botfaces.Loader); ok {
if err := setup.SetUp(); err != nil {
return nil, nil, err
}
}
tear := func() {
if tear, ok := handler.(botfaces.Tearer); ok {
tear.TearDown()
}
}
foremanKiller := make(chan bool)
foremanError := make(chan error)
go func() {
foremanError <- foreman(foremanKiller, kill, errs, logger)
}()
stop := func() {
defer tear()
close(foremanKiller)
}
wait := func() error {
defer tear()
return <-foremanError
}
return stop, wait, nil
}
func foreman(
kill <-chan bool,
killChildren chan<- bool,
errs <-chan error,
logger *log.Logger,
) error {
defer close(killChildren)
for {
select {
case <-kill:
return nil
case err := <-errs:
switch err {
case nil:
case reddit.BusyErr:
logger.Printf("Reddit was busy; staying up.")
case reddit.GatewayErr:
logger.Printf("Bad gateway error; staying up.")
case reddit.GatewayTimeoutErr:
logger.Printf("Gateway timeout; staying up.")
default:
return err
}
}
}
}