forked from QubitProducts/bamboo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bamboo.go
executable file
·196 lines (168 loc) · 5 KB
/
bamboo.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
package main
import (
"flag"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"path"
"strings"
"syscall"
"time"
"github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/go-martini/martini"
"github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/kardianos/osext"
"github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/natefinch/lumberjack"
"github.com/QubitProducts/bamboo/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk"
"github.com/QubitProducts/bamboo/api"
"github.com/QubitProducts/bamboo/configuration"
"github.com/QubitProducts/bamboo/qzk"
"github.com/QubitProducts/bamboo/services/event_bus"
)
/*
Commandline arguments
*/
var configFilePath string
var logPath string
var serverBindPort string
func init() {
flag.StringVar(&configFilePath, "config", "config/development.json", "Full path of the configuration JSON file")
flag.StringVar(&logPath, "log", "", "Log path to a file. Default logs to stdout")
flag.StringVar(&serverBindPort, "bind", ":8000", "Bind HTTP server to a specific port")
}
func main() {
flag.Parse()
configureLog()
// Load configuration
conf, err := configuration.FromFile(configFilePath)
if err != nil {
log.Fatal(err)
}
eventBus := event_bus.New()
// Wait for died children to avoid zombies
signalChannel := make(chan os.Signal, 2)
signal.Notify(signalChannel, os.Interrupt, syscall.SIGCHLD)
go func() {
for {
sig := <-signalChannel
if sig == syscall.SIGCHLD {
r := syscall.Rusage{}
syscall.Wait4(-1, nil, 0, &r)
}
}
}()
// Create StatsD client
conf.StatsD.CreateClient()
// Create Zookeeper connection
zkConn := listenToZookeeper(conf, eventBus)
// Register handlers
handlers := event_bus.Handlers{Conf: &conf, Zookeeper: zkConn}
eventBus.Register(handlers.MarathonEventHandler)
eventBus.Register(handlers.ServiceEventHandler)
eventBus.Publish(event_bus.MarathonEvent{EventType: "bamboo_startup", Timestamp: time.Now().Format(time.RFC3339)})
// Handle gracefully exit
registerOSSignals()
// Start server
initServer(&conf, zkConn, eventBus)
}
func initServer(conf *configuration.Configuration, conn *zk.Conn, eventBus *event_bus.EventBus) {
stateAPI := api.StateAPI{Config: conf, Zookeeper: conn}
serviceAPI := api.ServiceAPI{Config: conf, Zookeeper: conn}
eventSubAPI := api.EventSubscriptionAPI{Conf: conf, EventBus: eventBus}
conf.StatsD.Increment(1.0, "restart", 1)
// Status live information
router := martini.Classic()
router.Get("/status", api.HandleStatus)
// API
router.Group("/api", func(api martini.Router) {
// State API
api.Get("/state", stateAPI.Get)
// Service API
api.Get("/services", serviceAPI.All)
api.Post("/services", serviceAPI.Create)
api.Put("/services/**", serviceAPI.Put)
api.Delete("/services/**", serviceAPI.Delete)
api.Post("/marathon/event_callback", eventSubAPI.Callback)
})
// Static pages
router.Use(martini.Static(path.Join(executableFolder(), "webapp")))
registerMarathonEvent(conf)
router.RunOnAddr(serverBindPort)
}
// Get current executable folder path
func executableFolder() string {
folderPath, err := osext.ExecutableFolder()
if err != nil {
log.Fatal(err)
}
return folderPath
}
func registerMarathonEvent(conf *configuration.Configuration) {
client := &http.Client{}
// it's safe to register with multiple marathon nodes
for _, marathon := range conf.Marathon.Endpoints() {
url := marathon + "/v2/eventSubscriptions?callbackUrl=" + conf.Bamboo.Endpoint + "/api/marathon/event_callback"
req, _ := http.NewRequest("POST", url, nil)
req.Header.Add("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
errorMsg := "An error occurred while accessing Marathon callback system: %s\n"
log.Printf(errorMsg, err)
return
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
log.Fatal(err)
return
}
body := string(bodyBytes)
if strings.HasPrefix(body, "{\"message") {
warningMsg := "Access to the callback system of Marathon seems to be failed, response: %s\n"
log.Printf(warningMsg, body)
}
}
}
func createAndListen(conf configuration.Zookeeper) (chan zk.Event, *zk.Conn) {
conn, _, err := zk.Connect(conf.ConnectionString(), time.Second*10)
if err != nil {
log.Panic(err)
}
ch, _ := qzk.ListenToConn(conn, conf.Path, true, conf.Delay())
return ch, conn
}
func listenToZookeeper(conf configuration.Configuration, eventBus *event_bus.EventBus) *zk.Conn {
serviceCh, serviceConn := createAndListen(conf.Bamboo.Zookeeper)
go func() {
for {
select {
case _ = <-serviceCh:
eventBus.Publish(event_bus.ServiceEvent{EventType: "change"})
}
}
}()
return serviceConn
}
func configureLog() {
if len(logPath) > 0 {
log.SetOutput(io.MultiWriter(&lumberjack.Logger{
Filename: logPath,
// megabytes
MaxSize: 100,
MaxBackups: 3,
//days
MaxAge: 28,
}, os.Stdout))
}
}
func registerOSSignals() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for _ = range c {
log.Println("Server Stopped")
os.Exit(0)
}
}()
}