forked from open-falcon-archive/query
/
api.go
1671 lines (1594 loc) · 49 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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package http
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"math"
"net/http"
"sort"
"strconv"
"strings"
"time"
cmodel "github.com/Cepave/common/model"
"github.com/Cepave/query/g"
"github.com/Cepave/query/graph"
"github.com/Cepave/query/proc"
"github.com/astaxie/beego/orm"
"github.com/bitly/go-simplejson"
)
type Tag struct {
StrategyId int
Name string
Value string
CreateAt string
UpdateAt string
}
/**
* @function name: func postByJson(rw http.ResponseWriter, req *http.Request, url string)
* @description: This function sends a POST request in JSON format.
* @related issues: OWL-171
* @param: rw http.ResponseWriter
* @param: req *http.Request
* @param: url string
* @return: void
* @author: Don Hsieh
* @since: 11/12/2015
* @last modified: 11/13/2015
* @called by: func queryInfo(rw http.ResponseWriter, req *http.Request)
* func queryHistory(rw http.ResponseWriter, req *http.Request)
*/
func postByJSON(rw http.ResponseWriter, req *http.Request, url string) {
buf := new(bytes.Buffer)
buf.ReadFrom(req.Body)
s := buf.String()
reqPost, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(s)))
if err != nil {
log.Println("Error =", err.Error())
}
reqPost.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(reqPost)
if err != nil {
log.Println("Error =", err.Error())
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
rw.Header().Set("Content-Type", "application/json; charset=UTF-8")
rw.Write(body)
}
/**
* @function name: func queryInfo(rw http.ResponseWriter, req *http.Request)
* @description: This function handles /graph/info API request.
* @related issues: OWL-171
* @param: rw http.ResponseWriter
* @param: req *http.Request
* @return: void
* @author: Don Hsieh
* @since: 11/12/2015
* @last modified: 11/13/2015
* @called by: func configApiRoutes()
*/
func queryInfo(rw http.ResponseWriter, req *http.Request) {
url := g.Config().Api.Query + "/graph/info"
postByJSON(rw, req, url)
}
/**
* @function name: func queryHistory(rw http.ResponseWriter, req *http.Request)
* @description: This function handles /graph/history API request.
* @related issues: OWL-171
* @param: rw http.ResponseWriter
* @param: req *http.Request
* @return: void
* @author: Don Hsieh
* @since: 11/12/2015
* @last modified: 11/13/2015
* @called by: func configApiRoutes()
*/
func queryHistory(rw http.ResponseWriter, req *http.Request) {
url := g.Config().Api.Query + "/graph/history"
postByJSON(rw, req, url)
}
/**
* @function name: func getRequest(rw http.ResponseWriter, url string)
* @description: This function sends GET request to given URL.
* @related issues: OWL-159
* @param: rw http.ResponseWriter
* @param: url string
* @return: void
* @author: Don Hsieh
* @since: 11/24/2015
* @last modified: 11/24/2015
* @called by: func dashboardEndpoints(rw http.ResponseWriter, req *http.Request)
* in query/http/api.go
* @called by: func dashboardEndpoints(rw http.ResponseWriter, req *http.Request)
* in query/http/api.go
*/
func getRequest(rw http.ResponseWriter, url string) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Println("Error =", err.Error())
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("Error =", err.Error())
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
rw.Header().Set("Content-Type", "application/json; charset=UTF-8")
rw.Write(body)
}
/**
* @function name: func dashboardEndpoints(rw http.ResponseWriter, req *http.Request)
* @description: This function handles /api/endpoints API request.
* @related issues: OWL-159, OWL-171
* @param: rw http.ResponseWriter
* @param: req *http.Request
* @return: void
* @author: Don Hsieh
* @since: 11/12/2015
* @last modified: 11/24/2015
* @called by: func configApiRoutes()
*/
func dashboardEndpoints(rw http.ResponseWriter, req *http.Request) {
url := g.Config().Api.Dashboard + req.URL.RequestURI()
getRequest(rw, url)
}
/**
* @function name: func postByForm(rw http.ResponseWriter, req *http.Request, url string)
* @description: This function sends a POST request in Form format.
* @related issues: OWL-171
* @param: rw http.ResponseWriter
* @param: req *http.Request
* @param: url string
* @return: void
* @author: Don Hsieh
* @since: 11/12/2015
* @last modified: 11/13/2015
* @called by: func dashboardCounters(rw http.ResponseWriter, req *http.Request)
* func dashboardChart(rw http.ResponseWriter, req *http.Request)
*/
func postByForm(rw http.ResponseWriter, req *http.Request, url string) {
req.ParseForm()
client := &http.Client{}
resp, err := client.PostForm(url, req.PostForm)
if err != nil {
log.Println("Error =", err.Error())
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
rw.Header().Set("Content-Type", "application/json; charset=UTF-8")
rw.Write(body)
}
/**
* @function name: func dashboardCounters(rw http.ResponseWriter, req *http.Request)
* @description: This function handles /api/counters API request.
* @related issues: OWL-171
* @param: rw http.ResponseWriter
* @param: req *http.Request
* @return: void
* @author: Don Hsieh
* @since: 11/13/2015
* @last modified: 11/13/2015
* @called by: func configApiRoutes()
*/
func dashboardCounters(rw http.ResponseWriter, req *http.Request) {
url := g.Config().Api.Dashboard + "/api/counters"
postByForm(rw, req, url)
}
/**
* @function name: func dashboardChart(rw http.ResponseWriter, req *http.Request)
* @description: This function handles /api/chart API request.
* @related issues: OWL-171
* @param: rw http.ResponseWriter
* @param: req *http.Request
* @return: void
* @author: Don Hsieh
* @since: 11/13/2015
* @last modified: 11/13/2015
* @called by: func configApiRoutes()
*/
func dashboardChart(rw http.ResponseWriter, req *http.Request) {
url := g.Config().Api.Dashboard + "/chart"
postByForm(rw, req, url)
}
func getAgentAliveData(hostnames []string, versions map[string]string, result map[string]interface{}) []cmodel.GraphLastResp {
var queries []cmodel.GraphLastParam
o := orm.NewOrm()
var hosts []*Host
_, err := o.Raw("SELECT hostname, agent_version FROM falcon_portal.host ORDER BY hostname ASC").QueryRows(&hosts)
if err != nil {
setError(err.Error(), result)
} else {
for _, host := range hosts {
var query cmodel.GraphLastParam
if !strings.Contains(host.Hostname, ".") && strings.Contains(host.Hostname, "-") {
hostnames = append(hostnames, host.Hostname)
versions[host.Hostname] = host.Agent_version
query.Endpoint = host.Hostname
query.Counter = "agent.alive"
queries = append(queries, query)
}
}
}
s, err := json.Marshal(queries)
if err != nil {
setError(err.Error(), result)
}
url := g.Config().Api.Query + "/graph/last"
reqPost, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(s)))
if err != nil {
setError(err.Error(), result)
}
reqPost.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(reqPost)
if err != nil {
setError(err.Error(), result)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
data := []cmodel.GraphLastResp{}
err = json.Unmarshal(body, &data)
if err != nil {
setError(err.Error(), result)
}
return data
}
func processAgentAliveData(data []cmodel.GraphLastResp, hostnames []string, versions map[string]string, result map[string]interface{}) {
name := ""
version := ""
status := ""
alive := 0
countOfNormal := 0
countOfWarn := 0
countOfDead := 0
anomalies := []interface{}{}
items := []interface{}{}
for key, row := range data {
name = row.Endpoint
var diff int64
diff = 0
var timestamp int64
timestamp = 0
status = "dead"
alive = 0
if name == "" {
name = hostnames[key]
} else {
alive = int(row.Value.Value)
timestamp = row.Value.Timestamp
now := time.Now().Unix()
diff = now - timestamp
}
version = versions[name]
if alive > 0 {
if diff > 3600 {
status = "warm"
countOfWarn++
} else {
status = "normal"
countOfNormal++
}
} else {
countOfDead++
}
item := map[string]interface{}{}
item["id"] = strconv.Itoa(key + 1)
item["hostname"] = name
item["agent_version"] = version
item["alive"] = alive
item["timestamp"] = timestamp
item["diff"] = diff
item["status"] = status
items = append(items, item)
if diff > 60*60*24 && timestamp > 0 {
anomalies = append(anomalies, item)
}
}
var count = make(map[string]interface{})
count["all"] = len(data)
count["normal"] = countOfNormal
count["warn"] = countOfWarn
count["dead"] = countOfDead
result["count"] = count
result["items"] = items
}
func getAlive(rw http.ResponseWriter, req *http.Request) {
var nodes = make(map[string]interface{})
errors := []string{}
var result = make(map[string]interface{})
result["error"] = errors
data := []cmodel.GraphLastResp{}
hostnames := []string{}
var versions = make(map[string]string)
data = getAgentAliveData(hostnames, versions, result)
processAgentAliveData(data, hostnames, versions, result)
nodes["result"] = result
rw.Header().Set("Access-Control-Allow-Origin", "*")
setResponse(rw, nodes)
}
func setStrategyTags(rw http.ResponseWriter, req *http.Request) {
errors := []string{}
var result = make(map[string]interface{})
result["error"] = errors
buf := new(bytes.Buffer)
buf.ReadFrom(req.Body)
json, err := simplejson.NewJson(buf.Bytes())
if err != nil {
setError(err.Error(), result)
}
var nodes = make(map[string]interface{})
nodes, _ = json.Map()
strategyID := ""
tagName := ""
tagValue := ""
if value, ok := nodes["strategyID"]; ok {
strategyID = value.(string)
delete(nodes, "strategyID")
}
if value, ok := nodes["tagName"]; ok {
tagName = value.(string)
delete(nodes, "tagName")
}
if value, ok := nodes["tagValue"]; ok {
tagValue = value.(string)
delete(nodes, "tagValue")
}
if len(strategyID) > 0 && len(tagName) > 0 && len(tagValue) > 0 {
strategyIDint, err := strconv.Atoi(strategyID)
if err != nil {
setError(err.Error(), result)
} else {
o := orm.NewOrm()
var tag Tag
sqlcmd := "SELECT * FROM falcon_portal.tags WHERE strategy_id=?"
err = o.Raw(sqlcmd, strategyIDint).QueryRow(&tag)
if err == orm.ErrNoRows {
sql := "INSERT INTO tags(strategy_id, name, value, create_at) VALUES(?, ?, ?, ?)"
res, err := o.Raw(sql, strategyIDint, tagName, tagValue, getNow()).Exec()
if err != nil {
setError(err.Error(), result)
} else {
num, _ := res.RowsAffected()
log.Println("mysql row affected nums =", num)
result["strategyID"] = strategyID
result["action"] = "create"
}
} else if err != nil {
setError(err.Error(), result)
} else {
sql := "UPDATE tags SET name = ?, value = ? WHERE strategy_id = ?"
res, err := o.Raw(sql, tagName, tagValue, strategyIDint).Exec()
if err != nil {
setError(err.Error(), result)
} else {
num, _ := res.RowsAffected()
log.Println("mysql row affected nums =", num)
result["strategyID"] = strategyID
result["action"] = "update"
}
}
}
} else {
setError("Input value errors.", result)
}
nodes["result"] = result
setResponse(rw, nodes)
}
func getTemplateStrategies(rw http.ResponseWriter, req *http.Request) {
errors := []string{}
var result = make(map[string]interface{})
result["error"] = errors
items := []interface{}{}
countOfStrategies := 0
arguments := strings.Split(req.URL.Path, "/")
if arguments[len(arguments)-1] == "strategies" {
templateID, err := strconv.Atoi(arguments[len(arguments)-2])
if err != nil {
setError(err.Error(), result)
}
o := orm.NewOrm()
var strategyIDs []int64
num, err := o.Raw("SELECT id FROM falcon_portal.strategy WHERE tpl_id = ? ORDER BY id ASC", templateID).QueryRows(&strategyIDs)
if err != nil {
setError(err.Error(), result)
} else if num > 0 {
countOfStrategies = int(num)
var strategies = make(map[string]interface{})
sids := ""
for key, strategyID := range strategyIDs {
sid := strconv.Itoa(int(strategyID))
item := map[string]string{}
item["templateID"] = strconv.Itoa(templateID)
item["strategyID"] = sid
strategies[sid] = item
if key == 0 {
sids = sid
} else {
sids += ", " + sid
}
}
sqlcmd := "SELECT strategy_id, name, value FROM falcon_portal.tags WHERE strategy_id IN ("
sqlcmd += sids
sqlcmd += ") ORDER BY strategy_id ASC"
var tags []*Tag
_, err = o.Raw(sqlcmd).QueryRows(&tags)
if err != nil {
setError(err.Error(), result)
} else {
for _, tag := range tags {
strategyID := strconv.Itoa(int(tag.StrategyId))
strategy := strategies[strategyID].(map[string]string)
strategy["tagName"] = tag.Name
strategy["tagValue"] = tag.Value
strategies[strategyID] = strategy
}
}
for _, strategy := range strategies {
items = append(items, strategy)
}
}
}
result["items"] = items
result["count"] = countOfStrategies
var nodes = make(map[string]interface{})
nodes["result"] = result
setResponse(rw, nodes)
}
func getPlatformJSON(nodes map[string]interface{}, result map[string]interface{}) {
fcname := g.Config().Api.Name
fctoken := getFctoken()
url := g.Config().Api.Map + "/fcname/" + fcname + "/fctoken/" + fctoken
url += "/show_active/yes/hostname/yes/pop_id/yes/ip/yes.json"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
setError(err.Error(), result)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
setError(err.Error(), result)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
if err := json.Unmarshal(body, &nodes); err != nil {
setError(err.Error(), result)
}
}
func setGraphQueries(hostnames []string, hostnamesExisted []string, versions map[string]string, result map[string]interface{}) []*cmodel.GraphLastParam {
var queries []*cmodel.GraphLastParam
o := orm.NewOrm()
var hosts []*Host
hostnamesStr := strings.Join(hostnames, "','")
sqlcommand := "SELECT hostname, agent_version FROM falcon_portal.host WHERE hostname IN ('"
sqlcommand += hostnamesStr + "') ORDER BY hostname ASC"
_, err := o.Raw(sqlcommand).QueryRows(&hosts)
if err != nil {
setError(err.Error(), result)
} else {
for _, host := range hosts {
var query cmodel.GraphLastParam
if !strings.Contains(host.Hostname, ".") && strings.Contains(host.Hostname, "-") {
hostnamesExisted = append(hostnamesExisted, host.Hostname)
versions[host.Hostname] = host.Agent_version
query.Endpoint = host.Hostname
query.Counter = "agent.alive"
queries = append(queries, &query)
}
}
}
return queries
}
func queryAgentAlive(queries []*cmodel.GraphLastParam, reqHost string, result map[string]interface{}) []cmodel.GraphLastResp {
data := []cmodel.GraphLastResp{}
if len(queries) > 0 {
if strings.Index(g.Config().Api.Query, reqHost) >= 0 {
proc.LastRequestCnt.Incr()
for _, param := range queries {
if param == nil {
continue
}
last, err := graph.Last(*param)
if err != nil {
log.Printf("graph.last fail, resp: %v, err: %v", last, err)
}
if last == nil {
continue
}
data = append(data, *last)
}
proc.LastRequestItemCnt.IncrBy(int64(len(data)))
} else {
s, err := json.Marshal(queries)
if err != nil {
setError(err.Error(), result)
}
url := g.Config().Api.Query + "/graph/last"
reqPost, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(s)))
if err != nil {
setError(err.Error(), result)
}
reqPost.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(reqPost)
if err != nil {
setError(err.Error(), result)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(body, &data)
if err != nil {
setError(err.Error(), result)
}
}
}
return data
}
func classifyAgentAliveResponse(data []cmodel.GraphLastResp, hostnamesExisted []string, versions map[string]string, result map[string]interface{}) {
name := ""
version := ""
status := ""
alive := 0
var diff int64
var timestamp int64
items := map[string]interface{}{}
for key, row := range data {
name = row.Endpoint
alive = 0
diff = 0
timestamp = 0
status = "error"
if name == "" {
name = hostnamesExisted[key]
} else {
alive = int(row.Value.Value)
timestamp = row.Value.Timestamp
now := time.Now().Unix()
diff = now - timestamp
}
version = versions[name]
if alive > 0 {
if diff > 3600 {
status = "warm"
} else {
status = "normal"
}
}
item := map[string]interface{}{}
item["version"] = version
item["status"] = status
items[name] = item
}
result["items"] = items
}
func getAnomalies(errorHosts []interface{}, result map[string]interface{}) map[string]interface{} {
anomalies := map[string]interface{}{}
pop_ids := map[string]string{}
for _, errorHost := range errorHosts {
pop_id := errorHost.(map[string]string)["pop_id"]
pop_ids[pop_id] = pop_id
}
arr := []string{}
for _, pop_id := range pop_ids {
arr = append(arr, pop_id)
}
sort.Strings(arr)
sqlcmd := "SELECT pop_id, name, province, city FROM grafana.idc WHERE pop_id IN ('"
sqlcmd += strings.Join(arr, "','") + "')"
idcs := map[string]interface{}{}
var rows []orm.Params
o := orm.NewOrm()
o.Using("grafana")
_, err := o.Raw(sqlcmd).Values(&rows)
if err != nil {
setError(err.Error(), result)
} else {
for _, row := range rows {
idc := map[string]string{
"idc": row["name"].(string),
"province": row["province"].(string),
"city": row["city"].(string),
}
idcs[row["pop_id"].(string)] = idc
}
}
anomalies2 := map[string]interface{}{}
for _, errorHost := range errorHosts {
pop_id := errorHost.(map[string]string)["pop_id"]
if idc, ok := idcs[pop_id]; ok {
errorHost.(map[string]string)["idc"] = idc.(map[string]string)["idc"]
errorHost.(map[string]string)["city"] = idc.(map[string]string)["city"]
provinceName := idc.(map[string]string)["province"]
if provinceName == "特区" {
provinceName = idc.(map[string]string)["city"]
}
errorHost.(map[string]string)["province"] = provinceName
delete(errorHost.(map[string]string), "pop_id")
if province, ok := anomalies2[provinceName]; ok {
province = append(province.([]map[string]string), errorHost.(map[string]string))
anomalies2[provinceName] = province
} else {
anomalies2[provinceName] = []map[string]string{
errorHost.(map[string]string),
}
}
} else {
errorHost.(map[string]string)["idc"] = ""
errorHost.(map[string]string)["city"] = ""
errorHost.(map[string]string)["province"] = ""
}
}
for provinceName, hosts := range anomalies2 {
count := len(hosts.([]map[string]string))
anomalies[provinceName] = map[string]interface{}{
"count": count,
"hosts": hosts,
}
}
return anomalies
}
func completeAgentAliveData(groups map[string]interface{}, groupNames []string, result map[string]interface{}) {
errorHosts := []interface{}{}
platforms := []interface{}{}
count := map[string]int{}
countOfNormalSum := 0
countOfWarnSum := 0
countOfErrorSum := 0
countOfMissSum := 0
countOfDeactivatedSum := 0
hostId := 1
name := ""
activate := ""
version := ""
pop_id := ""
status := ""
items := result["items"].(map[string]interface{})
for _, groupName := range groupNames {
platform := map[string]interface{}{}
hosts := []interface{}{}
count := map[string]int{}
countOfNormal := 0
countOfWarn := 0
countOfError := 0
countOfMiss := 0
countOfDeactivated := 0
group := groups[groupName].([]interface{})
for _, agent := range group {
name = agent.(map[string]interface{})["name"].(string)
activate = agent.(map[string]interface{})["activate"].(string)
pop_id = agent.(map[string]interface{})["pop_id"].(string)
status = ""
version = ""
if activate == "1" {
if item, ok := items[name]; ok {
status = item.(map[string]interface{})["status"].(string)
version = item.(map[string]interface{})["version"].(string)
} else {
status = "miss"
countOfMiss++
}
} else {
status = "deactivated"
countOfDeactivated++
}
if status == "normal" {
countOfNormal++
} else if status == "warm" {
countOfWarn++
} else if status == "error" {
countOfError++
}
host := map[string]string{
"id": strconv.Itoa(hostId),
"name": name,
"platform": groupName,
"pop_id": pop_id,
"status": status,
"version": version,
}
if host["status"] == "error" {
errorHosts = append(errorHosts, host)
} else {
delete(host, "pop_id")
}
hosts = append(hosts, host)
hostId++
}
count["normal"] = countOfNormal
count["warn"] = countOfWarn
count["error"] = countOfError
count["miss"] = countOfMiss
count["deactivated"] = countOfDeactivated
count["all"] = countOfNormal + countOfWarn + countOfError + countOfMiss + countOfDeactivated
platform["platformName"] = groupName
platform["platformCount"] = count
platform["hosts"] = hosts
platforms = append(platforms, platform)
countOfNormalSum += countOfNormal
countOfWarnSum += countOfWarn
countOfErrorSum += countOfError
countOfMissSum += countOfMiss
countOfDeactivatedSum += countOfDeactivated
}
count["normal"] = countOfNormalSum
count["warn"] = countOfWarnSum
count["error"] = countOfErrorSum
count["miss"] = countOfMissSum
count["deactivated"] = countOfDeactivatedSum
count["all"] = countOfNormalSum + countOfWarnSum + countOfErrorSum + countOfMissSum + countOfDeactivatedSum
result["count"] = count
result["anomalies"] = getAnomalies(errorHosts, result)
result["items"] = platforms
}
func getPlatforms(rw http.ResponseWriter, req *http.Request) {
var nodes = make(map[string]interface{})
errors := []string{}
var result = make(map[string]interface{})
result["error"] = errors
getPlatformJSON(nodes, result)
groups := map[string]interface{}{}
groupNames := []string{}
hostnames := []string{}
hostnamesMap := map[string]int{}
if nodes["status"] != nil && int(nodes["status"].(float64)) == 1 {
hostname := ""
for _, platform := range nodes["result"].([]interface{}) {
groupName := platform.(map[string]interface{})["platform"].(string)
groupNames = append(groupNames, groupName)
group := []interface{}{}
for _, device := range platform.(map[string]interface{})["ip_list"].([]interface{}) {
hostname = device.(map[string]interface{})["hostname"].(string)
if _, ok := hostnamesMap[hostname]; !ok {
hostnames = append(hostnames, hostname)
host := map[string]interface{}{
"name": hostname,
"activate": device.(map[string]interface{})["ip_status"].(string),
"pop_id": device.(map[string]interface{})["pop_id"].(string),
}
group = append(group, host)
hostnamesMap[hostname] = 1
}
}
groups[groupName] = group
}
sort.Strings(hostnames)
sort.Strings(groupNames)
hostnamesExisted := []string{}
var versions = make(map[string]string)
queries := setGraphQueries(hostnames, hostnamesExisted, versions, result)
data := queryAgentAlive(queries, req.Host, result)
classifyAgentAliveResponse(data, hostnamesExisted, versions, result)
completeAgentAliveData(groups, groupNames, result)
}
if _, ok := nodes["info"]; ok {
delete(nodes, "info")
}
if _, ok := nodes["status"]; ok {
delete(nodes, "status")
}
nodes["result"] = result
rw.Header().Set("Access-Control-Allow-Origin", "*")
setResponse(rw, nodes)
}
func getMetricsByMetricType(metricType string) []string {
metrics := []string{}
if metricType == "bandwidths" {
metrics = []string{
"net.if.in.bits/iface=eth_all",
"net.if.out.bits/iface=eth_all",
}
} else if metricType == "cpu" {
metrics = []string{
"cpu.idle",
"cpu.system",
"cpu.softirq",
"cpu.user",
}
} else if metricType == "resources" {
metrics = []string{
"cpu.idle",
"disk.io.util.max",
"load.1min",
"mem.memfree.percent",
"mem.swapused.percent",
"vmstat.procs.b",
"vmstat.procs.r",
}
} else if metricType == "services" {
metrics = []string{
"http.response.time",
"https.response.time",
"ss.close.wait",
"ss.established",
"ss.syn.recv",
"vfcc.squid.response.time",
}
} else if metricType == "all" || metricType == "aggregate" {
metrics = []string{
"net.if.in.bits/iface=eth_all",
"net.if.out.bits/iface=eth_all",
"cpu.idle",
"disk.io.util.max",
"load.1min",
"mem.memfree.percent",
"mem.swapused.percent",
"http.response.time",
"https.response.time",
"ss.close.wait",
"ss.established",
"ss.syn.recv",
"vfcc.squid.response.time",
"vmstat.procs.b",
"vmstat.procs.r",
}
}
return metrics
}
func convertDurationToPoint(duration string, result map[string]interface{}) (timestampFrom int64, timestampTo int64) {
if strings.Index(duration, ",") > -1 {
var e error
timestampFrom, e = strconv.ParseInt(strings.Split(duration, ",")[0], 10, 64)
if e != nil {
setError(e.Error(), result)
}
timestampTo, e = strconv.ParseInt(strings.Split(duration, ",")[1], 10, 64)
if e != nil {
setError(e.Error(), result)
}
if timestampFrom >= timestampTo {
setError("Value of timestampFrom should be less than value of timestampTo.", result)
}
if timestampTo > time.Now().Unix() {
setError("Value of timestampTo should be equal to or less than value of now.", result)
}
} else if strings.Index(duration, "d") > -1 || strings.Index(duration, "min") > -1 {
unit := ""
seconds := int64(0)
if strings.Index(duration, "d") > -1 {
unit = "d"
seconds = int64(86400)
} else {
unit = "min"
seconds = int64(60)
}
multiplier, err := strconv.Atoi(strings.Split(duration, unit)[0])
if err != nil {
setError(err.Error(), result)
}
offset := int64(multiplier) * seconds
now := time.Now().Unix()
timestampFrom = now - offset
timestampTo = now
}
return
}
func getGraphQueryResponse(metrics []string, duration string, hostnames []string, result map[string]interface{}) []*cmodel.GraphQueryResponse {
data := []*cmodel.GraphQueryResponse{}
start, end := convertDurationToPoint(duration, result)
proc.HistoryRequestCnt.Incr()
for _, hostname := range hostnames {
for _, metric := range metrics {
request := cmodel.GraphQueryParam{
Start: start,
End: end,
ConsolFun: "AVERAGE",
Endpoint: hostname,
Counter: metric,
}
response, err := graph.QueryOne(request)
if err != nil {
setError("graph.queryOne fail, "+err.Error(), result)
}
if result == nil {
continue
}
data = append(data, response)
}
}
proc.HistoryResponseCounterCnt.IncrBy(int64(len(data)))
for _, item := range data {
proc.HistoryResponseItemCnt.IncrBy(int64(len(item.Values)))
}
return data
}
func getHostMetricValues(rw http.ResponseWriter, req *http.Request) {
errors := []string{}
var result = make(map[string]interface{})
result["error"] = errors
items := []interface{}{}
arguments := strings.Split(req.URL.Path, "/")
hostname := ""
metricType := ""
duration := ""
if len(arguments) == 6 {
hostname = arguments[len(arguments)-3]
metricType = arguments[len(arguments)-2]
duration = arguments[len(arguments)-1]
} else if len(arguments) == 5 {
hostname = arguments[len(arguments)-2]
metricType = arguments[len(arguments)-1]
duration = "3d"
}
metrics := getMetricsByMetricType(metricType)
if len(metrics) > 0 && strings.Index(duration, "d") > -1 {
data := getGraphQueryResponse(metrics, duration, []string{hostname}, result)
for _, series := range data {
values := []interface{}{}
for _, rrdObj := range series.Values {
value := []interface{}{
rrdObj.Timestamp * 1000,
rrdObj.Value,
}
values = append(values, value)
}
item := map[string]interface{}{
"host": series.Endpoint,
"metric": series.Counter,
"data": values,
}
items = append(items, item)
}
}
result["items"] = items
var nodes = make(map[string]interface{})
nodes["result"] = result
rw.Header().Set("Access-Control-Allow-Origin", "*")
setResponse(rw, nodes)
}
func getExistedHostnames(hostnames []string, result map[string]interface{}) []string {
hostnamesExisted := []string{}
o := orm.NewOrm()
var hosts []*Host
hostnamesStr := strings.Join(hostnames, "','")
sqlcommand := "SELECT hostname, agent_version FROM falcon_portal.host WHERE hostname IN ('"
sqlcommand += hostnamesStr + "') ORDER BY hostname ASC"
_, err := o.Raw(sqlcommand).QueryRows(&hosts)
if err != nil {
setError(err.Error(), result)