-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsensor_model.py
More file actions
1884 lines (1579 loc) · 76.5 KB
/
Copy pathsensor_model.py
File metadata and controls
1884 lines (1579 loc) · 76.5 KB
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
#!/usr/bin/env python
"""
Implement sensor model defined in
http://sites/intranet/home/technology/network-flow-sensor-asic
The script implements the flow stats models defined in the specs. The modeling
class FlowTable takes packets in time order, and computes stats. These stats
can be exported in proto format, which can then be used by a testing driver to
validate actual sensor outputs. """
__author__ = "Ashutosh Kulshreshtha <ashutkul@tetrationanalytics.com>"
import hashlib
import logging
import random
import struct
import time
import zlib
import gflags
import google.protobuf # pylint: disable=F0401,E0611
# pylint: disable=W0403
from dpkt_hack import dpkt
import flow_ac_int
import flow_info_pb2
import sensor_config_pb2
import sensor_util
FLAGS = gflags.FLAGS
gflags.DEFINE_integer('simulation_start_time',
time.mktime((2014, 1, 1, 0, 0, 0, 0, 0, -1)) * 1e6,
'Start time for the sensor.')
gflags.DEFINE_integer('export_interval_microseconds', 100000,
'Sensor export interval in microseconds')
gflags.DEFINE_integer('num_collectors', 1,
'Number of colllectors.')
gflags.DEFINE_boolean('asic_mode', True,
'Whether the golden model should run in the ASIC mode.')
gflags.DEFINE_boolean('check_tcam_policy_match', False,
'If True, crash on packet without matching TCAM policy.')
class SensorError(Exception):
"""Sensor model exceptions, like unsupported protocols."""
pass
class SensorStatsNotExported(Exception):
"""Sensor error, indicating uncollected stats from previous interval."""
pass
def DefaultSensorConfig():
"""Sensor Config parameters."""
sensor_config = sensor_config_pb2.SensorConfig()
sensor_config.sensor_start_time = FLAGS.simulation_start_time
sensor_config.export_interval = FLAGS.export_interval_microseconds
sensor_clock = sensor_config.clock
# Assume cycle and tick both to be 1 us, which requires no shift.
sensor_clock.cycle_bitshifts_for_tick = 0
sensor_clock.export_interval_in_ticks = sensor_config.export_interval
sensor_clock.tick_bitshifts_for_burst = 10
sensor_config.tcp_header_length_bins.extend(
[6, 7, 8, 9, 10, 12, 14])
# TODO(ashu): Confirm whether these are TCP payload lengths or
# include TCP header. Does this include IP header?
sensor_config.tcp_payload_length_bins.extend(
[1, 10, 100, 200, 500, 1000, 1500, 2000, 3000, 5000, 7000])
sensor_config.receiver_window_length_bins.extend(
[1, 10, 100, 1000, 10000])
sensor_config.tcp_sequence_number_plus_offset = 5000
sensor_config.tcp_sequence_number_minus_offset = 5000
sensor_config.num_collectors = FLAGS.num_collectors
return sensor_config
class PolicyHelper(object):
"""Helper for policy application."""
# Define proto here for shortcut.
proto = sensor_config_pb2.TcamPolicy
ACTION_DISPOSITION_MAP = {
proto.SECURITY_FAILED: 'port_security_failed',
proto.DENY: 'deny_policy',
proto.REDIRECT: 'redirect_service',
proto.COPY: 'copy_service',
proto.APPLIED: 'policy_applied',
}
def __init__(self, sensor_config):
"""Initialize analytics and policy maps."""
self.tenant_analytics_map = {}
for analytics in sensor_config.tenant_policy:
self.tenant_analytics_map[analytics.tenant_id] =\
analytics.analytics_type
self.tep_analytics_map = {}
for tep in sensor_config.tep_map:
self.tep_analytics_map[tep.tep_id] = tep.analytics_type
self.iface_analytics_map = {}
for iface in sensor_config.iface_map:
self.iface_analytics_map[iface.switch_port] = iface.analytics_type
self.tcam_policies = sensor_config.tcam_policy
def is_match(self, key, policy):
"""Return, if the policy matches the flow. If a policy field is
not set, it is considered a match."""
def match_value(mask, value1, value2):
"""Match values with mask."""
if isinstance(mask, int):
return (mask & value1) == (mask & value2)
if isinstance(mask, (bytes, str)):
if len(mask) != len(value1) or len(mask) != len(value2):
raise ValueError("len(mask) != len(value)")
assert len(mask) == len(value1) and len(mask) == len(value2)
for i in range(len(mask)):
if not match_value(ord(mask[i]),
ord(value1[i]), ord(value2[i])):
return False
return True
assert "match does not support type %s" % type(mask)
mask = policy.tcam.mask
value = policy.tcam.value
if value.key_type != key.key_type:
return False
if mask.HasField("proto") and\
not match_value(mask.proto, value.proto, key.proto):
return False
if mask.HasField("tenant_id") and\
not match_value(mask.tenant_id,
value.tenant_id, key.tenant_id):
return False
if mask.HasField("src_address") and\
not match_value(mask.src_address,
value.src_address, key.src_address):
return False
if mask.HasField("dst_address") and\
not match_value(mask.dst_address,
value.dst_address, key.dst_address):
return False
if mask.HasField("src_port") and\
not match_value(mask.src_port, value.src_port, key.src_port):
return False
if mask.HasField("dst_port") and\
not match_value(mask.dst_port, value.dst_port, key.dst_port):
return False
return True
def policy_action(self, flow_key):
"""Return action from the matching policy."""
for p in self.tcam_policies:
if p.action == self.proto.UNDEFINED:
continue
try:
if self.is_match(flow_key, p):
return p.action
except ValueError:
if FLAGS.check_tcam_policy_match:
assert False, "\n".join([str(s)
for s in self.tcam_policies])
return None
@classmethod
def collect(cls, analytics_type):
"""Combine collect/no-collect."""
if analytics_type is None:
# Consider default to be FULL analytics.
return True
return analytics_type != sensor_config_pb2.Analytics.NO_ANALYTICS
@classmethod
def valid(cls, analytics_type):
"""Combine full/concise analytics."""
if analytics_type is None:
# Consider default to be FULL analytics.
return True
return analytics_type == sensor_config_pb2.Analytics.FULL
@classmethod
def analytics_type(cls, collect, valid):
"""Combine collect and valid to analytics type."""
if not collect:
return sensor_config_pb2.Analytics.NO_ANALYTICS
elif valid:
return sensor_config_pb2.Analytics.FULL
return sensor_config_pb2.Analytics.CONCISE
@classmethod
def derive_analytics(cls, iface_analytics, tep_analytics,
tenant_analytics):
"""Combine port/tep/tenant analytics for final analytics."""
final_collect = cls.collect(iface_analytics) and (
cls.collect(tep_analytics) or cls.collect(tenant_analytics))
final_valid = cls.valid(iface_analytics) and (
cls.valid(tep_analytics) or cls.valid(tenant_analytics))
return cls.analytics_type(final_collect, final_valid)
def lu_analytics_type(self, tenant_id, tep, switch_port):
"""Analytics type based only on tep and switch port."""
iface_analytics = self.iface_analytics_map.get(switch_port, None)
tep_analytics = self.tep_analytics_map.get(tep, None)
tenant_analytics = self.tenant_analytics_map.get(tenant_id, None)
combined = sensor_config_pb2.Analytics()
combined.analytics_type = self.derive_analytics(
iface_analytics, tep_analytics, tenant_analytics)
return combined
def analytics(self, flow_key, tep, switch_port):
"""Return analytics type required from matching policy."""
tcam = None
for p in self.tcam_policies:
if not p.HasField('analytics'):
continue
if self.is_match(flow_key, p):
tcam = p.analytics
break
lu_analytics = self.lu_analytics_type(flow_key.tenant_id, tep,
switch_port)
if not tcam:
return lu_analytics
if tcam.collect_override and tcam.analytics_vld_override:
return tcam
# If override bits are not set, reset TCAM values.
lu_collect = self.collect(lu_analytics.analytics_type)
lu_valid = self.valid(lu_analytics.analytics_type)
tcam_collect = self.collect(tcam.analytics_type)
tcam_valid = self.valid(tcam.analytics_type)
if not tcam.collect_override:
tcam_collect = lu_collect
if not tcam.analytics_vld_override:
tcam_valid = lu_valid
tcam.analytics_type = self.analytics_type(tcam_collect, tcam_valid)
return tcam
def packet_disposition(self, flow_key, pd):
"""Iterate over all policies, and return action from matching one."""
action = self.policy_action(flow_key)
if action:
field_name = PolicyHelper.ACTION_DISPOSITION_MAP[action]
setattr(pd, field_name, 1)
class NetworkConfig(object):
"""Class to help with network config lookups."""
def __init__(self, sensor_config):
"""Initialize network config with data provided in sensor_config."""
self.config = sensor_config
def get_iface(self, iface_name=None, switch_port=None):
"""Return full iface proto based on interface."""
assert iface_name is not None or switch_port is not None
for iface in self.config.iface_map:
if iface_name is not None and iface.iface_name == iface_name:
return iface
if switch_port is not None and iface.switch_port == switch_port:
return iface
return sensor_config_pb2.InterfaceMap()
def get_tenant_id(self, iface_name=None, switch_port=None):
"""Get tenant id based on interface."""
assert iface_name or switch_port
for iface in self.config.iface_map:
if iface_name and iface.iface_name == iface_name:
return iface.tenant_id
if switch_port and iface.switch_port == switch_port:
return iface.tenant_id
return None
def get_tep(self, tenant_id, host_address):
"""Get Tunnel End Point (TEP) id, for host_address given tenant."""
for tep in self.config.tep_map:
for end_host in tep.end_hosts:
if end_host.tenant_id == tenant_id and\
end_host.host_address == host_address:
return tep.tep_id
return None
def add_saturate(current, to_add, bits):
"""Add value and saturate at given bits."""
assert bits <= 64
if current >= ((0x1 << bits) - 1 - to_add):
return (0x1 << bits) - 1
return current + to_add
def fill_parsed_packet(eth, packet, timestamp=None, iface_name=None,
switch_port=None):
"""Given ethernet frame, build packet proto."""
assert isinstance(eth, dpkt.ethernet.Ethernet)
assert isinstance(packet, sensor_config_pb2.Packet)
packet.timestamp = timestamp
if iface_name is not None:
packet.iface = iface_name
if switch_port is not None:
packet.switch_port = switch_port
# Rather than directly using eth object, pack and unpack, because many
# of the dpkt computations (like TCP cksum) happen during pack.
eth = dpkt.ethernet.Ethernet(str(eth))
# Ethernet frame without FCS must be at least 60 bytes. Add padding
# otherwise.
eth_str = str(eth)
if len(eth_str) < 60:
eth_str += '\x00' * (60 - len(eth_str))
# FCS includes padding and is added in little-endian!
fcs = zlib.crc32(eth_str) & 0xffffffff
packet.pcap = eth_str + struct.pack("<L", fcs)
packet.l2_len = len(packet.pcap)
if eth.type in [dpkt.ethernet.ETH_TYPE_IP,
dpkt.ethernet.ETH_TYPE_IP6]:
ip = eth.data
if eth.type == dpkt.ethernet.ETH_TYPE_IP:
packet.ip_header_length = len(ip.pack_hdr() + ip.opts)
packet.ip_fragment_offset_non_zero = \
(ip.off & dpkt.ip.IP_OFFMASK) > 0
packet.ip_mf = (ip.off & dpkt.ip.IP_MF) > 0
packet.ip_id = ip.id
if ip.len != len(ip):
packet.parser_error = True
elif eth.type == dpkt.ethernet.ETH_TYPE_IP6:
packet.ip_header_length = len(ip.pack_hdr() + ip.headers_str())
# Use len(str(ip)) rather than len(ip), because dpkt does not
# include extension headers in len(ip).
if ip.plen != len(str(ip)) - 40:
packet.parser_error = True
for value in ip.extension_hdrs.values():
if value and isinstance(value, dpkt.ip6.IP6FragmentHeader):
packet.ip_fragment_offset_non_zero = value.frag_off > 0
packet.ip_mf = value.m_flag > 0
packet.ip_id = value.id
if isinstance(ip.data, dpkt.tcp.TCP):
packet.tcp_receive_window = ip.data.win
packet.tcp_data_offset = ip.data.off
# ACK num is set in parser, even if ACK bit is not set.
# if ip.data.flags & dpkt.tcp.TH_ACK:
packet.tcp_ack_num = ip.data.ack
if isinstance(ip.data, (dpkt.tcp.TCP, dpkt.udp.UDP)):
packet.l4_payload_len = len(ip.data.data)
if isinstance(ip.data, (dpkt.icmp.ICMP, dpkt.icmp6.ICMP6)):
packet.icmp_checksum = ip.data.sum
# L4 payload length could potentially be taken from fragmented
# packets in TCP, but ASIC parser does not do this. So matching
# it.
# if isinstance(ip.data, str) and ip.p == 6:
# packet.tcp_receive_window = 0
# packet.tcp_data_offset = 0
# packet.tcp_ack_num = 0
# packet.l4_payload_len = 0 # len(ip.data)
def hashstr(val):
"""Return hash value in hex string."""
if len(val) < 8: # Return small key as it, typically in unittests.
return val
# Remove 0x prefix and L suffix.
return hex(hash(val) & 0xffffffffffffffff)[2:-1]
class FlowTableEntry(object):
"""A single entry in the flow table."""
def __init__(self, column, key, size, valid=True):
self.column = column
self.key = key
self.size = size
self.valid = valid
def __lt__(self, other):
"""For sorting."""
if self.valid != other.valid:
return self.valid > other.valid
return self.column < other.column
def __repr__(self):
"""Readable item."""
valid_str = {True: "*", False: ""}
return "%d-%d:%s%s" % (self.column, self.column + self.size - 1,
hashstr(self.key), valid_str[self.valid])
class AsicFlowTableBank(object):
"""Class to mimic ASIC flow table bank containing 4 cells."""
NUM_COLUMNS = 4
def __init__(self, bank):
"""Initialize empty row."""
self.bank = bank
self.flow_items = []
def __repr__(self):
"""Readable row."""
return " ".join([repr(k) for k in self.flow_items])
def sort_items(self):
"""Sort the items."""
self.flow_items.sort()
col = 0
for k in self.flow_items:
k.column = col
col += k.size
def get_size(self):
"""Get total size of valid items."""
return sum([k.size for k in self.flow_items if k.valid])
def get_item(self, key):
"""Return the column for the key."""
# If item is already in the table, return the column.
for item in self.flow_items:
if item.key == key:
return item
return None
def insert_item(self, item):
"""Insert item in the bank at given column. Replace ghost items, if
needed."""
# We may have to remove some invalid items,
remove_items = []
# start and end (inclusive) of indices in flow_items that need to be
# removed.
(remove_index_start, remove_index_end) = (None, None)
last_column_removed = None
# print "Inserting item " + repr(item) + " in table " + repr(self)
for (index, k) in enumerate(self.flow_items):
# If the range of current item overlaps with the range of item
# present, it should be removed.
if (k.column + k.size - 1 >= item.column and
k.column <= item.column + item.size - 1):
# print "Removing item " + repr(k) + " from table ",
# print repr(self) + " to insert " + repr(item)
assert not k.valid, "Removing valid item " + repr(k) +\
" from table " + repr(self) + " to insert " + repr(item)
if remove_index_start is None:
remove_index_start = index
remove_index_end = index
last_column_removed = k.column + k.size
remove_items.append(k.key)
if remove_items:
insert_array = [item]
# If the new item doesn't completely cover the removed items, we
# may have to add a dummy item.
dummy_size = last_column_removed - (item.column + item.size)
if dummy_size > 0:
dummy = FlowTableEntry(item.column + item.size, "dummy",
dummy_size, False)
insert_array.append(dummy)
self.flow_items = self.flow_items[0 : remove_index_start] +\
insert_array + self.flow_items[remove_index_end + 1:]
else:
# print "No items to remove"
self.flow_items.append(item)
# print "After inserting table ", repr(self)
# Remove "dummy" from remove_items, before returning..
remove_items = [r for r in remove_items if r != "dummy"]
return (item.column, remove_items)
def add_key(self, key, size):
"""Add a key, possibly existing. Return column index, where the
key exists or newly added. The method returns (column, ghost_key_list)
tuple. The ghost items are those that adding this key pushed out.
If row is full, column = -1."""
item = self.get_item(key)
if item:
if not item.valid:
item.valid = True
self.sort_items()
item = self.get_item(key)
return (item.column, [])
if self.get_size() + size > self.NUM_COLUMNS:
logging.debug("Can't fit key in the row in ASIC.")
return (-1, [])
item = FlowTableEntry(self.get_size(), key, size, True)
return self.insert_item(item)
def remove_key(self, key, do_compaction=True):
"""Simply mark the entry invalid. Removal happens during compaction."""
for k in self.flow_items:
if k.key == key:
k.valid = False
if do_compaction:
self.sort_items()
return
class AsicFlowTableRow(object):
"""Class to mimic ASIC flow table row."""
NUM_BANKS = 4
def __init__(self):
"""Initialize empty row."""
self.banks = [AsicFlowTableBank(i)
for i in range(AsicFlowTableRow.NUM_BANKS)]
def __repr__(self):
"""Readable flow table."""
return " ".join(["[%s]" % repr(v) for v in self.banks])
def add_key(self, key, size):
"""Add key to a given row. Returns (column, removed_list)."""
# First check if the item is already present in the bank.
for (index, bank) in enumerate(self.banks):
item = bank.get_item(key)
if item:
(col, remove_items) = bank.add_key(key, size)
assert remove_items == []
return (index * AsicFlowTableBank.NUM_COLUMNS + col, [])
# Then add the item to first available bank.
for (index, bank) in enumerate(self.banks):
(col, remove_items) = bank.add_key(key, size)
if col >= 0:
return (index * AsicFlowTableBank.NUM_COLUMNS + col,
remove_items)
return (-1, [])
def remove_key(self, key, do_compaction=True):
"""Remove key from given row."""
for bank in self.banks:
bank.remove_key(key, do_compaction)
def get_item(self, key):
"""Get item given key."""
for bank in self.banks:
item = bank.get_item(key)
if item is not None:
return item
return None
class AsicFlowTable(object):
"""Class to mimic ASIC flow table behavior."""
NUM_ROWS = (1 << 12)
def __init__(self):
"""Initialize the row_index -> AsicFlowTableRow map. We use a map,
rather than array, because most of the tests will have a sparse
row fillup."""
self.rows = {}
def __repr__(self):
"""Readable flow table."""
return "\n".join("%d: %s" % (k, v) for (k, v) in self.rows.items())
def add_key(self, row, key, size):
"""Add key to a given row. Returns (column, removed_list)."""
if row not in self.rows:
self.rows[row] = AsicFlowTableRow()
return self.rows[row].add_key(key, size)
def remove_key(self, row, key, do_compaction=True):
"""Remove key from given row."""
if row in self.rows:
self.rows[row].remove_key(key, do_compaction)
def get_item(self, row, key):
"""Get item given key in a row."""
return self.rows[row].get_item(key)
class SingleFlowState(object):
"""Flow state for a single flow."""
# Consts related to flow table saturation.
PACKET_COUNT_BITS = 22
BYTE_COUNT_BITS = 30
CURRENT_BURST_BITS = 16
MAX_BURST_BITS = 11
FLOWLET_COUNT_BITS = 7
def __init__(self, flow_key, timestamp, sensor_config,
interval_start_time, switch_port, analytics=None):
"""Initialize flow state."""
self._flow_info = flow_info_pb2.FlowInfo()
self._flow_info.key.CopyFrom(flow_key)
self._flow_info.key.flow_start_time = timestamp
self.crc12 = flow_ac_int.flow_key_crc12(flow_key, switch_port)
# Flow state variables
self.payload_len = 0
self.last_packet_timestamp = None
self.current_burst_index = 0
self.current_burst = 0
self.max_burst_index = 0
self.max_burst = 0
self.num_flowlets = 0
self.packet_count = 0
self.byte_count = 0
self.interval_start_time = interval_start_time
# Config parameters, read from sensor_config
self.burst_interval = 0
self.current_burst_bitshifts = 0
self.additional_max_burst_bitshifts = 0
self.flowlet_pause = 0
# Cache analytics requirements for the flow.
self._analytics = sensor_config_pb2.Analytics()
if analytics:
self._analytics.CopyFrom(analytics)
self.analytics_changed = False
self.sensor_mode = None
self.update_sensor_config(sensor_config)
def get_analytics(self):
"""Get analytics."""
return self._analytics
def set_analytics(self, analytics):
"""Set analytics value."""
# If anaytics value is different from previous value, record it.
if self._analytics.analytics_type != analytics.analytics_type:
self.analytics_changed = True
self._analytics.CopyFrom(analytics)
# Use property for analytics get/set to take care of the side effects.
analytics = property(get_analytics, set_analytics)
def __repr__(self):
"""Readable flow state."""
return str(self._flow_info)
def update_sensor_config(self, sensor_config):
"""Set parameters from sensor_config."""
burst_bitshift = sensor_config.clock.tick_bitshifts_for_burst
self.burst_interval = 0x1 << burst_bitshift
# self.interval_start_time = sensor_config.sensor_start_time
self.current_burst_bitshifts = \
sensor_config.burst.burst_size_bitshifts
self.additional_max_burst_bitshifts = \
sensor_config.burst.additional_max_burst_size_bitshifts
self.flowlet_pause = sensor_config.flowlet_pause_duration
self.sensor_mode = sensor_config.sensor_mode
def flow_info_after_export(self, new_interval_start_time):
"""Flow info to be kept after export."""
# Rather than removing information, we copy relevant fields.
flow_info_preserved = flow_info_pb2.FlowInfo()
flow_info_preserved.key.CopyFrom(self._flow_info.key)
if self._flow_info.HasField("ip_info"):
if self._flow_info.ip_info.dont_fragment_set:
flow_info_preserved.ip_info.dont_fragment_set = 1
if self._flow_info.ip_info.HasField("last_cached_ttl"):
flow_info_preserved.ip_info.last_cached_ttl = \
self._flow_info.ip_info.last_cached_ttl
if self._flow_info.HasField("tcp_info"):
tcp_info = self._flow_info.tcp_info
if tcp_info.HasField("sequence_num"):
flow_info_preserved.tcp_info.sequence_num =\
tcp_info.sequence_num
# Although, the ack_num should be preserved, ACK flag is not.
# Current ASIC implementation uses ACK flag before checking
# ack_num, and thus behaves like ack_num is not preserved.
if self.sensor_mode !=\
sensor_config_pb2.SensorConfig.ASIC_SENSOR_MODEL:
if tcp_info.HasField("ack_num"):
flow_info_preserved.tcp_info.ack_num = \
tcp_info.ack_num
# Reset stats.
self.interval_start_time = new_interval_start_time
self.last_packet_timestamp = None
self.current_burst_index = 0
self.current_burst = 0
self.max_burst_index = 0
self.max_burst = 0
self.num_flowlets = 0
self.packet_count = 0
self.byte_count = 0
self._flow_info = flow_info_preserved
def new_packet(self, timestamp, l2_bytes, payload_len=None):
"""Update flow state given packet at a timestamp.
l2_bytes: L2 packet length (inner packet in case of encapsulation).
payload_bytes: Size of the TCP/UDP payload. Only available in case
of TCP/UDP packets."""
if payload_len is not None:
self.payload_len = payload_len
else:
self.payload_len = l2_bytes
burst_index = (timestamp - self.interval_start_time) / \
self.burst_interval
if burst_index != self.current_burst_index:
self.current_burst_index = burst_index
self.current_burst = 0
current_bytes = l2_bytes >> self.current_burst_bitshifts
self.current_burst = \
add_saturate(self.current_burst, current_bytes,
self.CURRENT_BURST_BITS)
max_bytes = self.current_burst >> self.additional_max_burst_bitshifts
if max_bytes > self.max_burst:
self.max_burst = max_bytes
self.max_burst_index = burst_index
# Num flowlets. Saturate after FLOWLET_COUNT_BITS.
if self.last_packet_timestamp is None or\
timestamp - self.last_packet_timestamp > self.flowlet_pause:
self.num_flowlets = \
add_saturate(self.num_flowlets, 1, self.FLOWLET_COUNT_BITS)
# print "last time stamp ", self.last_packet_timestamp, "timestamp ",\
# timestamp, " num flowlets ", self.num_flowlets
# Packet count. Saturate.
self.packet_count = add_saturate(self.packet_count, 1,
self.PACKET_COUNT_BITS)
# Byte count with saturation.
self.byte_count = add_saturate(self.byte_count, l2_bytes,
self.BYTE_COUNT_BITS)
# Cache last packet timestamp for flowlet computation.
self.last_packet_timestamp = timestamp
def get_flow_info(self):
"""flow_info getter."""
return self._flow_info
def set_flow_info(self, flow_info):
"""flow_info setter. Also set side effects from the flow info."""
logging.debug("Setting flow info: %s", str(flow_info))
self.last_packet_timestamp = flow_info.end_time
if len(flow_info.flow_features) > 0:
flow_features = flow_info.flow_features[0]
self.current_burst_index = \
(flow_info.end_time - self.interval_start_time) / \
self.burst_interval
self.current_burst = flow_features.current_burst
self.max_burst_index = flow_features.max_burst_index
self.max_burst = flow_features.max_burst
self.num_flowlets = flow_features.num_flowlets
self.packet_count = flow_features.packet_count
self.byte_count = flow_features.byte_count
self._flow_info = flow_info
flow_info = property(get_flow_info, set_flow_info)
class FlowTable(object):
"""Maintain flow table and stats that are used in the sensor model.
The class maintains all flows in an export interval. The stats are indexed
by flow-key. The class also maintains data like packet lengths and
bursts/flowlets, which are later used to derive overall stats."""
# Map of ARP op code to sensor proto.
ARP_OP_PROTO_MAP = {
dpkt.arp.ARP_OP_REVREPLY: 248,
dpkt.arp.ARP_OP_REVREQUEST: 247,
dpkt.arp.ARP_OP_REQUEST: 249,
dpkt.arp.ARP_OP_REPLY: 250
}
# Consts related to flow table.
# TODO(ashu): Move this logic to SingleFlowState class.
RANDOM_PACKET_LEN_BITS = 14
# Event type fields in the EventDescriptor proto.
EVENT_TYPES = ['event_type_rtt_seq',
'event_type_rtt_ack',
'event_type_table_full',
'event_type_pkt_value_match',
'event_type_mouse_pkt',
'event_type_first_pkt',
'event_type_export_flow',
'event_type_analytics_changed']
def __init__(self, sensor_config=DefaultSensorConfig(),
sensor_mode_cache=True,
include_validation=True, sensor_export_callback=None,
event_export_callback=None):
"""Initialize various maps.
Args:
sensor_config: SensorConfig object.
sensor_mode_cache: Whether sensor keeps export stats cache. See
below for more details.
include_validation: Whether to include validation information
in flow_info exports.
"""
# Initialize members to None in __init__ to keep lint happy. These
# values are set later by set_sensor_config.
self.policy_helper = None
self.network_helper = None
# Start time for the first export interval.
self.interval_start_time = 0
self.burst_interval = None
# flow_key -> SingleFlowState map
self.flow_state_map = {}
self.asic_flow_table = AsicFlowTable()
# Configuration for the sensor. Set other members using
# sensor configuration.
self.set_sensor_config(sensor_config)
# If sensor_mode_cache is True, the FlowTable keeps the list of
# flow stats per export duration in export_stats_cache. This is useful
# to run sensor model for test or on a small set of packets.
# If sensor_mode_cache is False, the model raises
# SensorStatsNotExported exception, which allows caller to collect
# sensor stats. In this mode, this object does not maintain the cache.
self.sensor_mode_cache = sensor_mode_cache
# Method to callback, when export interval is over.
self.sensor_export_callback = sensor_export_callback
if self.sensor_export_callback:
assert self.sensor_mode_cache is False
self.export_stats_cache = flow_info_pb2.FlowInfoFromSensorList()
# Whether there is a new packet after the last export.
self.export_pending = False
self.include_validation = include_validation
# Callback method for event export.
self.event_export_callback = event_export_callback
# Enable/disable debug.
self.debug = False
def remove_flow_item(self, flow_key_str, check_item=True):
"""Remove invalid/preserved flow item from the table."""
# Make sure that the items getting removed are ghost items.
remove_flow_info = self.flow_state_map[flow_key_str].flow_info
if check_item:
assert (not remove_flow_info.flow_features or
not remove_flow_info.flow_features[0].packet_count)
del self.flow_state_map[flow_key_str]
def set_sensor_config(self, sensor_config):
"""Set sensor_config, including side-effects."""
self._sensor_config = sensor_config
self.policy_helper = PolicyHelper(self._sensor_config)
self.network_helper = NetworkConfig(self._sensor_config)
self.interval_start_time = self._sensor_config.sensor_start_time
burst_bitshift = self._sensor_config.clock.tick_bitshifts_for_burst
self.burst_interval = 0x1 << burst_bitshift
if sensor_config.HasField("initial_flow_table_state"):
for info in sensor_config.initial_flow_table_state.flow_info:
self.set_flow_info(info)
# TODO(ashu): Add burst interval stats from initial state.
# key = self.flow_key_str(flow_info.key)
# self.burst_lists[key].set_current_burst
def get_sensor_config(self):
"""Get sensor config."""
return self._sensor_config
# Setting getter and setter for sensor_config, to take care of the
# side effects when setting, rather than directly exposing the
# variable.
sensor_config = property(get_sensor_config, set_sensor_config)
def set_export_callback(self, sensor_export_callback):
"""Set callback function for flow table export."""
self.sensor_mode_cache = False
assert callable(sensor_export_callback)
self.sensor_export_callback = sensor_export_callback
def set_event_callback(self, event_export_callback):
"""Set callback function for event export."""
assert callable(event_export_callback)
self.event_export_callback = event_export_callback
def __del__(self):
"""Write any remaining flow table records."""
if callable(self.sensor_export_callback):
self.sensor_export_callback(self.export_done())
def __repr__(self):
"""Readable string for the stats."""
flow_info_str = "\n".join(
[str(fi.flow_info.key) for fi in self.flow_state_map.values()])
return flow_info_str
def set_flow_info(self, flow_info):
"""Set a given flow info state in the model. Useful for testing."""
validation = flow_info.Extensions[sensor_config_pb2.validation]
key = self.flow_key_str(flow_info.key,
validation.analytics.analytics_type)
if key not in self.flow_state_map:
self.flow_state_map[key] = SingleFlowState(
flow_info.key, flow_info.key.flow_start_time,
self._sensor_config, self.interval_start_time,
validation.switch_port, validation.analytics)
self.flow_state_map[key].flow_info = flow_info
# TODO(ashu): Also add the packet to asic_flow_table
# validation.flow_table_row = flow_state.crc12
# asic_cells = self.asic_num_cells(stats.key, flow_state.analytics)
# (column, removed_keys) = self.asic_flow_table.add_key(
# flow_state.crc12, flow_key_str, asic_cells)
def collector_analytics_match(self, flow_key, col_analytics, analytics):
"""Check whether collector analytics matched flow analytics."""
analytics_type = analytics.analytics_type
# CE flows are always considered CONCISE.
if flow_key.key_type == flow_info_pb2.FlowKey.MAC:
analytics_type = sensor_config_pb2.Analytics.CONCISE
if col_analytics == sensor_config_pb2.SensorCollectorConfig.BOTH:
return True
if col_analytics == sensor_config_pb2.SensorCollectorConfig.FULL:
return analytics_type == sensor_config_pb2.Analytics.FULL
if col_analytics == sensor_config_pb2.SensorCollectorConfig.CONCISE:
return analytics_type == sensor_config_pb2.Analytics.CONCISE
assert False, "Unknown collector analytics %d" % col_analytics
def collector_index(self, flow_key, analytics):
"""If there are multiple collectors, load-balance between those."""
if self._sensor_config.num_collectors <= 1:
return 0
# If the collector range is really small, assume this flow will
# not be collected.
if (self._sensor_config.collector_config.range_high -
self._sensor_config.collector_config.range_low) <= 1:
return -1
# Match collector config with analytics.
if not self.collector_analytics_match(
flow_key,
self.sensor_config.collector_config.analytics_setup,
analytics):
return -1
# Use required fields from flow_key, based on collector config.
(src_addr, dst_addr) = ("", "")
(src_port, dst_port) = ("", "")
tenant_id = ""
if self._sensor_config.collector_config.include_src_address:
src_addr = sensor_util.convert_ip(flow_key.src_address)
if self._sensor_config.collector_config.include_dst_address:
dst_addr = sensor_util.convert_ip(flow_key.dst_address)
if self._sensor_config.collector_config.include_src_port:
src_port = str(flow_key.src_port)
if self._sensor_config.collector_config.include_dst_port:
dst_port = str(flow_key.dst_port)
if self._sensor_config.collector_config.include_tenant_id:
tenant_id = str(flow_key.tenant_id)
# Create a direction independent hash, using min/max.
m = hashlib.md5()
for i in range(10):
m.update(min(src_addr, dst_addr))
m.update(max(src_addr, dst_addr))
m.update(min(src_port, dst_port))
m.update(max(src_port, dst_port))
m.update(tenant_id)
# Use last 16 bytes of the digest.
collector_hash = int(m.hexdigest(), 16)
ret = collector_hash % self._sensor_config.num_collectors
# print (src_addr, dst_addr, src_port, dst_port, tenant_id,
# collector_hash, ret, min(src_addr, dst_addr),