/
graph_controller.go
456 lines (411 loc) · 11.2 KB
/
graph_controller.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
package graph
import (
"errors"
"fmt"
"strconv"
"strings"
"time"
log "github.com/Sirupsen/logrus"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
cmodel "github.com/open-falcon/falcon-plus/common/model"
h "github.com/open-falcon/falcon-plus/modules/api/app/helper"
m "github.com/open-falcon/falcon-plus/modules/api/app/model/graph"
"github.com/open-falcon/falcon-plus/modules/api/app/utils"
grh "github.com/open-falcon/falcon-plus/modules/api/graph"
tcache "github.com/toolkits/cache/localcache/timedcache"
"net/http"
)
var (
localStepCache = tcache.New(600*time.Second, 60*time.Second)
)
type APIEndpointObjGetInputs struct {
Endpoints []string `json:"endpoints" form:"endpoints"`
Deadline int64 `json:"deadline" form:"deadline"`
}
func EndpointObjGet(c *gin.Context) {
inputs := APIEndpointObjGetInputs{
Deadline: 0,
}
if err := c.Bind(&inputs); err != nil {
h.JSONR(c, badstatus, err)
return
}
if len(inputs.Endpoints) == 0 {
h.JSONR(c, http.StatusBadRequest, "endpoints missing")
return
}
var result []m.Endpoint = []m.Endpoint{}
dt := db.Graph.Table("endpoint").
Where("endpoint in (?) and ts >= ?", inputs.Endpoints, inputs.Deadline).
Scan(&result)
if dt.Error != nil {
h.JSONR(c, http.StatusBadRequest, dt.Error)
return
}
endpoints := []map[string]interface{}{}
for _, r := range result {
endpoints = append(endpoints, map[string]interface{}{"id": r.ID, "endpoint": r.Endpoint, "ts": r.Ts})
}
h.JSONR(c, endpoints)
}
type APIEndpointRegexpQueryInputs struct {
Q string `json:"q" form:"q"`
Label string `json:"tags" form:"tags"`
Limit int `json:"limit" form:"limit"`
Page int `json:"page" form:"page"`
}
func EndpointRegexpQuery(c *gin.Context) {
inputs := APIEndpointRegexpQueryInputs{
//set default is 500
Limit: 500,
Page: 1,
}
if err := c.Bind(&inputs); err != nil {
h.JSONR(c, badstatus, err)
return
}
if inputs.Q == "" && inputs.Label == "" {
h.JSONR(c, http.StatusBadRequest, "q and labels are all missing")
return
}
labels := []string{}
if inputs.Label != "" {
labels = strings.Split(inputs.Label, ",")
}
qs := []string{}
if inputs.Q != "" {
qs = strings.Split(inputs.Q, " ")
}
var offset int = 0
if inputs.Page > 1 {
offset = (inputs.Page - 1) * inputs.Limit
}
var endpoint []m.Endpoint
var endpoint_id []int
var dt *gorm.DB
if len(labels) != 0 {
dt = db.Graph.Table("endpoint_counter").Select("distinct endpoint_id")
for _, trem := range labels {
dt = dt.Where(" counter like ? ", "%"+strings.TrimSpace(trem)+"%")
}
dt = dt.Limit(inputs.Limit).Offset(offset).Pluck("distinct endpoint_id", &endpoint_id)
if dt.Error != nil {
h.JSONR(c, http.StatusBadRequest, dt.Error)
return
}
}
if len(qs) != 0 {
dt = db.Graph.Table("endpoint").
Select("endpoint, id")
if len(endpoint_id) != 0 {
dt = dt.Where("id in (?)", endpoint_id)
}
for _, trem := range qs {
dt = dt.Where(" endpoint regexp ? ", strings.TrimSpace(trem))
}
dt.Limit(inputs.Limit).Offset(offset).Scan(&endpoint)
} else if len(endpoint_id) != 0 {
dt = db.Graph.Table("endpoint").
Select("endpoint, id").
Where("id in (?)", endpoint_id).
Scan(&endpoint)
}
if dt.Error != nil {
h.JSONR(c, http.StatusBadRequest, dt.Error)
return
}
endpoints := []map[string]interface{}{}
for _, e := range endpoint {
endpoints = append(endpoints, map[string]interface{}{"id": e.ID, "endpoint": e.Endpoint})
}
h.JSONR(c, endpoints)
}
func EndpointCounterRegexpQuery(c *gin.Context) {
eid := c.DefaultQuery("eid", "")
metricQuery := c.DefaultQuery("metricQuery", ".+")
limitTmp := c.DefaultQuery("limit", "500")
limit, err := strconv.Atoi(limitTmp)
if err != nil {
h.JSONR(c, http.StatusBadRequest, err)
return
}
pageTmp := c.DefaultQuery("page", "1")
page, err := strconv.Atoi(pageTmp)
if err != nil {
h.JSONR(c, http.StatusBadRequest, err)
return
}
var offset int = 0
if page > 1 {
offset = (page - 1) * limit
}
if eid == "" {
h.JSONR(c, http.StatusBadRequest, "eid is missing")
} else {
eids := utils.ConverIntStringToList(eid)
if eids == "" {
h.JSONR(c, http.StatusBadRequest, "input error, please check your input info.")
return
} else {
eids = fmt.Sprintf("(%s)", eids)
}
var counters []m.EndpointCounter
dt := db.Graph.Table("endpoint_counter").Select("endpoint_id, counter, step, type").Where(fmt.Sprintf("endpoint_id IN %s", eids))
if metricQuery != "" {
qs := strings.Split(metricQuery, " ")
if len(qs) > 0 {
for _, term := range qs {
dt = dt.Where("counter regexp ?", strings.TrimSpace(term))
}
}
}
dt = dt.Limit(limit).Offset(offset).Scan(&counters)
if dt.Error != nil {
h.JSONR(c, http.StatusBadRequest, dt.Error)
return
}
countersResp := []interface{}{}
for _, c := range counters {
countersResp = append(countersResp, map[string]interface{}{
"endpoint_id": c.EndpointID,
"counter": c.Counter,
"step": c.Step,
"type": c.Type,
})
}
h.JSONR(c, countersResp)
}
return
}
type APIQueryGraphDrawData struct {
HostNames []string `json:"hostnames" binding:"required"`
Counters []string `json:"counters" binding:"required"`
ConsolFun string `json:"consol_fun" binding:"required"`
StartTime int64 `json:"start_time" binding:"required"`
EndTime int64 `json:"end_time" binding:"required"`
Step int `json:"step"`
}
func QueryGraphDrawData(c *gin.Context) {
var inputs APIQueryGraphDrawData
var err error
if err = c.Bind(&inputs); err != nil {
h.JSONR(c, badstatus, err)
return
}
respData := []*cmodel.GraphQueryResponse{}
for _, host := range inputs.HostNames {
for _, counter := range inputs.Counters {
var step int
if inputs.Step > 0 {
step = inputs.Step
} else {
step, err = getCounterStep(host, counter)
if err != nil {
continue
}
}
data, _ := fetchData(host, counter, inputs.ConsolFun, inputs.StartTime, inputs.EndTime, step)
respData = append(respData, data)
}
}
h.JSONR(c, respData)
}
func QueryGraphLastPoint(c *gin.Context) {
var inputs []cmodel.GraphLastParam
if err := c.Bind(&inputs); err != nil {
h.JSONR(c, badstatus, err)
return
}
respData := []*cmodel.GraphLastResp{}
for _, param := range inputs {
one_resp, err := grh.Last(param)
if err != nil {
log.Warn("query last point from graph fail:", err)
} else {
respData = append(respData, one_resp)
}
}
h.JSONR(c, respData)
}
func DeleteGraphEndpoint(c *gin.Context) {
var inputs []string = []string{}
if err := c.Bind(&inputs); err != nil {
h.JSONR(c, badstatus, err)
return
}
type DBRows struct {
Endpoint string
CounterId int
Counter string
Type string
Step int
}
rows := []DBRows{}
dt := db.Graph.Raw(
`select a.endpoint, b.id AS counter_id, b.counter, b.type, b.step from endpoint as a, endpoint_counter as b
where b.endpoint_id = a.id
AND a.endpoint in (?)`, inputs).Scan(&rows)
if dt.Error != nil {
h.JSONR(c, badstatus, dt.Error)
return
}
var affected_counter int64 = 0
var affected_endpoint int64 = 0
if len(rows) > 0 {
var params []*cmodel.GraphDeleteParam = []*cmodel.GraphDeleteParam{}
for _, row := range rows {
param := &cmodel.GraphDeleteParam{
Endpoint: row.Endpoint,
DsType: row.Type,
Step: row.Step,
}
fields := strings.SplitN(row.Counter, "/", 2)
if len(fields) == 1 {
param.Metric = fields[0]
} else if len(fields) == 2 {
param.Metric = fields[0]
param.Tags = fields[1]
} else {
log.Error("invalid counter", row.Counter)
continue
}
params = append(params, param)
}
grh.Delete(params)
}
tx := db.Graph.Begin()
if len(rows) > 0 {
var cids []int = make([]int, len(rows))
for i, row := range rows {
cids[i] = row.CounterId
}
dt = tx.Table("endpoint_counter").Where("id in (?)", cids).Delete(&m.EndpointCounter{})
if dt.Error != nil {
h.JSONR(c, badstatus, dt.Error)
tx.Rollback()
return
}
affected_counter = dt.RowsAffected
dt = tx.Exec(`delete from tag_endpoint where endpoint_id in
(select id from endpoint where endpoint in (?))`, inputs)
if dt.Error != nil {
h.JSONR(c, badstatus, dt.Error)
tx.Rollback()
return
}
}
dt = tx.Table("endpoint").Where("endpoint in (?)", inputs).Delete(&m.Endpoint{})
if dt.Error != nil {
h.JSONR(c, badstatus, dt.Error)
tx.Rollback()
return
}
affected_endpoint = dt.RowsAffected
tx.Commit()
h.JSONR(c, map[string]int64{
"affected_endpoint": affected_endpoint,
"affected_counter": affected_counter,
})
}
type APIGraphDeleteCounterInputs struct {
Endpoints []string `json:"endpoints" binding:"required"`
Counters []string `json:"counters" binding:"required"`
}
func DeleteGraphCounter(c *gin.Context) {
var inputs APIGraphDeleteCounterInputs = APIGraphDeleteCounterInputs{}
if err := c.Bind(&inputs); err != nil {
h.JSONR(c, badstatus, err)
return
}
type DBRows struct {
Endpoint string
CounterId int
Counter string
Type string
Step int
}
rows := []DBRows{}
dt := db.Graph.Raw(`select a.endpoint, b.id AS counter_id, b.counter, b.type, b.step from endpoint as a,
endpoint_counter as b
where b.endpoint_id = a.id
AND a.endpoint in (?)
AND b.counter in (?)`, inputs.Endpoints, inputs.Counters).Scan(&rows)
if dt.Error != nil {
h.JSONR(c, badstatus, dt.Error)
return
}
if len(rows) == 0 {
h.JSONR(c, map[string]int64{
"affected_counter": 0,
})
return
}
var params []*cmodel.GraphDeleteParam = []*cmodel.GraphDeleteParam{}
for _, row := range rows {
param := &cmodel.GraphDeleteParam{
Endpoint: row.Endpoint,
DsType: row.Type,
Step: row.Step,
}
fields := strings.SplitN(row.Counter, "/", 2)
if len(fields) == 1 {
param.Metric = fields[0]
} else if len(fields) == 2 {
param.Metric = fields[0]
param.Tags = fields[1]
} else {
log.Error("invalid counter", row.Counter)
continue
}
params = append(params, param)
}
grh.Delete(params)
tx := db.Graph.Begin()
var cids []int = make([]int, len(rows))
for i, row := range rows {
cids[i] = row.CounterId
}
dt = tx.Table("endpoint_counter").Where("id in (?)", cids).Delete(&m.EndpointCounter{})
if dt.Error != nil {
h.JSONR(c, badstatus, dt.Error)
tx.Rollback()
return
}
affected_counter := dt.RowsAffected
tx.Commit()
h.JSONR(c, map[string]int64{
"affected_counter": affected_counter,
})
}
func fetchData(hostname string, counter string, consolFun string, startTime int64, endTime int64, step int) (resp *cmodel.GraphQueryResponse, err error) {
qparm := grh.GenQParam(hostname, counter, consolFun, startTime, endTime, step)
// log.Debugf("qparm: %v", qparm)
resp, err = grh.QueryOne(qparm)
if err != nil {
log.Debugf("query graph got error: %s", err.Error())
}
return
}
func getCounterStep(endpoint, counter string) (step int, err error) {
cache_key := fmt.Sprintf("step:%s/%s", endpoint, counter)
s, found := localStepCache.Get(cache_key)
if found && s != nil {
step = s.(int)
return
}
var rows []int
dt := db.Graph.Raw(`select a.step from endpoint_counter as a, endpoint as b
where b.endpoint = ? and a.endpoint_id = b.id and a.counter = ? limit 1`, endpoint, counter).Scan(&rows)
if dt.Error != nil {
err = dt.Error
return
}
if len(rows) == 0 {
err = errors.New("empty result")
return
}
step = rows[0]
localStepCache.Set(cache_key, step, tcache.DefaultExpiration)
return
}