-
Notifications
You must be signed in to change notification settings - Fork 6
/
api.go
537 lines (419 loc) · 12.3 KB
/
api.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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"html/template"
"io"
"log"
"net"
"net/http"
"os"
"strings"
"sync"
)
// Defines the currently supported cloud providers
// TODO: AWS
const (
AWS CloudProvider = iota + 1
GCE
)
var (
openBrace = byte('(')
closeBrace = byte(')')
)
// Cloud Provider ENUM
type CloudProvider uint8
type cluster struct {
Name string
IP string
Joined bool
}
type clusters []*cluster
// ==============================
type templateData struct {
RemoteHost string
}
// API Service
type api struct {
config *ApiConfig
serviceConfig *ServiceConfig
adminConfig *AdminConfig
templateData templateData
datacenters map[string]bool
traffic map[string]bool
mutex sync.Mutex
mutexTraffic sync.Mutex
federation *federationManager
clusters clusters
}
// Create a new API struct
func NewAPI(apiConfig *ApiConfig, serviceConfig *ServiceConfig, adminConfig *AdminConfig) *api {
remoteHost := serviceConfig.adminHost
if serviceConfig != nil && serviceConfig.adminPort != "" {
remoteHost = fmt.Sprintf("%s:%s", serviceConfig.adminHost, serviceConfig.adminPort)
}
if remoteHost == "" {
remoteHost = "localhost:8081" // for local development
}
api := api{
config: apiConfig,
serviceConfig: serviceConfig,
adminConfig: adminConfig,
datacenters: make(map[string]bool),
traffic: make(map[string]bool),
mutex: sync.Mutex{},
mutexTraffic: sync.Mutex{},
}
// set the federation manager if the FEDERATION_IP
if adminConfig.federationIP != "" {
log.Println("FEDERATION_IP:", adminConfig.federationIP)
api.federation = NewFederationManager(adminConfig.federationIP)
}
if adminConfig.clusters != "" {
api.clusters = parseClusters(adminConfig.clusters)
}
return &api
}
// Start the API: both the admin and the services
// the difference is set by an environment variable
func (api *api) Start() {
http.HandleFunc("/favicon.ico", api.faviconHandlerFunc)
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
// used for signaling that the conatiner is up and running
http.HandleFunc("/live", api.liveHandlerFunc)
// used for signaling that the conatiner is ready to receive requests
http.HandleFunc("/ready", api.readyHandlerFunc)
if api.config.isAdmin {
// Add zone handler
http.HandleFunc("/ping", api.pingHandlerFunc)
http.HandleFunc("/", api.zoneIndexHandlerFunc)
http.HandleFunc("/services", api.adminHandlerFunc)
http.HandleFunc("/disable", api.adminDisableHandlerFunc)
http.HandleFunc("/enable", api.adminEnableHandlerFunc)
http.HandleFunc("/startTraffic", api.startTraffic)
http.HandleFunc("/stopTraffic", api.stopTraffic)
http.HandleFunc("/trafficSourceActive", api.trafficSourceActive)
// simple GET entry points
http.HandleFunc("/federation/clusters", api.clustersHandlerFunc)
http.HandleFunc("/federation/add", api.federationAddHandlerFunc)
http.HandleFunc("/federation/remove", api.federationRemoveHandlerFunc)
} else {
indexHandler := http.HandlerFunc(api.loadHandlerFunc)
// load generation
http.Handle("/load", api.requestsMiddleware(indexHandler))
// Add zone handler
http.HandleFunc("/", api.indexHandlerFunc)
// Service to get the data
http.HandleFunc("/location", api.zoneHandlerFunc)
// disable the readyness
http.HandleFunc("/disable", api.disableHandlerFunc)
// enable the readyness
http.HandleFunc("/enable", api.enableHandlerFunc)
// kill ther app
http.HandleFunc("/kill", api.killHandlerFunc)
// default zone ready to true
if api.config.zone != nil {
api.config.zone.Ready = true
}
}
// start the HTTP server
portHost := fmt.Sprintf("%s:%s", api.config.host, api.config.port)
// show the vars
if api.config.isAdmin {
log.Println("Admin mode - HTTP listening on:", portHost, "for provider", api.config.provider)
} else {
log.Println("HTTP listening on:", portHost, "for provider", api.config.provider)
}
for _, e := range os.Environ() {
log.Println(e)
}
// socket listening
log.Fatal(http.ListenAndServe(portHost, nil))
}
// =============================================================
// Middleware for request counter
func (api *api) requestsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
trafficSourceZone := r.Header.Get("X-Origin-Region")
if trafficSourceZone != "" {
// increment the counter for traffic coming to a specific zone
api.config.traffic.Increment(trafficSourceZone)
}
next.ServeHTTP(w, r)
})
}
// ##### ADMIN
// =============================================================
func (api *api) clustersHandlerFunc(w http.ResponseWriter, r *http.Request) {
federatedClusters := api.federation.AllClusters()
for _, staticCluster := range api.clusters {
for _, federatedCluster := range federatedClusters.Entries {
// reset the joined flag
staticCluster.Joined = false
if federatedCluster.Meta.Name == staticCluster.Name {
staticCluster.Joined = true
break
}
}
}
data := api.clusters.toJson()
w.Header().Set("Content-Type", "application/json")
w.Write(data)
}
func (api *api) federationAddHandlerFunc(w http.ResponseWriter, r *http.Request) {
clusterName := r.URL.Query().Get("name")
if clusterName != "" {
// retrieve the IP
ip := api.clusters.findIP(clusterName)
if ip != "" && api.federation != nil {
if ok := api.federation.AddCluster(clusterName, ip); ok {
w.WriteHeader(http.StatusOK)
return
}
}
}
w.WriteHeader(http.StatusInternalServerError)
}
func (api *api) federationRemoveHandlerFunc(w http.ResponseWriter, r *http.Request) {
clusterName := r.URL.Query().Get("name")
if clusterName != "" {
// retrieve the IP
ip := api.clusters.findIP(clusterName)
if ip != "" && api.federation != nil {
if ok := api.federation.RemoveCluster(clusterName); ok {
w.WriteHeader(http.StatusOK)
return
}
}
}
w.WriteHeader(http.StatusInternalServerError)
}
func (api *api) startTraffic(w http.ResponseWriter, r *http.Request) {
dc := r.URL.Query().Get("dc")
if dc != "" {
api.mutexTraffic.Lock()
api.traffic[dc] = true
api.mutexTraffic.Unlock()
log.Println("Traffic from", dc, "enabled.")
}
}
func (api *api) stopTraffic(w http.ResponseWriter, r *http.Request) {
dc := r.URL.Query().Get("dc")
if dc != "" {
api.mutexTraffic.Lock()
api.traffic[dc] = false
api.mutexTraffic.Unlock()
log.Println("Traffic from", dc, "disabled.")
}
}
func (api *api) trafficSourceActive(w http.ResponseWriter, r *http.Request) {
dc := r.URL.Query().Get("dc")
if dc != "" {
api.mutexTraffic.Lock()
active, ok := api.traffic[dc]
api.mutexTraffic.Unlock()
if ok {
fmt.Fprintf(w, "%t", active)
return
}
}
fmt.Fprintf(w, "%t", true)
}
func (api *api) adminHandlerFunc(w http.ResponseWriter, r *http.Request) {
vms := api.adminConfig.adminPanel.AllZones()
data, _ := json.Marshal(&vms)
w.Header().Set("Content-Type", "application/json")
w.Write(data)
}
func (api *api) pingHandlerFunc(w http.ResponseWriter, r *http.Request) {
if r.Body == nil {
http.Error(w, "Missing request body", 400)
return
}
decoder := json.NewDecoder(r.Body)
var z zone
err := decoder.Decode(&z)
if err != nil {
log.Println("Could not deserialize zone", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
// the heartbeat ping responds to the clients and may set the READY flag in the zone
// thefore we have to overwrite it here
// The value is coming from the admin
if z.Name != "" {
// ping the ZONE and increase the traffic counters
api.adminConfig.adminPanel.Ping(z)
// set the READY flag
if enabled, ok := api.datacenters[z.Name]; ok {
if enabled {
api.adminConfig.adminPanel.Enable(z.Name)
} else {
api.adminConfig.adminPanel.Disable(z.Name)
}
}
data := api.adminConfig.adminPanel.get(z.Name).toJson()
w.Header().Set("Content-Type", "application/json")
w.Write(data)
return
}
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Could not de-serialize zone data"))
}
func (api *api) adminDisableHandlerFunc(w http.ResponseWriter, r *http.Request) {
dc := r.URL.Query().Get("dc")
if dc != "" {
api.mutex.Lock()
api.datacenters[dc] = false
api.mutex.Unlock()
log.Println("Datacenter", dc, "disabled.")
}
}
func (api *api) adminEnableHandlerFunc(w http.ResponseWriter, r *http.Request) {
dc := r.URL.Query().Get("dc")
if dc != "" {
api.mutex.Lock()
api.datacenters[dc] = true
api.mutex.Unlock()
log.Println("Datacenter", dc, "enabled.")
}
}
// =====================================================================
// ##### END ADMIN
func (api *api) indexHandlerFunc(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s", api.config.zone.Name)
}
func (api *api) loadHandlerFunc(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
func (api *api) zoneIndexHandlerFunc(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
w.WriteHeader(http.StatusNotFound)
return
}
t, err := template.ParseFiles("templates/index.html")
if err != nil {
log.Fatal("Error parsing admin template files ", err)
}
t.Execute(w, nil)
}
func (api *api) faviconHandlerFunc(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}
func (api *api) killHandlerFunc(w http.ResponseWriter, r *http.Request) {
log.Println("Used KILL SWITCH")
os.Exit(1)
}
// checks whether the service is up and runnning
func (api *api) liveHandlerFunc(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
// check if the service is ready to serve requests
func (api *api) readyHandlerFunc(w http.ResponseWriter, r *http.Request) {
api.writeReadyness(w)
}
// Enable the service
func (api *api) enableHandlerFunc(w http.ResponseWriter, r *http.Request) {
api.mutex.Lock()
api.config.isReady = true
api.mutex.Unlock()
log.Println("Service enabled")
w.WriteHeader(http.StatusOK)
}
// Disable the service
func (api *api) disableHandlerFunc(w http.ResponseWriter, r *http.Request) {
api.mutex.Lock()
api.config.isReady = false
api.mutex.Unlock()
log.Println("Service disabled")
w.WriteHeader(http.StatusOK)
}
// Returns the datacenter zone information about the running process
func (api *api) zoneHandlerFunc(w http.ResponseWriter, r *http.Request) {
api.mutex.Lock()
defer api.mutex.Unlock()
if !api.config.isReady {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.Header().Set("Content-Type", "application/json")
// serve back the VM info and the client remote IP info
remoteIp := getIPAdress(r)
host, _, err := net.SplitHostPort(remoteIp)
if err != nil {
log.Println("Error splitting remote IP", err)
host = remoteIp
}
if host != "" {
coord := getIPCoordinates(host)
api.config.zone.ClientIpAddress = &coord
log.Printf("Got client IP coordinates: %s\n", api.config.zone.ClientIpAddress)
}
// serve the data back
if data := api.config.zone.toJson(); len(data) > 0 {
w.Write(data)
return
}
log.Println("Error serialize VM information to JSON")
// otherwise return error
w.WriteHeader(http.StatusServiceUnavailable)
}
func (api *api) writeReadyness(w http.ResponseWriter) {
if api.config.isAdmin {
w.WriteHeader(http.StatusOK)
return
}
api.mutex.Lock()
if api.config.isReady {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusServiceUnavailable)
}
api.mutex.Unlock()
}
func remove(slice []*zone, s int) []*zone {
return append(slice[:s], slice[s+1:]...)
}
func parseClusters(clustersEnv string) clusters {
var clusters []*cluster
if clustersEnv == "" {
return clusters
}
log.Println("Parsing clusters:", clustersEnv)
r := csv.NewReader(strings.NewReader(clustersEnv))
for {
records, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Println(err)
break
}
for _, record := range records {
tokens := strings.Split(record, "=")
if len(tokens) > 0 {
clusters = append(clusters, &cluster{Name: strings.Replace(tokens[0], "gce", "cluster", 1), IP: tokens[1]})
}
}
}
log.Println("Parsed clusters", clusters)
return clusters
}
func (c clusters) toJson() []byte {
var data []byte
jsonData, err := json.Marshal(c)
if err != nil {
return data
}
return jsonData
}
func (c clusters) findIP(name string) string {
for _, cluster := range c {
if cluster.Name == name {
return cluster.IP
}
}
return ""
}