-
Notifications
You must be signed in to change notification settings - Fork 36
/
main.go
236 lines (204 loc) · 5.67 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
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/danielkrainas/aie-burnit/marathon"
"github.com/danielkrainas/aie-burnit/names"
"github.com/danielkrainas/aie-burnit/resources"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
const (
LOCAL_APP_ID = "local-app"
)
var (
MARATHON_APP_ID = ""
instanceName = ""
alerts = 0
marathonClient marathon.Client
)
type updateRequest struct {
Resource string `json:"resource,omitempty"`
Value string `json:"value,omitempty"`
Action string `json:"action,omitempty"`
Host string `json:"host,omitempty"`
}
func updateHandler(w http.ResponseWriter, r *http.Request) {
op := &updateRequest{}
jd := json.NewDecoder(r.Body)
if err := jd.Decode(op); err != nil {
fmt.Printf("error decoding update: %v\n", err)
w.WriteHeader(http.StatusBadRequest)
return
}
value, err := strconv.ParseFloat(op.Value, 32)
if err != nil {
fmt.Printf("error parsing value: %v\n", err)
w.WriteHeader(http.StatusBadRequest)
return
}
if op.Host == "" || r.URL.Path == "/update/self" {
switch op.Resource {
case "memory":
if op.Action == "reset" {
resources.ResetMemoryUsage()
} else {
resources.SetMemoryUsage(value)
}
}
w.WriteHeader(http.StatusNoContent)
} else {
content, err := json.Marshal(op)
if err != nil {
fmt.Printf("error reencoding update: %v\n", err)
w.WriteHeader(http.StatusBadRequest)
return
}
resp, err := http.Post(fmt.Sprintf("http://%s/update/self", op.Host), "application/json", strings.NewReader(string(content)))
if err != nil {
fmt.Printf("error relaying update: %v\n", err)
w.WriteHeader(http.StatusBadRequest)
return
}
resp.Body.Close()
w.WriteHeader(resp.StatusCode)
}
}
func defaultHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
alerts++
w.WriteHeader(http.StatusOK)
} else {
assetHandler(w, r)
}
}
func assetHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/style.css" {
http.ServeFile(w, r, "./assets/style.css")
return
} else if r.URL.Path == "/app.js" {
http.ServeFile(w, r, "./assets/app.js")
return
} else if r.URL.Path == "/" {
http.ServeFile(w, r, "./assets/index.html")
return
} else if r.URL.Path == "/cisco-logo-white.png" {
http.ServeFile(w, r, "./assets/cisco-logo-white.png")
return
}
w.WriteHeader(http.StatusNotFound)
}
func statusHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
io.WriteString(w, fmt.Sprintf(`{
"name": %q,
"host": %q,
"memory_usage": "%.1f"
}`, instanceName, r.Host, resources.GetMemoryUsage()))
}
func aggregateStatusHandler(w http.ResponseWriter, r *http.Request) {
app, err := marathonClient.GetApp(MARATHON_APP_ID)
if err != nil {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, fmt.Sprintf(`{ "errors": [%q] }`, err.Error()))
return
}
if app == nil {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.Header().Add("Content-Type", "application/json")
results := make([]string, 0)
for _, t := range app.Tasks {
status := getStatus(t)
results = append(results, string(status))
}
w.WriteHeader(http.StatusOK)
io.WriteString(w, fmt.Sprintf("[%s]", strings.Join(results, ",")))
}
func getStatus(t *marathon.Task) string {
if !t.Alive {
return getErrorStatus(t.HostAddress, "dead", "invalid healthcheck")
}
resp, err := http.Get(fmt.Sprintf("http://%s/status", t.HostAddress))
if err != nil {
return getErrorStatus(t.HostAddress, "quiet", "could not connect")
}
defer resp.Body.Close()
s, err := ioutil.ReadAll(resp.Body)
if err != nil {
return getErrorStatus(t.HostAddress, "confused", "invalid response")
}
return string(s)
}
func getErrorStatus(hostname string, status string, message string) string {
return fmt.Sprintf(`{"name":"(unknown)", "host":%q, "status":{"name":%q,message:%q}}`, hostname, status, message)
}
func determineAppId() {
instanceName = names.Generate()
serviceName := os.Getenv("SERVICE_NAME")
if serviceName != "" {
fmt.Printf("svc name=%q\n", serviceName)
hostVarName := strings.ToUpper(serviceName)
hostVarName = "HOST_" + strings.Replace(hostVarName, "-", "_", -1)
if os.Getenv(hostVarName) == "" {
MARATHON_APP_ID = serviceName
} else {
u, err := url.Parse(os.Getenv(hostVarName))
if err == nil {
MARATHON_APP_ID = strings.Split(u.Host, ".")[0]
}
}
} else {
fmt.Println("SERVICE_NAME not found")
}
if MARATHON_APP_ID == "" {
MARATHON_APP_ID = LOCAL_APP_ID
}
fmt.Printf("app=%s\n", MARATHON_APP_ID)
}
func setupMarathon() {
var err error
if os.Getenv("MOCK") != "" {
fmt.Println("mocks enabled")
marathonClient = marathon.NewMockClient()
err = nil
} else {
marathonClient, err = marathon.NewClient()
}
if err != nil {
panic(err)
}
}
func main() {
determineAppId()
setupMarathon()
app, err := marathonClient.GetApp(MARATHON_APP_ID)
if err != nil {
panic(err)
} else if app == nil {
panic("couldn't get app from marathon")
}
resources.SetMemoryLimit(float64(app.Memory))
http.HandleFunc("/", http.HandlerFunc(defaultHandler))
http.HandleFunc("/update", http.HandlerFunc(updateHandler))
http.HandleFunc("/update/self", http.HandlerFunc(updateHandler))
http.HandleFunc("/style.css", http.HandlerFunc(assetHandler))
http.HandleFunc("/app.js", http.HandlerFunc(assetHandler))
http.HandleFunc("/status", http.HandlerFunc(statusHandler))
http.HandleFunc("/status/all", http.HandlerFunc(aggregateStatusHandler))
fmt.Println("Example app listening at http://localhost:8888")
http.ListenAndServe(":8888", nil)
}