/
main.go
231 lines (197 loc) · 5.51 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
package main
import (
"encoding/json"
"fmt"
"github.com/gambol99/go-marathon"
"github.com/gorilla/websocket"
"io/ioutil"
"log"
"net/http"
"path/filepath"
"text/template"
"time"
)
const (
// Time allowed to write the file to the client.
writeWait = 10 * time.Second
// Time allowed to read the next pong message from the client.
pongWait = 60 * time.Second
// Send pings to client with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
// How long to wait between data pushes to the browser.
dataPushPeriod = 1 * time.Second
// How long to wait before we can scale again, in order to not overwhelm Marathon.
scaleCoolDownPeriod time.Duration = 5 * time.Second
marathonAddr = "http://172.17.0.1:8080"
)
type ClusterState struct {
Instances []Instance `json:"instances"`
NrOfInstances int `json:"nrOfInstances"`
}
type Instance struct {
Id string `json:"id"`
Max int `json:"max"`
Ops int `json:"ops"`
}
type State struct {
Max int `json:"max"`
Ops int `json:"ops"`
}
// custom template delimiters since the Go default delimiters clash with Angular's default.
var templateDelimiters = []string{"{{%", "%}}"}
var lastScaleAction = time.Unix(0, 0)
var (
client marathon.Marathon
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
)
func reader(ws *websocket.Conn) {
defer ws.Close()
ws.SetReadLimit(512)
ws.SetReadDeadline(time.Now().Add(pongWait))
ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
_, _, err := ws.ReadMessage()
if err != nil {
break
}
}
}
func scaleUp(opsT float64, maxT float64) {
load := opsT / maxT
reservoir := int(maxT - opsT)
log.Printf("load: %f, reservoir: %d, max: %d", load, reservoir, int(maxT))
if load > 0.5 && reservoir < 120 {
var diff time.Duration
diff = time.Now().Sub(lastScaleAction)
if diff < scaleCoolDownPeriod {
log.Print("Not scaling due to cooldown period")
return
}
app, err := client.Application("cattlestore")
if err != nil {
log.Printf("Not scaling: %s", err)
}
newInstances := 2 + app.Instances
lastScaleAction = time.Now()
log.Print("SCALE UP DUDE!!!")
if _, err := client.ScaleApplicationInstances("cattlestore", newInstances, false); err != nil {
log.Printf("Could not scale: %s", err)
}
}
}
func writer(ws *websocket.Conn) {
pingTicker := time.NewTicker(pingPeriod)
fileTicker := time.NewTicker(dataPushPeriod)
defer func() {
pingTicker.Stop()
fileTicker.Stop()
ws.Close()
}()
timeout := time.Duration(1 * time.Second)
httpClient := http.Client{
Timeout: timeout,
}
for {
select {
case <-fileTicker.C:
var clusterState ClusterState
app, err := client.Application("cattlestore")
if err != nil {
log.Printf("Not scaling: %s", err)
}
clusterState.NrOfInstances = app.Instances
ops_t, max_t := 0.0, 0.0
if app != nil && err == nil {
for _, task := range app.Tasks {
resp, err := httpClient.Get(fmt.Sprintf("http://172.17.0.1:%d/info", task.Ports[0]))
if err != nil {
continue
}
state, err := ioutil.ReadAll(resp.Body)
if err != nil {
continue
}
f := State{}
json.Unmarshal(state, &f)
clusterState.Instances = append(clusterState.Instances, Instance{
Id: task.ID[12:20],
Ops: f.Ops,
Max: f.Max,
})
ops_t += float64(f.Ops)
max_t += float64(f.Max)
}
}
go scaleUp(ops_t, max_t)
p, err := json.Marshal(clusterState)
if err != nil {
continue
}
// p := []byte(`[{"id":"6cd8a58f","max":24,"ops":24},{"id":"6cd8a58e","max":24,"ops":18},
// {"id":"1cd8a58f","max":24,"ops":24},{"id":"4cd8a58e","max":24,"ops":18},
// {"id":"2cd8a58f","max":24,"ops":24},{"id":"5cd8a58e","max":24,"ops":18},
// {"id":"3cd8a58f","max":24,"ops":24},{"id":"7cd8a58e","max":24,"ops":18}, {"id":"6cdf3444","max":30,"ops":12},{"id":"6cbdca8b","max":13,"ops":3},{"id":"6ce8f854","max":13,"ops":12}]`)
if p != nil {
ws.SetWriteDeadline(time.Now().Add(writeWait))
if err := ws.WriteMessage(websocket.TextMessage, p); err != nil {
return
}
}
case <-pingTicker.C:
ws.SetWriteDeadline(time.Now().Add(writeWait))
if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
return
}
}
}
}
func serveWs(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
if _, ok := err.(websocket.HandshakeError); !ok {
log.Println(err)
}
return
}
go writer(ws)
reader(ws)
}
func serveHome(w http.ResponseWriter, r *http.Request) {
temp := template.New("index.html")
temp.Delims(templateDelimiters[0], templateDelimiters[1])
temp.ParseFiles(filepath.Join("./", "index.html"))
if r.Method != "GET" {
http.Error(w, "Method not allowed", 405)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
var v = struct {
Host string
Data string
}{
r.Host,
string("initial data goes here"),
}
temp.Execute(w, &v)
}
func initMarathonClient() (marathon.Marathon, error) {
config := marathon.NewDefaultConfig()
config.URL = "http://172.17.0.1:8080"
return marathon.NewClient(config)
}
func main() {
var err error
if client, err = initMarathonClient(); err != nil {
log.Fatalf("No marathon client; %s", err)
}
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))
http.HandleFunc("/", serveHome)
http.HandleFunc("/ws", serveWs)
log.Print("Ready to herd...")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}