This repository has been archived by the owner on Dec 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
database_query.go
684 lines (612 loc) · 16.4 KB
/
database_query.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
// Copyright 2017 Google Inc. All Rights Reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package database
import (
"compress/gzip"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/golang/glog"
"github.com/golang/protobuf/proto"
"github.com/google/tflow2/avltree"
"github.com/google/tflow2/convert"
"github.com/google/tflow2/netflow"
"github.com/google/tflow2/stats"
)
// BreakDownMap defines by what fields data should be broken down in a query
type BreakDownMap struct {
Router bool
Family bool
SrcAddr bool
DstAddr bool
Protocol bool
IntIn bool
IntOut bool
NextHop bool
SrcAsn bool
DstAsn bool
NextHopAsn bool
SrcPfx bool
DstPfx bool
SrcPort bool
DstPort bool
}
// Condition represents a query condition
type Condition struct {
Field int
Operator int
Operand []byte
}
// ConditionExt is external representation of a query condition
type ConditionExt struct {
Field int
Operator int
Operand string
}
// Conditions represents a set of conditions of a query
type Conditions []Condition
// ConditionsExt is external representation of conditions of a query
type ConditionsExt []ConditionExt
// QueryExt represents a query in the way it is received from the frontend
type QueryExt struct {
Cond ConditionsExt
Breakdown BreakDownMap
TopN int
}
// Query is the internal representation of a query
type Query struct {
Cond Conditions
Breakdown BreakDownMap
TopN int
}
type concurrentResSum struct {
Values map[string]uint64
Lock sync.Mutex
}
// These constants are used in communication with the frontend
const (
OpEqual = 0
OpUnequal = 1
OpSmaller = 2
OpGreater = 3
FieldTimestamp = 0
FieldRouter = 1
FieldSrcAddr = 2
FieldDstAddr = 3
FieldProtocol = 4
FieldIntIn = 5
FieldIntOut = 6
FieldNextHop = 7
FieldSrcAs = 8
FieldDstAs = 9
FieldNextHopAs = 10
FieldSrcPfx = 11
FieldDstPfx = 12
FieldSrcPort = 13
FieldDstPort = 14
)
// translateQuery translates a query from external representation to internal representaion
func translateQuery(e QueryExt) (Query, error) {
var q Query
q.Breakdown = e.Breakdown
q.TopN = e.TopN
for _, c := range e.Cond {
var operand []byte
switch c.Field {
case FieldTimestamp:
op, err := strconv.Atoi(c.Operand)
if err != nil {
return q, err
}
operand = convert.Int64Byte(int64(op))
case FieldProtocol:
op, err := strconv.Atoi(c.Operand)
if err != nil {
return q, err
}
operand = convert.Uint16Byte(uint16(op))
case FieldSrcPort:
op, err := strconv.Atoi(c.Operand)
if err != nil {
return q, err
}
operand = convert.Uint16Byte(uint16(op))
case FieldDstPort:
op, err := strconv.Atoi(c.Operand)
if err != nil {
return q, err
}
operand = convert.Uint16Byte(uint16(op))
case FieldSrcAddr:
operand = convert.IPByteSlice(c.Operand)
case FieldDstAddr:
operand = convert.IPByteSlice(c.Operand)
case FieldRouter:
operand = convert.IPByteSlice(c.Operand)
case FieldIntIn:
op, err := strconv.Atoi(c.Operand)
if err != nil {
return q, err
}
operand = convert.Uint16Byte(uint16(op))
case FieldIntOut:
op, err := strconv.Atoi(c.Operand)
if err != nil {
return q, err
}
operand = convert.Uint16Byte(uint16(op))
case FieldNextHop:
operand = convert.IPByteSlice(c.Operand)
case FieldSrcAs:
op, err := strconv.Atoi(c.Operand)
if err != nil {
return q, err
}
operand = convert.Uint32Byte(uint32(op))
case FieldDstAs:
op, err := strconv.Atoi(c.Operand)
if err != nil {
return q, err
}
operand = convert.Uint32Byte(uint32(op))
case FieldNextHopAs:
op, err := strconv.Atoi(c.Operand)
if err != nil {
return q, err
}
operand = convert.Uint32Byte(uint32(op))
case FieldSrcPfx:
_, pfx, err := net.ParseCIDR(string(c.Operand))
if err != nil {
return q, err
}
operand = []byte(pfx.String())
case FieldDstPfx:
_, pfx, err := net.ParseCIDR(string(c.Operand))
if err != nil {
return q, err
}
operand = []byte(pfx.String())
}
q.Cond = append(q.Cond, Condition{
Field: c.Field,
Operator: c.Operator,
Operand: operand,
})
}
return q, nil
}
// loadFromDisc loads netflow data from disk into in memory data structure
func (fdb *FlowDatabase) loadFromDisc(ts int64, router string, query Query, ch chan map[string]uint64, resSum *concurrentResSum) {
res := avltree.New()
ymd := fmt.Sprintf("%04d-%02d-%02d", time.Unix(ts, 0).Year(), time.Unix(ts, 0).Month(), time.Unix(ts, 0).Day())
filename := fmt.Sprintf("%s/%s/nf-%d-%s.tflow2.pb.gzip", fdb.storage, ymd, ts, router)
fh, err := os.Open(filename)
if err != nil {
if fdb.debug > 0 {
glog.Errorf("unable to open file: %v", err)
}
ch <- nil
return
}
if fdb.debug > 1 {
glog.Infof("sucessfully opened file: %s", filename)
}
defer fh.Close()
gz, err := gzip.NewReader(fh)
if err != nil {
glog.Errorf("unable to create gzip reader: %v", err)
ch <- nil
return
}
defer gz.Close()
buffer, err := ioutil.ReadAll(gz)
if err != nil {
glog.Errorf("unable to gunzip: %v", err)
ch <- nil
return
}
// Unmarshal protobuf
flows := netflow.Flows{}
err = proto.Unmarshal(buffer, &flows)
if err != nil {
glog.Errorf("unable to unmarshal protobuf: %v", err)
ch <- nil
return
}
if fdb.debug > 1 {
glog.Infof("file %s contains %d flows", filename, len(flows.Flows))
}
// Validate flows and add them to res tree
for _, fl := range flows.Flows {
if validateFlow(fl, query) {
res.Insert(fl, fl, ptrIsSmaller)
}
}
// Breakdown
resTime := make(map[string]uint64)
res.Each(breakdown, query.Breakdown, resSum, resTime)
ch <- resTime
}
func validateFlow(fl *netflow.Flow, query Query) bool {
for _, c := range query.Cond {
switch c.Field {
case FieldTimestamp:
continue
case FieldRouter:
continue
case FieldProtocol:
if fl.Protocol != uint32(convert.Uint16b(c.Operand)) {
return false
}
continue
case FieldSrcAddr:
if net.IP(fl.SrcAddr).String() != net.IP(c.Operand).String() {
return false
}
continue
case FieldDstAddr:
if net.IP(fl.DstAddr).String() != net.IP(c.Operand).String() {
return false
}
continue
case FieldIntIn:
if fl.IntIn != uint32(convert.Uint16b(c.Operand)) {
return false
}
continue
case FieldIntOut:
if fl.IntOut != uint32(convert.Uint16b(c.Operand)) {
return false
}
continue
case FieldNextHop:
if net.IP(fl.NextHop).String() != net.IP(c.Operand).String() {
return false
}
continue
case FieldSrcAs:
if fl.SrcAs != convert.Uint32b(c.Operand) {
return false
}
continue
case FieldDstAs:
if fl.DstAs != convert.Uint32b(c.Operand) {
return false
}
continue
case FieldNextHopAs:
if fl.NextHopAs != convert.Uint32b(c.Operand) {
return false
}
case FieldSrcPort:
if fl.SrcPort != uint32(convert.Uint16b(c.Operand)) {
return false
}
continue
case FieldDstPort:
if fl.DstPort != uint32(convert.Uint16b(c.Operand)) {
return false
}
continue
case FieldSrcPfx:
if fl.SrcPfx.String() != string(c.Operand) {
return false
}
continue
case FieldDstPfx:
if fl.DstPfx.String() != string(c.Operand) {
return false
}
continue
}
}
return true
}
// RunQuery executes a query and returns sends the result as JSON on `w`
func (fdb *FlowDatabase) RunQuery(query string) ([][]string, error) {
queryStart := time.Now()
stats.GlobalStats.Queries++
var qe QueryExt
err := json.Unmarshal([]byte(query), &qe)
if err != nil {
glog.Warningf("Unable unmarshal json query: %s", query)
return nil, err
}
q, err := translateQuery(qe)
if err != nil {
glog.Warningf("Unable to translate query")
return nil, err
}
// Determine router
rtr := ""
for _, c := range q.Cond {
if c.Field == FieldRouter {
iprtr := net.IP(c.Operand)
rtr = iprtr.String()
}
}
if rtr == "" {
glog.Warningf("Router is mandatory cirteria")
return nil, err
}
var start int64
end := time.Now().Unix()
// Determine time window
for _, c := range q.Cond {
if c.Field != FieldTimestamp {
continue
}
switch c.Operator {
case OpGreater:
start = int64(convert.Uint64b(c.Operand))
case OpSmaller:
end = int64(convert.Uint64b(c.Operand))
}
}
// Allign start point to `aggregation` raster
start = start - (start % fdb.aggregation)
resSum := &concurrentResSum{}
resSum.Values = make(map[string]uint64)
resTime := make(map[int64]map[string]uint64)
resChannels := make(map[int64]chan map[string]uint64)
for ts := start; ts < end; ts += fdb.aggregation {
resChannels[ts] = make(chan map[string]uint64)
fdb.lock.RLock()
if _, ok := fdb.flows[ts]; !ok {
fdb.lock.RUnlock()
go fdb.loadFromDisc(ts, rtr, q, resChannels[ts], resSum)
fdb.lock.RLock()
if _, ok := fdb.flows[ts]; !ok {
fdb.lock.RUnlock()
continue
}
}
// candidates keeps a list of all trees that fulfill the queries criteria
candidates := make([]*avltree.Tree, 0)
for _, c := range q.Cond {
if fdb.debug > 1 {
glog.Infof("Adding tree to cancidates list: Field: %d, Value: %d", c.Field, c.Operand)
}
switch c.Field {
case FieldTimestamp:
continue
case FieldRouter:
continue
case FieldProtocol:
candidates = append(candidates, fdb.flows[ts][rtr].Protocol[uint32(convert.Uint16b(c.Operand))])
case FieldSrcAddr:
candidates = append(candidates, fdb.flows[ts][rtr].SrcAddr[net.IP(c.Operand).String()])
case FieldDstAddr:
candidates = append(candidates, fdb.flows[ts][rtr].DstAddr[net.IP(c.Operand).String()])
case FieldIntIn:
candidates = append(candidates, fdb.flows[ts][rtr].IntIn[uint32(convert.Uint16b(c.Operand))])
case FieldIntOut:
candidates = append(candidates, fdb.flows[ts][rtr].IntOut[uint32(convert.Uint16b(c.Operand))])
case FieldNextHop:
candidates = append(candidates, fdb.flows[ts][rtr].NextHop[net.IP(c.Operand).String()])
case FieldSrcAs:
candidates = append(candidates, fdb.flows[ts][rtr].SrcAs[convert.Uint32b(c.Operand)])
case FieldDstAs:
candidates = append(candidates, fdb.flows[ts][rtr].DstAs[convert.Uint32b(c.Operand)])
case FieldNextHopAs:
candidates = append(candidates, fdb.flows[ts][rtr].NextHopAs[convert.Uint32b(c.Operand)])
case FieldSrcPort:
candidates = append(candidates, fdb.flows[ts][rtr].SrcPort[uint32(convert.Uint16b(c.Operand))])
case FieldDstPort:
candidates = append(candidates, fdb.flows[ts][rtr].DstPort[uint32(convert.Uint16b(c.Operand))])
case FieldSrcPfx:
candidates = append(candidates, fdb.flows[ts][rtr].SrcPfx[string(c.Operand)])
case FieldDstPfx:
candidates = append(candidates, fdb.flows[ts][rtr].DstPfx[string(c.Operand)])
}
}
if len(candidates) == 0 {
candidates = append(candidates, fdb.flows[ts][rtr].Any[0])
}
fdb.lock.RUnlock()
go func(candidates []*avltree.Tree, ch chan map[string]uint64, ts int64) {
if fdb.debug > 1 {
glog.Infof("candidate trees: %d (%d)", len(candidates), ts)
}
// Find common elements of candidate trees
res := avltree.Intersection(candidates)
if res == nil {
glog.Warningf("Interseciton Result was empty!")
res = fdb.flows[ts][rtr].Any[0]
}
// Breakdown
resTime := make(map[string]uint64)
res.Each(breakdown, q.Breakdown, resSum, resTime)
ch <- resTime
}(candidates, resChannels[ts], ts)
}
// Reading results from go routines
glog.Infof("Awaiting results from go routines")
for ts := start; ts < end; ts += fdb.aggregation {
glog.Infof("Waiting for results for ts %d", ts)
resTime[ts] = <-resChannels[ts]
}
glog.Infof("Done reading results")
// Build list of all keys
keys := make([]string, 0)
// Build Tree Bytes -> Key to allow efficient finding of top n flows
var btree = avltree.New()
for k, b := range resSum.Values {
keys = append(keys, k)
btree.Insert(b, k, uint64IsSmaller)
}
// Find top n keys
topKeysList := btree.TopN(q.TopN)
topKeys := make(map[string]int)
for _, v := range topKeysList {
topKeys[v.(string)] = 1
}
// Find all timestamps we have and get them sorted
tsTree := avltree.New()
for ts := range resTime {
tsTree.Insert(ts, ts, int64IsSmaller)
}
timestamps := tsTree.Dump()
queryResult := make([][]string, 0)
// Construct table header
headLine := make([]string, 0)
headLine = append(headLine, "Time")
for _, k := range topKeysList {
headLine = append(headLine, k.(string))
}
headLine = append(headLine, "Rest")
queryResult = append(queryResult, headLine)
for _, ts := range timestamps {
line := make([]string, 0)
t := time.Unix(ts.(int64), 0)
line = append(line, fmt.Sprintf("%02d:%02d:%02d", t.Hour(), t.Minute(), t.Second()))
// Top flows
buckets := resTime[ts.(int64)]
for _, k := range topKeysList {
if _, ok := buckets[k.(string)]; !ok {
line = append(line, "0")
} else {
line = append(line, fmt.Sprintf("%d", buckets[k.(string)]/uint64(fdb.aggregation)*8*uint64(fdb.samplerate)))
}
}
// Rest
var rest uint64
for k, v := range buckets {
if _, ok := topKeys[k]; ok {
continue
}
rest += v
}
line = append(line, fmt.Sprintf("%d", rest))
queryResult = append(queryResult, line)
}
glog.Infof("Query %s took %d ns\n", query, time.Since(queryStart))
return queryResult, nil
}
// breakdown build all possible relevant keys of flows for flows in tree `node`
// and builds sums for each key in order to allow us to find top combinations
func breakdown(node *avltree.TreeNode, vals ...interface{}) {
if len(vals) != 3 {
glog.Errorf("lacking arguments")
return
}
bd := vals[0].(BreakDownMap)
sums := vals[1].(*concurrentResSum)
buckets := vals[2].(map[string]uint64)
fl := node.Value.(*netflow.Flow)
// Build format string to build key
srcAddr := "_"
dstAddr := "_"
protocol := "_"
intIn := "_"
intOut := "_"
nextHop := "_"
srcAs := "_"
dstAs := "_"
nextHopAs := "_"
srcPfx := "_"
dstPfx := "_"
srcPort := "_"
dstPort := "_"
if bd.SrcAddr {
srcAddr = fmt.Sprintf("Src:%s", net.IP(fl.SrcAddr).String())
}
if bd.DstAddr {
dstAddr = fmt.Sprintf("Dst:%s", net.IP(fl.DstAddr).String())
}
if bd.Protocol {
protocol = fmt.Sprintf("Proto:%d", fl.Protocol)
}
if bd.IntIn {
intIn = fmt.Sprintf("IntIn:%d", fl.IntIn)
}
if bd.IntOut {
intOut = fmt.Sprintf("IntOut:%d", fl.IntOut)
}
if bd.NextHop {
nextHop = fmt.Sprintf("NH:%s", net.IP(fl.NextHop).String())
}
if bd.SrcAsn {
srcAs = fmt.Sprintf("SrcAS:%d", fl.SrcAs)
}
if bd.DstAsn {
dstAs = fmt.Sprintf("DstAS:%d", fl.DstAs)
}
if bd.NextHopAsn {
nextHopAs = fmt.Sprintf("NH_AS:%d", fl.NextHopAs)
}
if bd.SrcPfx {
if fl.SrcPfx != nil {
pfx := net.IPNet{
IP: fl.SrcPfx.IP,
Mask: fl.SrcPfx.Mask,
}
srcPfx = fmt.Sprintf("SrcNet:%s", pfx.String())
} else {
srcPfx = fmt.Sprintf("SrcNet:0.0.0.0/0")
}
}
if bd.DstPfx {
if fl.DstPfx != nil {
pfx := net.IPNet{
IP: fl.DstPfx.IP,
Mask: fl.DstPfx.Mask,
}
dstPfx = fmt.Sprintf("DstNet:%s", pfx.String())
} else {
dstPfx = fmt.Sprintf("DstNet:0.0.0.0/0")
}
}
if bd.SrcPort {
srcPort = fmt.Sprintf("SrcPort:%d", fl.SrcPort)
}
if bd.DstPort {
dstPort = fmt.Sprintf("DstPort:%d", fl.DstPort)
}
// Build key
key := fmt.Sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s", srcAddr, dstAddr, protocol, intIn, intOut, nextHop, srcAs, dstAs, nextHopAs, srcPfx, dstPfx, srcPort, dstPort)
// Remove underscores from key
key = strings.Replace(key, ",_,", ",", -1)
key = strings.Replace(key, "_,", "", -1)
key = strings.Replace(key, ",_", "", -1)
// Remove leading and trailing commas
parts := strings.Split(key, "")
first := 0
last := len(parts) - 1
if parts[0] == "," {
first++
}
if parts[last] == "," {
last--
}
key = strings.Join(parts[first:last+1], "")
// Build sum for key
if _, ok := buckets[key]; !ok {
buckets[key] = fl.Size
} else {
buckets[key] += fl.Size
}
// Build overall sum
sums.Lock.Lock()
if _, ok := sums.Values[key]; !ok {
sums.Values[key] = fl.Size
} else {
sums.Values[key] += fl.Size
}
sums.Lock.Unlock()
}