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
#![deny(missing_docs)]
extern crate int_compute;
extern crate libdata;
extern crate libflow;
#[cfg(test)]
extern crate libquery;
extern crate libutils;
extern crate futures;
#[cfg(test)]
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate slog;
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet};
use std::mem;
use std::rc::Rc;
use std::time::{Duration, SystemTime};
use futures::unsync::mpsc::UnboundedSender;
use slog::Logger;
use int_compute::{Event, Query as ComputeQuery};
use libdata::column::{FlowTags, RefHeaders, Tags};
use libdata::stats::Sizes as SizeStats;
use libflow::update::{Cork, Key, Status, Update};
use libflow::slice::{Flow as FlowSlice, Time as TimeSlice};
use libutils::tunable::{SLICE_INACTIVE_LIMIT, SLICE_KEEP_ENDED, SLICE_LENGTH_SECONDS};
struct FlowHead {
keys: BTreeSet<Key>,
tags: FlowTags,
last_stats: SizeStats,
current_stats: SizeStats,
status: Status,
start_time: SystemTime,
end_time: Option<SystemTime>,
inactive_for: u16,
started_here: bool,
}
impl FlowHead {
fn new(status: Status, current_stats: SizeStats) -> Self {
let stats = if status == Status::Start {
current_stats.clone()
} else {
SizeStats::default()
};
Self {
keys: BTreeSet::new(),
tags: FlowTags::new(Tags::new()),
last_stats: current_stats,
current_stats: stats,
status,
start_time: SystemTime::now(),
end_time: None,
inactive_for: 0,
started_here: true,
}
}
fn slice(&mut self, mut start: SystemTime, mut end: SystemTime) -> FlowSlice {
if self.start_time > start {
start = self.start_time;
}
if let Some(my_end) = self.end_time {
if my_end < end {
end = my_end;
}
}
let stats = self.current_stats.expand(start, end,
Duration::from_secs(SLICE_LENGTH_SECONDS),
self.started_here);
self.current_stats = SizeStats::default();
self.started_here = false;
FlowSlice::new(self.tags.clone(), stats)
}
}
pub struct Gather {
logger: Logger,
last_close: SystemTime,
flows: Vec<Rc<RefCell<FlowHead>>>,
index: BTreeMap<Key, Rc<RefCell<FlowHead>>>,
event_sink: UnboundedSender<Event>,
}
impl Gather {
pub fn new(logger: Logger, event_sink: UnboundedSender<Event>) -> Self {
debug!(logger, "Creating new gather component");
Gather {
logger,
last_close: SystemTime::now(),
flows: Vec::new(),
index: BTreeMap::new(),
event_sink,
}
}
pub fn update(&mut self, mut update: Update) {
trace!(self.logger, "Applying update {:?}", update);
let mut flow = None;
for key in &update.keys {
if let Some(found) = self.index.get(key) {
flow = Some(Rc::clone(found));
break;
} else if let Key::InternalHandle(_) = *key {
warn!(self.logger, "An internal key references non-existent flow, ignoring");
return;
}
}
let flow = flow.unwrap_or_else(|| {
trace!(self.logger, "Corresponding flow not found, adding a new one");
let stats = update.stats
.take()
.unwrap_or_default();
let new = FlowHead::new(update.status, stats);
let internal_key = Key::InternalHandle(new.tags.clone());
let flow_tags = new.tags.clone();
let flow = Rc::new(RefCell::new(new));
self.index.insert(internal_key, Rc::clone(&flow));
self.flows.push(Rc::clone(&flow));
drop(self.event_sink.unbounded_send(Event::FlowStarted(flow_tags)));
flow
});
let mut inner = flow.borrow_mut();
let key_cnt = update.keys.len();
for key in update.keys.drain(..) {
if let Key::InternalHandle(_) = key {
if key_cnt > 1 {
panic!("An update with internal handle and some other key");
}
} else if !inner.keys.contains(&key) {
inner.keys.insert(key.clone());
assert!(self.index.insert(key.clone(), Rc::clone(&flow)).is_none(),
"Collision on a key {:?}", key);
}
}
if inner.status != Status::End {
inner.status = update.status;
inner.inactive_for = 0;
}
if !update.tags.is_empty() {
let event = Event::FlowUpdated {
flow: inner.tags.clone(),
columns: update.tags
.idents()
.cloned()
.collect(),
};
inner.tags.borrow_mut().extend(update.tags);
drop(self.event_sink.unbounded_send(event));
}
if let Some(stats) = update.stats {
let mut last = stats.clone();
mem::swap(&mut last, &mut inner.last_stats);
if stats.sub_safe(&last) {
let difference = stats - last;
inner.current_stats += difference;
} else {
warn!(self.logger,
"Stats {:?} are smaller than previous snapshot {:?}",
stats,
last);
}
}
}
pub fn close_slice(&mut self) -> TimeSlice {
let logger = &self.logger;
let index = &mut self.index;
debug!(logger, "Closing a time slice");
let now = SystemTime::now();
let before = self.last_close;
self.last_close = now;
trace!(logger, "Flow head bookkeeping");
let sink = &self.event_sink;
self.flows.retain(|head| {
let mut h = head.borrow_mut();
if h.status == Status::Start {
trace!(logger, "Activating flow {:?}", h.tags);
h.status = Status::Ongoing;
h.inactive_for = 1;
true
} else if h.status == Status::Ongoing && h.inactive_for >= SLICE_INACTIVE_LIMIT {
trace!(logger, "Timing out an inactive flow {:?}", h.tags);
h.status = Status::End;
h.inactive_for = 1;
true
} else if h.status == Status::End && h.inactive_for >= SLICE_KEEP_ENDED {
trace!(logger, "Dropping an old flow {:?}", h.tags);
for key in &h.keys {
if let Key::InternalHandle(_) = *key {
panic!("Internal handle in list of keys");
}
index.remove(key);
}
index.remove(&Key::InternalHandle(h.tags.clone()));
drop(sink.unbounded_send(Event::FlowTerminated(h.tags.clone())));
false
} else {
h.inactive_for += 1;
true
}
});
trace!(logger, "Creating flow slices");
let slices = self.flows
.iter()
.filter_map(|head| {
let mut h = head.borrow_mut();
if h.status == Status::End && h.inactive_for > 1 {
None
} else {
let slice = h.slice(before, now);
Some(slice)
}
})
.collect();
TimeSlice::new(before, now, slices)
}
pub fn push_cork(&self, cork: Cork) {
drop(self.event_sink.unbounded_send(Event::CorkRequest(cork)));
}
}
impl ComputeQuery for Gather {
fn query<'a, 'b, 'r>(&'a self, filter: &'b RefHeaders<'b>)
-> Box<Iterator<Item = FlowTags> + 'r>
where
'a: 'r,
'b: 'r,
{
let iter = self.flows
.iter()
.filter_map(move |flow| {
let inner = flow.borrow();
let tags = inner.tags.borrow();
for (ident, values) in filter {
let value = tags.get(ident);
if !values.contains(&value) {
return None;
}
}
Some(inner.tags.clone())
});
Box::new(iter)
}
}
#[cfg(test)]
mod tests {
use futures::unsync::mpsc;
use futures::{Future, Stream};
use super::*;
use libutils;
use libdata::column::{Headers, Ident, Value, Type as ColumnType};
use libdata::flow::{Bytes, Count, Direction, IpProto};
use libdata::stats::Size as SizeStat;
use libflow::update;
use libquery::{InTimeInterval, ValueSrc};
struct TestData {
sizes: SizeStats,
}
impl TestData {
fn new() -> Self {
Self {
sizes: SizeStats {
dir_in: SizeStat {
packets: Count(2),
size: Bytes(1024),
},
dir_out: SizeStat {
packets: Count(3),
size: Bytes(512),
},
}
}
}
}
#[test]
fn flow_head() {
let data = TestData::new();
let start = SystemTime::now();
let head_aged = FlowHead::new(Status::Ongoing, data.sizes.clone());
assert!(head_aged.keys.is_empty());
assert_eq!(0, head_aged.tags.borrow().len());
assert_eq!(data.sizes, head_aged.last_stats);
assert_eq!(SizeStats::default(), head_aged.current_stats);
assert_eq!(Status::Ongoing, head_aged.status);
assert!(start <= head_aged.start_time && head_aged.start_time <= SystemTime::now());
assert!(head_aged.end_time.is_none());
assert_eq!(0, head_aged.inactive_for);
assert!(head_aged.started_here);
let mut head = FlowHead::new(Status::Start, data.sizes.clone());
assert_eq!(data.sizes, head.current_stats);
assert_eq!(Status::Start, head.status);
let end = start + Duration::from_secs(15);
let slice = head.slice(start, end);
assert_eq!((head.start_time, end), (&slice).interval());
assert_eq!(&data.sizes.expand(head.start_time, end, Duration::from_secs(5), true),
(&slice).stats());
assert!((&slice).value(&Ident::of::<Direction>()).is_none());
assert!(!head.started_here);
assert_eq!(SizeStats::default(), head.current_stats);
head.tags.borrow_mut().insert(Direction::In);
assert_eq!(Value::from(Direction::In), (&slice).value(&Ident::of::<Direction>()).unwrap());
}
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
struct Key1(usize);
impl ColumnType for Key1 {
fn name() -> String { "test-key-1".to_owned() }
}
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
struct Key2(usize);
impl ColumnType for Key2 {
fn name() -> String { "test-key-2".to_owned() }
}
#[test]
fn updates() {
let data = TestData::new();
let logger = libutils::test_logger();
let (sender, receiver) = mpsc::unbounded();
let mut iter = receiver.wait();
let mut gather = Gather::new(logger, sender);
assert!(gather.flows.is_empty());
assert!(gather.index.is_empty());
let time = gather.close_slice();
assert_eq!(0, (&time).into_iter().count());
let init_f1 = Update {
keys: vec![
Key::Simple(Key1(1).into()),
],
status: Status::Start,
tags: Tags::new(),
stats: Some(data.sizes.clone()),
};
gather.update(init_f1);
assert_eq!(1, gather.flows.len());
assert_eq!(2, gather.index.len());
assert_eq!(Status::Start, gather.flows[0].borrow().status);
assert_eq!(1, gather.flows[0].borrow().keys.len());
if let Some(Ok(Event::FlowStarted(flow))) = iter.next() {
assert_eq!(0, flow.borrow().len());
} else {
panic!("Wrong event");
}
let time = gather.close_slice();
assert_eq!(1, (&time).into_iter().count());
assert_eq!(Status::Ongoing, gather.flows[0].borrow().status);
assert!(!gather.flows[0].borrow().started_here);
assert_eq!(SizeStats::default(), gather.flows[0].borrow().current_stats);
assert_eq!(1, gather.flows[0].borrow().inactive_for);
let both_keys = vec![
Key::Simple(Key1(1).into()),
Key::Simple(Key2(2).into()),
];
let mut tags = Tags::new();
tags.insert(Direction::In);
let update_f1 = Update {
keys: both_keys.clone(),
status: Status::Ongoing,
tags,
stats: None,
};
gather.update(update_f1);
assert_eq!(1, gather.flows.len());
assert_eq!(0, gather.flows[0].borrow().inactive_for);
assert_eq!(2, gather.flows[0].borrow().keys.len());
assert_eq!(3, gather.index.len());
let ident = Ident::of::<Direction>();
for flow in &time {
assert_eq!(Value::from(Direction::In), flow.value(&ident).unwrap());
}
if let Some(Ok(Event::FlowUpdated { flow, columns })) = iter.next() {
assert_eq!(1, flow.borrow().len());
assert_eq!(1, columns.len());
assert!(columns.contains(&ident));
} else {
panic!("Wrong event");
}
let update_f1 = Update {
keys: both_keys.clone(),
status: Status::Ongoing,
tags: Tags::new(),
stats: Some(data.sizes.clone()),
};
gather.update(update_f1);
assert_eq!(SizeStats::default(), gather.flows[0].borrow().current_stats);
assert_eq!(data.sizes, gather.flows[0].borrow().last_stats);
let larger = data.sizes.clone() + data.sizes.clone();
let update_f1 = Update {
keys: vec![
Key::Simple(Key2(2).into()),
],
status: Status::Ongoing,
tags: Tags::new(),
stats: Some(larger.clone()),
};
gather.update(update_f1);
assert_eq!(1, gather.flows.len());
assert_eq!(3, gather.index.len());
assert_eq!(data.sizes, gather.flows[0].borrow().current_stats);
assert_eq!(larger, gather.flows[0].borrow().last_stats);
let mut tags2 = Tags::new();
tags2.insert(IpProto::Tcp);
tags2.insert(Direction::In);
let init_f2 = Update {
keys: vec![
Key::Simple(Key1(2).into()),
],
status: Status::Ongoing,
tags: tags2,
stats: None,
};
gather.update(init_f2);
assert_eq!(2, gather.flows.len());
assert_eq!(5, gather.index.len());
{
let f = gather.flows[1].borrow();
assert_eq!(SizeStats::default(), f.current_stats);
assert_eq!(SizeStats::default(), f.last_stats);
assert_eq!(Status::Ongoing, f.status);
assert_eq!(0, f.inactive_for);
}
if let Some(Ok(Event::FlowStarted(flow))) = iter.next() {
let borrow = flow.borrow();
assert_eq!(2, borrow.len());
assert!(borrow.contains(&Ident::of::<Direction>()));
assert!(borrow.contains(&Ident::of::<IpProto>()));
} else {
panic!("Wrong event");
}
if let Some(Ok(Event::FlowUpdated { flow, columns })) = iter.next() {
let borrow = flow.borrow();
assert_eq!(2, borrow.len());
assert!(borrow.contains(&Ident::of::<Direction>()));
assert!(borrow.contains(&Ident::of::<IpProto>()));
assert_eq!(2, columns.len());
assert!(columns.contains(&Ident::of::<Direction>()));
assert!(columns.contains(&Ident::of::<IpProto>()));
} else {
panic!("Wrong event");
}
let close_f1 = Update {
keys: both_keys.clone(),
status: Status::End,
tags: Tags::new(),
stats: None,
};
gather.update(close_f1);
assert_eq!(2, gather.flows.len());
assert_eq!(5, gather.index.len());
assert_eq!(Status::End, gather.flows[0].borrow().status);
assert_eq!(0, gather.flows[0].borrow().inactive_for);
let time = gather.close_slice();
assert_eq!(2, (&time).into_iter().count());
assert_eq!(2, gather.flows.len());
assert_eq!(5, gather.index.len());
gather.push_cork(update::cork().0);
if let Some(Ok(Event::CorkRequest(_))) = iter.next() { } else {
panic!("There should have been a cork");
}
let dead_f1 = Update {
keys: both_keys.clone(),
status: Status::Ongoing,
tags: Tags::new(),
stats: None,
};
gather.update(dead_f1);
assert_eq!(2, gather.flows.len());
assert_eq!(5, gather.index.len());
assert_eq!(Status::End, gather.flows[0].borrow().status);
let mut time = gather.close_slice();
assert_eq!(1, (&time).into_iter().count());
for _ in 0..SLICE_KEEP_ENDED {
time = gather.close_slice();
}
assert_eq!(1, (&time).into_iter().count());
assert_eq!(1, gather.flows.len());
assert_eq!(2, gather.index.len());
assert!(gather.index.contains_key(&Key::Simple(Key1(2).into())));
assert_eq!(1, gather.flows[0].borrow().keys.len());
if let Some(Ok(Event::FlowTerminated(flow))) = iter.next() {
assert_eq!(1, flow.borrow().len());
} else {
panic!("Wrong event");
}
for _ in 0..SLICE_INACTIVE_LIMIT {
time = gather.close_slice();
}
assert_eq!(0, (&time).into_iter().count());
assert_eq!(0, gather.flows.len());
assert_eq!(0, gather.index.len());
if let Some(Ok(Event::FlowTerminated(flow))) = iter.next() {
assert_eq!(2, flow.borrow().len());
} else {
panic!("Wrong event");
}
drop(gather);
assert!(iter.next().is_none());
}
#[test]
fn internal_key_missing() {
let key = Key::InternalHandle(FlowTags::new(Tags::new()));
let update = Update {
keys: vec![key],
status: Status::Start,
tags: Tags::new(),
stats: None,
};
let logger = libutils::test_logger();
let (sender, receiver) = mpsc::unbounded();
let mut gather = Gather::new(logger, sender);
gather.update(update);
assert_eq!(0, gather.flows.len());
assert_eq!(0, gather.index.len());
drop(gather);
assert_eq!(0, receiver.wait().count());
}
#[test]
fn gather_cork() {
let data = TestData::new();
let logger = libutils::test_logger();
let (sender, receiver) = mpsc::unbounded();
let mut gather = Gather::new(logger, sender);
let init_f1 = Update {
keys: vec![
Key::Simple(Key1(1).into()),
],
status: Status::Start,
tags: Tags::new(),
stats: Some(data.sizes.clone()),
};
gather.update(init_f1);
let (cork, handle) = update::cork();
gather.push_cork(cork);
let mut iter = receiver.wait();
if let Some(Ok(Event::FlowStarted(_))) = iter.next() { } else {
panic!("The first event should be FlowStarted");
}
if let Some(Ok(Event::CorkRequest(_))) = iter.next() { } else {
panic!("The second event should be a CorkRequest");
}
handle.wait().unwrap();
drop(gather);
assert!(iter.next().is_none());
}
#[test]
fn query() {
let logger = libutils::test_logger();
let (sender, _receiver) = mpsc::unbounded();
let mut gather = Gather::new(logger, sender);
let empty_query = Headers::new();
let empty_query = RefHeaders::from(&empty_query);
assert_eq!(0, gather.query(&empty_query).count());
let flows: Vec<Vec<Value>> = vec![
vec![Direction::In.into()],
vec![Direction::In.into()],
vec![Direction::Out.into()],
vec![IpProto::Tcp.into()],
vec![Direction::In.into(), IpProto::Tcp.into()],
vec![],
];
for (id, flow) in flows.into_iter().enumerate() {
let mut tags = Tags::new();
for v in flow {
tags.insert(v);
}
let update = Update {
keys: vec![
Key::Simple(Key1(id).into()),
],
status: Status::Start,
tags,
stats: None,
};
gather.update(update);
}
assert_eq!(6, gather.flows.len());
assert_eq!(6, gather.query(&empty_query).count());
let mut in_unset = Headers::new();
in_unset.insert(Direction::In);
in_unset.insert_empty(Ident::of::<Direction>());
let in_unset = RefHeaders::from(&in_unset);
assert_eq!(5, gather.query(&in_unset).count());
let mut two_crits = Headers::new();
two_crits.insert(Direction::In);
two_crits.insert(IpProto::Tcp);
let two_crits = RefHeaders::from(&two_crits);
assert_eq!(1, gather.query(&two_crits).count());
let mut tcp_out = Headers::new();
tcp_out.insert(Direction::Out);
tcp_out.insert(IpProto::Tcp);
let tcp_out = RefHeaders::from(&tcp_out);
assert_eq!(0, gather.query(&tcp_out).count());
let single = gather.query(&two_crits).next().unwrap();
let borrowed = single.borrow();
assert_eq!(2, borrowed.len());
assert_eq!(Some(&Value::from(IpProto::Tcp)), borrowed.get(&Ident::of::<IpProto>()));
assert_eq!(Some(&Value::from(Direction::In)), borrowed.get(&Ident::of::<Direction>()));
}
}