forked from faucetsdn/ryu
-
Notifications
You must be signed in to change notification settings - Fork 6
/
beba_v1_0_parser.py
1242 lines (1102 loc) · 66.1 KB
/
beba_v1_0_parser.py
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
import struct
from ryu.lib.pack_utils import msg_pack_into
from ryu.ofproto.ofproto_parser import StringifyMixin, MsgBase, msg_str_attr
import ryu.ofproto.ofproto_v1_3_parser as ofproto_parser
import ryu.ofproto.ofproto_v1_3 as ofproto
import ryu.ofproto.beba_v1_0 as bebaproto
from ryu import utils
import logging
import six
from array import array
LOG = logging.getLogger('ryu.ofproto.beba_v1_0_parser')
def OFPExpActionSetState(state, table_id, bit=0, hard_timeout=0, idle_timeout=0, hard_rollback=0, idle_rollback=0, state_mask=0xffffffff):
"""
Returns a Set state experimenter action
This action applies the state. TO DO: look how deal with ofl msg instruction
and also cls
================ ======================================================
Attribute Description
================ ======================================================
state State instance
state_mask State mask
table_id Stage ID
bit Enable/Disable swapping of the source/destination addresses a
and source/destination ports in the case of bi-flow identificatin
================ ======================================================
"""
act_type=bebaproto.OFPAT_EXP_SET_STATE
data=struct.pack(bebaproto.OFP_EXP_ACTION_SET_STATE_PACK_STR, act_type, state, state_mask, table_id ,hard_rollback, idle_rollback, hard_timeout*1000000, idle_timeout*1000000,bit)
return ofproto_parser.OFPActionExperimenterUnknown(experimenter=0xBEBABEBA, data=data)
def OFPExpActionSetGlobalState(global_state, global_state_mask=0xffffffff):
"""
Returns a Set Global State experimenter action
This action updates the switch global state.
================ ======================================================
Attribute Description
================ ======================================================
global_state Global state value
global_state_mask Mask value
================ ======================================================
"""
act_type=bebaproto.OFPAT_EXP_SET_GLOBAL_STATE
data=struct.pack(bebaproto.OFP_EXP_ACTION_SET_GLOBAL_STATE_PACK_STR, act_type, global_state, global_state_mask)
return ofproto_parser.OFPActionExperimenterUnknown(experimenter=0XBEBABEBA, data=data)
def OFPExpActionIncState(table_id):
"""
Returns a Set Inc state experimenter action
This action increment the current state.
================ ======================================================
Attribute Description
================ ======================================================
table_id Stage ID
================ ======================================================
"""
act_type=bebaproto.OFPAT_EXP_INC_STATE
data=struct.pack(bebaproto.OFP_EXP_ACTION_INC_STATE_PACK_STR, act_type, table_id)
return ofproto_parser.OFPActionExperimenterUnknown(experimenter=0xBEBABEBA, data=data)
def OFPExpMsgConfigureStatefulTable(datapath, stateful, table_id):
command=bebaproto.OFPSC_EXP_STATEFUL_TABLE_CONFIG
data=struct.pack(bebaproto.OFP_EXP_STATE_MOD_PACK_STR, command)
data+=struct.pack(bebaproto.OFP_EXP_STATE_MOD_STATEFUL_TABLE_CONFIG_PACK_STR,table_id,stateful)
exp_type=bebaproto.OFPT_EXP_STATE_MOD
return ofproto_parser.OFPExperimenter(datapath=datapath, experimenter=0xBEBABEBA, exp_type=exp_type, data=data)
def OFPExpMsgKeyExtract(datapath, command, fields, table_id,bit=0):
field_count=len(fields)
if field_count > bebaproto.MAX_FIELD_COUNT:
field_count = 0
LOG.debug("OFPExpMsgKeyExtract: Number of fields given > MAX_FIELD_COUNT")
data=struct.pack(bebaproto.OFP_EXP_STATE_MOD_PACK_STR, command)
data+=struct.pack(bebaproto.OFP_EXP_STATE_MOD_EXTRACTOR_PACK_STR,table_id,bit,field_count)
field_extract_format='!I'
if field_count <= bebaproto.MAX_FIELD_COUNT:
for f in range(field_count):
data+=struct.pack(field_extract_format,fields[f])
exp_type=bebaproto.OFPT_EXP_STATE_MOD
# store lookup-scopes
if command == bebaproto.OFPSC_EXP_SET_L_EXTRACTOR:
if hasattr(datapath, 'lookup_scope'):
datapath.lookup_scope[table_id] = fields
else:
datapath.lookup_scope = {table_id: fields}
return ofproto_parser.OFPExperimenter(datapath=datapath, experimenter=0xBEBABEBA, exp_type=exp_type, data=data)
def OFPExpMsgSetFlowState(datapath, state, keys, table_id, idle_timeout=0, idle_rollback=0, hard_timeout=0, hard_rollback=0, state_mask=0xffffffff):
key_count=len(keys)
if key_count > bebaproto.MAX_KEY_LEN:
key_count = 0
LOG.debug("OFPExpMsgSetFlowState: Number of keys given > MAX_KEY_LEN")
command=bebaproto.OFPSC_EXP_SET_FLOW_STATE
data=struct.pack(bebaproto.OFP_EXP_STATE_MOD_PACK_STR, command)
data+=struct.pack(bebaproto.OFP_EXP_STATE_MOD_SET_FLOW_STATE_PACK_STR, table_id, key_count, state, state_mask, hard_rollback, idle_rollback, hard_timeout*1000000, idle_timeout*1000000)
field_extract_format='!B'
if key_count <= bebaproto.MAX_KEY_LEN:
for f in range(key_count):
data+=struct.pack(field_extract_format,keys[f])
exp_type=bebaproto.OFPT_EXP_STATE_MOD
return ofproto_parser.OFPExperimenter(datapath=datapath, experimenter=0xBEBABEBA, exp_type=exp_type, data=data)
def OFPExpMsgDelFlowState(datapath, keys, table_id):
key_count=len(keys)
if key_count > bebaproto.MAX_KEY_LEN:
key_count = 0
LOG.debug("OFPExpMsgDelFlowState: Number of keys given > MAX_KEY_LEN")
command=bebaproto.OFPSC_EXP_DEL_FLOW_STATE
data=struct.pack(bebaproto.OFP_EXP_STATE_MOD_PACK_STR, command)
data+=struct.pack(bebaproto.OFP_EXP_STATE_MOD_DEL_FLOW_STATE_PACK_STR,table_id,key_count)
field_extract_format='!B'
if key_count <= bebaproto.MAX_KEY_LEN:
for f in range(key_count):
data+=struct.pack(field_extract_format,keys[f])
exp_type=bebaproto.OFPT_EXP_STATE_MOD
return ofproto_parser.OFPExperimenter(datapath=datapath, experimenter=0xBEBABEBA, exp_type=exp_type, data=data)
def OFPExpSetGlobalState(datapath, global_state, global_state_mask=0xffffffff):
data=struct.pack(bebaproto.OFP_EXP_STATE_MOD_PACK_STR, bebaproto.OFPSC_EXP_SET_GLOBAL_STATE)
data+=struct.pack(bebaproto.OFP_EXP_STATE_MOD_SET_GLOBAL_STATE_PACK_STR,global_state,global_state_mask)
exp_type=bebaproto.OFPT_EXP_STATE_MOD
return ofproto_parser.OFPExperimenter(datapath=datapath, experimenter=0xBEBABEBA, exp_type=exp_type, data=data)
def OFPExpResetGlobalState(datapath):
data=struct.pack(bebaproto.OFP_EXP_STATE_MOD_PACK_STR, bebaproto.OFPSC_EXP_RESET_GLOBAL_STATE)
exp_type=bebaproto.OFPT_EXP_STATE_MOD
return ofproto_parser.OFPExperimenter(datapath=datapath, experimenter=0xBEBABEBA, exp_type=exp_type, data=data)
def OFPExpStateStatsMultipartRequestBase(datapath, exp_type, table_id=ofproto.OFPTT_ALL, state=None, match=None):
flags = 0 # Zero or ``OFPMPF_REQ_MORE``
get_from_state = 1
if state is None:
get_from_state = 0
state = 0
if match is None:
match = ofproto_parser.OFPMatch()
data = bytearray()
msg_pack_into(bebaproto.OFP_STATE_STATS_REQUEST_0_PACK_STR, data, 0, table_id, get_from_state, state)
offset = bebaproto.OFP_STATE_STATS_REQUEST_0_SIZE
match.serialize(data, offset)
return ofproto_parser.OFPExperimenterStatsRequest(datapath=datapath, flags=flags, experimenter=0xBEBABEBA,
exp_type=exp_type, data=data)
def OFPExpStateStatsMultipartRequest(datapath, table_id=ofproto.OFPTT_ALL, state=None, match=None):
return OFPExpStateStatsMultipartRequestBase(datapath=datapath, exp_type=bebaproto.OFPMP_EXP_STATE_STATS,
table_id=table_id, state=state, match=match)
def OFPExpStateStatsMultipartRequestAndDelete(datapath, table_id=ofproto.OFPTT_ALL, state=None, match=None):
return OFPExpStateStatsMultipartRequestBase(datapath=datapath, exp_type=bebaproto.OFPMP_EXP_STATE_STATS_AND_DELETE,
table_id=table_id, state=state, match=match)
def OFPExpStateStatsMultipartRequestShort(datapath, table_id=ofproto.OFPTT_ALL, state=None, match=None):
return OFPExpStateStatsMultipartRequestBase(datapath=datapath, exp_type=bebaproto.OFPMP_EXP_STATE_STATS_SHORT,
table_id=table_id, state=state, match=match)
def OFPExpStateStatsMultipartRequestAndDeleteShort(datapath, table_id=ofproto.OFPTT_ALL, state=None, match=None):
return OFPExpStateStatsMultipartRequestBase(datapath=datapath, exp_type=bebaproto.OFPMP_EXP_STATE_STATS_AND_DELETE_SHORT,
table_id=table_id, state=state, match=match)
"""
State Sync: Controller asks for flows in a specific state
"""
def OFPExpGetFlowsInState(datapath, table_id=ofproto.OFPTT_ALL, state=None):
return OFPExpStateStatsMultipartRequest(datapath=datapath, table_id=table_id, state=state, match=None)
"""
State Sync: Controller asks for the state of a flow
"""
def OFPExpGetFlowState(datapath, table_id=ofproto.OFPTT_ALL, match=None):
return OFPExpStateStatsMultipartRequest(datapath=datapath, table_id=table_id, state=None, match=match)
"""
State Sync: This function returns the global state of a switch
"""
def OFPExpGlobalStateStatsMultipartRequest(datapath):
flags = 0 # Zero or ``OFPMPF_REQ_MORE``
data=bytearray()
exp_type=bebaproto.OFPMP_EXP_GLOBAL_STATE_STATS
return ofproto_parser.OFPExperimenterStatsRequest(datapath=datapath, flags=flags, experimenter=0xBEBABEBA, exp_type=exp_type, data=data)
def OFPErrorExperimenterMsg_handler(ev):
msg = ev.msg
LOG.debug('')
LOG.debug('OFPErrorExperimenterMsg received.')
LOG.debug('version=%s, msg_type=%s, msg_len=%s, xid=%s',hex(msg.version),
hex(msg.msg_type), hex(msg.msg_len), hex(msg.xid))
LOG.debug(' `-- msg_type: %s',ofproto.ofp_msg_type_to_str(msg.msg_type))
LOG.debug("OFPErrorExperimenterMsg(type=%s, exp_type=%s, experimenter_id='%s')",hex(msg.type),
hex(msg.exp_type), hex(msg.experimenter))
LOG.debug(' |-- type: %s',ofproto.ofp_error_type_to_str(msg.type))
LOG.debug(' |-- exp_type: %s',bebaproto.ofp_error_code_to_str(msg.type,msg.exp_type))
LOG.debug(' |-- experimenter_id: %s',hex(msg.experimenter))
(version, msg_type, msg_len, xid) = struct.unpack_from(ofproto.OFP_HEADER_PACK_STR,
six.binary_type(msg.data))
LOG.debug(
' `-- data: version=%s, msg_type=%s, msg_len=%s, xid=%s',
hex(version), hex(msg_type), hex(msg_len), hex(xid))
def OFPExpMsgAddPktTmp(datapath, pkttmp_id, pkt_data):
command=bebaproto.OFPSC_ADD_PKTTMP
data=struct.pack(bebaproto.OFP_EXP_PKTTMP_MOD_PACK_STR, command)
data+=struct.pack(bebaproto.OFP_EXP_PKTTMP_MOD_ADD_PKTTMP_PACK_STR, pkttmp_id)
data+=pkt_data
#print("Data:%s\n" % ''.join( [ "%02X " % ord( x ) for x in data ] ).strip())
exp_type=bebaproto.OFPT_EXP_PKTTMP_MOD
return ofproto_parser.OFPExperimenter(datapath=datapath, experimenter=0xBEBABEBA, exp_type=exp_type, data=data)
def OFPExpMsgDelPktTmp(datapath, pkttmp_id):
command=bebaproto.OFPSC_DEL_PKTTMP
data=struct.pack(bebaproto.OFP_EXP_PKTTMP_MOD_PACK_STR, command)
data+=struct.pack(bebaproto.OFP_EXP_PKTTMP_MOD_DEL_PKTTMP_PACK_STR, pkttmp_id)
#LOG.error("OFPExpMsgSetFlowState: Number of keys given > MAX_KEY_LEN")
exp_type=bebaproto.OFPT_EXP_PKTTMP_MOD
return ofproto_parser.OFPExperimenter(datapath=datapath, experimenter=0xBEBABEBA, exp_type=exp_type, data=data)
class OFPInstructionInSwitchPktGen(ofproto_parser.OFPInstruction):
"""
In Switch Packet Generation instruction
This instruction triggers the generation of a packet.
================ ======================================================
Attribute Description
================ ======================================================
type OFPIT_EXPERIMENTER
experimenter_id BEBA_VENDOR_ID
instr_type OFPIT_IN_SWITCH_PKT_GEN
actions list of OpenFlow action class
================ ======================================================
"""
def __init__(self, pkttmp_id, actions=None, len_=None):
super(OFPInstructionInSwitchPktGen, self).__init__()
self.type = ofproto.OFPIT_EXPERIMENTER
self.experimenter_id = bebaproto.BEBA_EXPERIMENTER_ID
self.instr_type = bebaproto.OFPIT_IN_SWITCH_PKT_GEN
self.pkttmp_id = pkttmp_id
for a in actions:
assert isinstance(a, ofproto_parser.OFPAction)
self.actions = actions
@classmethod
def parser(cls, buf, offset):
(type_, len_, experimenter_id_, instr_type_) = struct.unpack_from(
bebaproto.OFP_INSTRUCTION_INSWITCH_PKT_GEN_PACK_STR,
buf, offset)
offset += bebaproto.OFP_INSTRUCTION_INSWITCH_PKT_GEN_SIZE
actions = []
actions_len = len_ - bebaproto.OFP_INSTRUCTION_INSWITCH_PKT_GEN_SIZE
while actions_len > 0:
a = ofproto_parser.OFPAction.parser(buf, offset)
actions.append(a)
actions_len -= a.len
offset += a.len
inst = cls(type_, actions)
inst.len = len_
inst.experimenter_id = experimenter_id_
inst.instr_type = instr_type_
return inst
def serialize(self, buf, offset):
action_offset = offset + bebaproto.OFP_INSTRUCTION_INSWITCH_PKT_GEN_SIZE
if self.actions:
for a in self.actions:
a.serialize(buf, action_offset)
action_offset += a.len
self.len = action_offset - offset
pad_len = utils.round_up(self.len, 8) - self.len
msg_pack_into("%dx" % pad_len, buf, action_offset)
self.len += pad_len
msg_pack_into(bebaproto.OFP_INSTRUCTION_INSWITCH_PKT_GEN_PACK_STR,
buf, offset, self.type, self.len, self.experimenter_id,
self.instr_type, self.pkttmp_id)
class OFPStateEntry(object):
def __init__(self, key_count=None, key=None, state=None):
super(OFPStateEntry, self).__init__()
self.key_count=key_count
self.key = key
self.state = state
@classmethod
def parser(cls, buf, offset, key_count, state):
entry = OFPStateEntry(key_count=key_count, state=state)
entry.key = []
if entry.key_count <= bebaproto.MAX_KEY_LEN:
for f in range(entry.key_count):
key=struct.unpack_from('!B',buf,offset,)
entry.key.append(key[0])
offset +=1
offset += (utils.round_up(entry.key_count, 8) - entry.key_count)
return entry, offset
class OFPStateStats(StringifyMixin):
def __init__(self, table_id=None, dur_sec=None, dur_nsec=None, field_count=None, fields=None,
entry=None,length=None, hard_rb=None, idle_rb=None, hard_to=None, idle_to=None):
super(OFPStateStats, self).__init__()
self.length = 0
self.table_id = table_id
self.dur_sec = dur_sec
self.dur_nsec = dur_nsec
self.field_count = field_count
self.fields = fields
self.entry = entry
self.hard_to = hard_to
self.hard_rb = hard_rb
self.idle_to = idle_to
self.hard_rb = hard_rb
@classmethod
def parser(cls, msg, offset=0):
state_stats_list = []
buf = msg.body.data
while len(buf)-offset > 0:
state_stats = cls()
(state_stats.length, state_stats.table_id, state_stats.key_len, state_stats.dur_sec,
state_stats.dur_nsec, state_stats.hard_rb, state_stats.idle_rb,state_stats.hard_to,
state_stats.idle_to, state_stats.state) = struct.unpack_from(
bebaproto.OFP_STATE_STATS_PACK_STR, buf, offset)
offset += bebaproto.OFP_STATE_STATS_SIZE
if state_stats.table_id not in msg.datapath.lookup_scope:
continue
state_stats.fields = msg.datapath.lookup_scope[state_stats.table_id]
state_stats.field_count = len(state_stats.fields)
state_stats.entry, offset = OFPStateEntry.parser(buf, offset, state_stats.key_len, state_stats.state)
state_stats_list.append(state_stats)
return state_stats_list
class OFPStateStatsShort(StringifyMixin):
def __init__(self, table_id=None, dur_sec=None, dur_nsec=None, field_count=None, fields=None,
entry=None, length=None, hard_rb=None, idle_rb=None, hard_to=None, idle_to=None):
super(OFPStateStatsShort, self).__init__()
self.length = 0
self.table_id = table_id
self.dur_sec = dur_sec
self.dur_nsec = dur_nsec
self.field_count = field_count
self.fields = fields
self.entry = entry
self.hard_to = hard_to
self.hard_rb = hard_rb
self.idle_to = idle_to
self.hard_rb = hard_rb
@classmethod
def parser(cls, msg, offset=0):
state_stats_list = []
buf = msg.body.data
while len(buf) - offset > 0:
state_stats = cls()
(state_stats.length, state_stats.table_id, state_stats.key_len, state_stats.state) = struct.unpack_from(
bebaproto.OFP_STATE_STATS_SHORT_PACK_STR, buf, offset)
offset += bebaproto.OFP_STATE_STATS_SHORT_SIZE
if state_stats.table_id not in msg.datapath.lookup_scope:
continue
state_stats.fields = msg.datapath.lookup_scope[state_stats.table_id]
state_stats.field_count = len(state_stats.fields)
state_stats.entry, offset = OFPStateEntry.parser(buf, offset, state_stats.key_len, state_stats.state)
state_stats_list.append(state_stats)
return state_stats_list
class OFPGlobalStateStats(StringifyMixin):
def __init__(self, global_state=None):
super(OFPGlobalStateStats, self).__init__()
self.global_state = global_state
@classmethod
def parser(cls, buf, offset):
global_state_stats = cls()
(global_state_stats.global_state, ) = struct.unpack_from('!4xI', buf, offset)
return global_state_stats
def get_field_string(field,key,key_count,offset):
if field==ofproto.OXM_OF_IN_PORT:
if key_count!=0:
length = 4
value = struct.unpack('<I', array('B',key[offset:offset+length]))[0]
return ("in_port=\"%d\""%(value),length)
else:
return ("in_port=*",0)
elif field==ofproto.OXM_OF_IN_PHY_PORT:
if key_count!=0:
length = 4
VLAN_VID_MASK = 0x0fff
value = struct.unpack('<I', array('B',key[offset:offset+length]))[0] & VLAN_VID_MASK
return ("in_phy_port=\"%d\""%(value),length)
else:
return ("in_phy_port=*",0)
elif field==ofproto.OXM_OF_VLAN_VID:
if key_count!=0:
length = 2
value = struct.unpack('<H', array('B',key[offset:offset+length]))[0]
return ("vlan_vid=\"%d\""%(value),length)
else:
return ("vlan_vid=*",0)
elif field==ofproto.OXM_OF_VLAN_PCP:
if key_count!=0:
length = 1
value = struct.unpack('<B', array('B',key[offset:offset+length]))[0] & 0x7
return ("vlan_pcp=\"%d\""%(value),length)
else:
return ("vlan_pcp=*",0)
elif field==ofproto.OXM_OF_ETH_TYPE:
if key_count!=0:
length = 2
value = struct.unpack('<H', array('B',key[offset:offset+length]))[0]
return ("eth_type=\"%d\""%(value),length)
else:
return ("eth_type=*",0)
elif field==ofproto.OXM_OF_TCP_SRC:
if key_count!=0:
length = 2
value = struct.unpack('<H', array('B',key[offset:offset+length]))[0]
return ("tcp_src=\"%d\""%(value),length)
else:
return ("tcp_src=*",0)
elif field==ofproto.OXM_OF_TCP_DST:
if key_count!=0:
length = 2
value = struct.unpack('<H', array('B',key[offset:offset+length]))[0]
return ("tcp_dst=\"%d\""%(value),length)
else:
return ("tcp_dst=*",0)
elif field==ofproto.OXM_OF_TCP_FLAGS:
if key_count!=0:
length = 2
value = struct.unpack('<H', array('B',key[offset:offset+length]))[0]
return ("tcp_flags=\"%d\""%(value),length)
else:
return ("tcp_flags=*",0)
elif field==ofproto.OXM_OF_UDP_SRC:
if key_count!=0:
length = 2
value = struct.unpack('<H', array('B',key[offset:offset+length]))[0]
return ("udp_src=\"%d\""%(value),length)
else:
return ("udp_src=*",0)
elif field==ofproto.OXM_OF_UDP_DST:
if key_count!=0:
length = 2
value = struct.unpack('<H', array('B',key[offset:offset+length]))[0]
return ("udp_dst=\"%d\""%(value),length)
else:
return ("udp_dst=*",0)
elif field==ofproto.OXM_OF_SCTP_SRC:
if key_count!=0:
length = 2
value = struct.unpack('<H', array('B',key[offset:offset+length]))[0]
return ("sctp_src=\"%d\""%(value),length)
else:
return ("sctp_src=*",0)
elif field==ofproto.OXM_OF_SCTP_DST:
if key_count!=0:
length = 2
value = struct.unpack('<H', array('B',key[offset:offset+length]))[0]
return ("sctp_dst=\"%d\""%(value),length)
else:
return ("sctp_dst=*",0)
elif field==ofproto.OXM_OF_ETH_SRC:
if key_count!=0:
length = 6
return ("eth_src=\"%02x:%02x:%02x:%02x:%02x:%02x\""%(key[offset],key[offset+1],key[offset+2],key[offset+3],key[offset+4],key[offset+5]),length)
else:
return ("eth_src=*",0)
elif field==ofproto.OXM_OF_ETH_DST:
if key_count!=0:
length = 6
return ("eth_dst=\"%02x:%02x:%02x:%02x:%02x:%02x\""%(key[offset],key[offset+1],key[offset+2],key[offset+3],key[offset+4],key[offset+5]),length)
else:
return ("eth_dst=*",0)
elif field==ofproto.OXM_OF_IPV4_SRC:
if key_count!=0:
length = 4
return ("ipv4_src=\"%d.%d.%d.%d\""%(key[offset],key[offset+1],key[offset+2],key[offset+3]),length)
else:
return ("ipv4_src=*",0)
elif field==ofproto.OXM_OF_IPV4_DST:
if key_count!=0:
length = 4
return ("ipv4_dst=\"%d.%d.%d.%d\""%(key[offset],key[offset+1],key[offset+2],key[offset+3]),length)
else:
return ("ipv4_dst=*",0)
elif field==ofproto.OXM_OF_IP_PROTO:
if key_count!=0:
length = 1
value = struct.unpack('<B', array('B',key[offset:offset+length]))[0]
return ("ip_proto=\"%d\""%(value),length)
else:
return ("ip_proto=*",0)
elif field==ofproto.OXM_OF_IP_DSCP:
if key_count!=0:
length = 1
value = struct.unpack('<B', array('B',key[offset:offset+length]))[0] & 0x3f
return ("ip_dscp=\"%d\""%(value),length)
else:
return ("ip_dscp=*",0)
elif field==ofproto.OXM_OF_IP_ECN:
if key_count!=0:
length = 1
value = struct.unpack('<B', array('B',key[offset:offset+length]))[0] & 0x3
return ("ip_ecn=\"%d\""%(value),length)
else:
return ("ip_ecn=*",0)
elif field==ofproto.OXM_OF_ICMPV4_TYPE:
if key_count!=0:
length = 1
value = struct.unpack('<B', array('B',key[offset:offset+length]))[0]
return ("icmpv4_type=\"%d\""%(value),length)
else:
return ("icmpv4_type=*",0)
elif field==ofproto.OXM_OF_ICMPV4_CODE:
if key_count!=0:
length = 1
value = struct.unpack('<B', array('B',key[offset:offset+length]))[0]
return ("icmpv4_code=\"%d\""%(value),length)
else:
return ("icmpv4_code=*",0)
elif field==ofproto.OXM_OF_ARP_SHA:
if key_count!=0:
length = 6
return ("arp_sha=\"%02x:%02x:%02x:%02x:%02x:%02x\""%(key[offset],key[offset+1],key[offset+2],key[offset+3],key[offset+4],key[offset+5]),length)
else:
return ("arp_sha=*",0)
elif field==ofproto.OXM_OF_ARP_THA:
if key_count!=0:
length = 6
return ("arp_tha=\"%02x:%02x:%02x:%02x:%02x:%02x\""%(key[offset],key[offset+1],key[offset+2],key[offset+3],key[offset+4],key[offset+5]),length)
else:
return ("arp_tha=*",0)
elif field==ofproto.OXM_OF_ARP_SPA:
if key_count!=0:
length = 4
return ("arp_spa=\"%d.%d.%d.%d\""%(key[offset],key[offset+1],key[offset+2],key[offset+3]),length)
else:
return ("arp_spa=*",0)
elif field==ofproto.OXM_OF_ARP_TPA:
if key_count!=0:
length = 4
return ("arp_tpa=\"%d.%d.%d.%d\""%(key[offset],key[offset+1],key[offset+2],key[offset+3]),length)
else:
return ("arp_tpa=*",0)
elif field==ofproto.OXM_OF_ARP_OP:
if key_count!=0:
length = 2
value = struct.unpack('<H', array('B',key[offset:offset+length]))[0]
return ("arp_op=\"%d\""%(value),length)
else:
return ("arp_op=*",0)
elif field==ofproto.OXM_OF_IPV6_SRC:
if key_count!=0:
length = 16
value = []
for q in range(8):
value[q]=format(struct.unpack('<H', array('B',key[offset:offset+2]))[0],'x')
offset += 2
return ("nw_src_ipv6=\"%s:%s:%s:%s:%s:%s:%s:%s\""%(value[0],value[1],value[2],value[3],value[4],value[5],value[6],value[7]),length)
else:
return ("nw_src_ipv6=*",0)
elif field==ofproto.OXM_OF_IPV6_DST:
if key_count!=0:
length = 16
value = []
for q in range(8):
value.append(format(struct.unpack('<H', array('B',key[offset:offset+2]))[0],'x'))
offset += 2
return ("nw_dst_ipv6=\"%s:%s:%s:%s:%s:%s:%s:%s\""%(value[0],value[1],value[2],value[3],value[4],value[5],value[6],value[7]),length)
else:
return ("nw_dst_ipv6=*",0)
elif field==ofproto.OXM_OF_IPV6_ND_TARGET:
if key_count!=0:
length = 16
value = []
for q in range(8):
value[q]=format(struct.unpack('<H', array('B',key[offset:offset+2]))[0],'x')
offset += 2
return ("ipv6_nd_target=\"%s:%s:%s:%s:%s:%s:%s:%s\""%(value[0],value[1],value[2],value[3],value[4],value[5],value[6],value[7]),length)
else:
return ("ipv6_nd_target=*",0)
elif field==ofproto.OXM_OF_IPV6_ND_SLL:
if key_count!=0:
length = 6
return ("ipv6_nd_sll=\"%02x:%02x:%02x:%02x:%02x:%02x\""%(key[offset],key[offset+1],key[offset+2],key[offset+3],key[offset+4],key[offset+5]),length)
else:
return ("ipv6_nd_sll=*",0)
elif field==ofproto.OXM_OF_IPV6_ND_TLL:
if key_count!=0:
length = 6
return ("ipv6_nd_tll=\"%02x:%02x:%02x:%02x:%02x:%02x\""%(key[offset],key[offset+1],key[offset+2],key[offset+3],key[offset+4],key[offset+5]),length)
else:
return ("ipv6_nd_tll=*",0)
elif field==ofproto.OXM_OF_IPV6_FLABEL:
if key_count!=0:
length = 4
value = struct.unpack('<I', array('B',key[offset:offset+length]))[0] & 0x000fffff
return ("ipv6_flow_label=\"%d\""%(value),length)
else:
return ("ipv6_flow_label=*",0)
elif field==ofproto.OXM_OF_ICMPV6_TYPE:
if key_count!=0:
length = 1
value = struct.unpack('<B', array('B',key[offset:offset+length]))[0]
return ("icmpv6_type=\"%d\""%(value),length)
else:
return ("icmpv6_type=*",0)
elif field==ofproto.OXM_OF_ICMPV6_CODE:
if key_count!=0:
length = 1
value = struct.unpack('<B', array('B',key[offset:offset+length]))[0]
return ("icmpv6_code=\"%d\""%(value),length)
else:
return ("icmpv6_code=*",0)
elif field==ofproto.OXM_OF_MPLS_LABEL:
if key_count!=0:
length = 4
value = struct.unpack('<I', array('B',key[offset:offset+length]))[0] & 0x000fffff
return ("mpls_label=\"%d\""%(value),length)
else:
return ("mpls_label=*",0)
elif field==ofproto.OXM_OF_MPLS_TC:
if key_count!=0:
length = 1
value = struct.unpack('<B', array('B',key[offset:offset+length]))[0] & 0x3
return ("mpls_tc=\"%d\""%(value),length)
else:
return ("mpls_tc=*",0)
elif field==ofproto.OXM_OF_MPLS_BOS:
if key_count!=0:
length = 1
value = struct.unpack('<B', array('B',key[offset:offset+length]))[0] & 0x1
return ("mpls_bos=\"%d\""%(value),length)
else:
return ("mpls_bos=*",0)
elif field==ofproto.OXM_OF_PBB_ISID:
if key_count!=0:
length = 4
value = struct.unpack('<I', array('B',key[offset:offset+length]))[0]
return ("pbb_isid=\"%d\""%(value),length)
else:
return ("pbb_isid=*",0)
elif field==ofproto.OXM_OF_TUNNEL_ID:
if key_count!=0:
length = 8
value = struct.unpack('<Q', array('B',key[offset:offset+length]))[0]
return ("tunnel_id=\"%d\""%(value),length)
else:
return ("tunnel_id=*",0)
elif field==ofproto.OXM_OF_IPV6_EXTHDR:
if key_count!=0:
length = 2
value = struct.unpack('<H', array('B',key[offset:offset+length]))[0]
return ("ext_hdr=\"%d\""%(value),length)
else:
return ("ext_hdr=*",0)
def state_entry_key_to_str(state_stats):
offset = 0
s = ''
for field in state_stats.fields[:state_stats.field_count]:
(string,field_len) = get_field_string(field,state_stats.entry.key,state_stats.entry.key_count,offset)
s += string
offset += field_len
if field != state_stats.fields[state_stats.field_count-1]:
s += ","
return s
'''
Global states are 32, numbered from 0 to 31 from right to left
masked_global_state_from_str("0*1100") -> **************************0*1100 -> (12,47)
masked_global_state_from_str("0*1100",12) -> ***************0*1100*********** -> (49152, 192512)
'''
def masked_global_state_from_str(string,offset=0):
import re
str_len=len(string)
if re.search('r[^01*]', string) or str_len>32 or str_len<1:
print("ERROR: global_state string can only contain 0,1 and * and must have at least 1 bit and at most 32 bits!")
return (0,0)
if offset>31 or offset<0:
print("ERROR: offset must be in range 0-31!")
return (0,0)
if str_len+offset>32:
print("ERROR: offset is too big")
return (0,0)
mask=['0']*32
value=['0']*32
for i in range(offset,str_len+offset):
if not string[str_len-1+offset-i]=="*":
mask[31-i]="1"
value[31-i]=string[str_len-1+offset-i]
mask=''.join(mask)
value=''.join(value)
return (int(value,2),int(mask,2))
'''
state field is 32bit long
Thanks to the mask we can divide the field in multiple substate matchable with masks.
substate(state,section,sec_count)
state = state to match
section = number of the selected subsection (starts from 1 from the right)
sec_count = number of how many subsection the state field has been divided
substate(5,2,4) -> |********|********|00000101|********|-> (1280,16711680)
'''
def substate(state,section,sec_count):
if not isinstance(state, int) or not isinstance(section, int) or not isinstance(sec_count, int):
print("ERROR: parameters must be integers!")
return(0,0)
if state < 0 or section < 0 or sec_count < 0:
print("ERROR: parameters must be positive!")
return(0,0)
if 32%sec_count != 0:
print("ERROR: the number of sections must be a divisor of 32")
return(0,0)
section_len = 32/sec_count
if state >= pow(2,section_len):
print("ERROR: state exceed the section's length")
return(0,0)
if section not in range (1,sec_count+1):
print("ERROR: section not exist. It must be between 1 and sec_count")
return(0,0)
sec_count = sec_count -1
count = 1
starting_point = section*section_len
mask=['0']*32
value=['0']*32
bin_state=['0']*section_len
state = bin(state)
state = ''.join(state[2:])
for i in range(0,len(state)):
bin_state [section_len-1-i]= state[len(state)-1-i]
for i in range(starting_point,starting_point+section_len):
value[31-i]=bin_state[section_len - count]
count = count + 1
mask[31-i]="1"
mask=''.join(mask)
value=''.join(value)
return (int(value,2),int(mask,2))
###############################################################################################################################
'''
[Beba to Open vSwitch wrapper]
An Beba application can be run by an Open vSwitch softswitch without Beba support by adding
'@Beba2OVSWrapper' just before def switch_features_handler(self, ev), after '@set_ev_cls()'
$ sudo mn --topo single,4 --mac --switch ovsk --controller remote ---> starts Open vSwitch (OpenFlow only)
$ sudo mn --topo single,4 --mac --switch user --controller remote ---> starts ofsoftswitch13 (OpenFlow + Beba)
$ ryu-manager [app_name]
How stuff works:
we need to intercept any message containing Beba code (Beba messages, FlowMod matching on 'state', FlowMod containing
SetState action, ...). The best way is intercepting any call to send_msg() in order to filter/modify/drop the outgoing message.
We don't want to touch Ryu code and we'd like minimal modifications to Beba applications code.
send_msg() is a method from Datapath class, so we need to extend it to override send_msg().
The Datapath object 'datapath' should be casted to a OVSDatapath object and the best moment is when the controller
communicates with the switch for the first time (so in switch_features_handler()).
We want to cast the object just before the execution of the user-defined handler, so we can use a decorator to execute some
additional code before the user-defined function. A decorator is a function that takes a function object as an argument, and
returns a function object as a return value.
'''
from ryu.controller.controller import Datapath
from sets import Set
'''
OVSDatapath class inherits Datapath class to override send_msg() method in order to intercept and adapt Beba messages.
Finally the original send_msg() is called, when appropriate (e.g. messages OFPExpMsgConfigureStatefulTable and OFPExpMsgKeyExtract
just update OVSDatapath internal state withtout being sent to the switch)
'''
class OVSDatapath(Datapath):
def send_msg(self, msg):
'''
In Beba a stateful stage has a state table and a flow table with the same table_id.
In Open vSwitch a stateful stage has two separated flow tables with adjacent table_ids
'''
def get_state_table_id(table_id):
return 2*table_id
def get_flow_table_id(table_id):
return 2*table_id+1
if isinstance(msg,ofproto_parser.OFPExperimenter) and msg.experimenter==0xBEBABEBA and msg.exp_type==bebaproto.OFPT_EXP_STATE_MOD:
# We are forced to unpack because OFPExpMsgConfigureStatefulTable is not a class with attributes; for simplicity it's a
# method returning an instance of OFPExperimenter with the packed payload (refactoring!?!)
command_offset = struct.calcsize(bebaproto.OFP_EXP_STATE_MOD_PACK_STR)
(command,) = struct.unpack(bebaproto.OFP_EXP_STATE_MOD_PACK_STR, msg.data[:command_offset])
if command == bebaproto.OFPSC_EXP_STATEFUL_TABLE_CONFIG:
(table_id,stateful) = struct.unpack(bebaproto.OFP_EXP_STATE_MOD_STATEFUL_TABLE_CONFIG_PACK_STR, msg.data[command_offset:command_offset+struct.calcsize(bebaproto.OFP_EXP_STATE_MOD_STATEFUL_TABLE_CONFIG_PACK_STR)])
# "control flow" table miss in State Table
# OVS have all port numbers into the 16-bit range (like in OF1.0), while later OF version use 32-bit port numbers.
# NXActionResubmitTable needs 16-bit port numbers, so we cannot put ofproto.OFPP_IN_PORT: we put 0xfff8 (OFPP_IN_PORT=0xfff8 in OF1.0)
# https://github.com/openvswitch/ovs/blob/master/OPENFLOW-1.1%2B.md
match = ofproto_parser.OFPMatch(reg1=0)
actions = [ofproto_parser.OFPActionSetField(reg1=1),
ofproto_parser.NXActionResubmitTable(0xfff8,get_state_table_id(table_id)),
ofproto_parser.NXActionResubmitTable(0xfff8,get_flow_table_id(table_id))]
inst = [ofproto_parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, actions)]
mod = ofproto_parser.OFPFlowMod(datapath=self, table_id=get_state_table_id(table_id), priority=10, match=match, instructions=inst)
super(OVSDatapath, self).send_msg(mod)
# "return DEFAULT state" in State Table
match = ofproto_parser.OFPMatch(reg1=1)
actions = [ofproto_parser.OFPActionSetField(reg0=0)]
inst = [ofproto_parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, actions)]
mod = ofproto_parser.OFPFlowMod(datapath=self, table_id=get_state_table_id(table_id), priority=10, match=match, instructions=inst)
super(OVSDatapath, self).send_msg(mod)
# keep track of stateful stages (useful when handling GotoTable instructions)
self.stateful_stages_in_use.add(table_id)
# OFPExpMsgConfigureStatefulTable msg is dropped
return
elif command == bebaproto.OFPSC_EXP_SET_L_EXTRACTOR or command == bebaproto.OFPSC_EXP_SET_U_EXTRACTOR:
(table_id,field_count) = struct.unpack(bebaproto.OFP_EXP_STATE_MOD_EXTRACTOR_PACK_STR,msg.data[command_offset:command_offset+struct.calcsize(bebaproto.OFP_EXP_STATE_MOD_EXTRACTOR_PACK_STR)])
if field_count>0:
fields_offset = command_offset+struct.calcsize(bebaproto.OFP_EXP_STATE_MOD_EXTRACTOR_PACK_STR)
field_size = struct.calcsize('!I')
if command == bebaproto.OFPSC_EXP_SET_L_EXTRACTOR:
self.lookup_scope[table_id] = []
for f in range(field_count):
current_field_offset = fields_offset+field_size*f
self.lookup_scope[table_id].append( struct.unpack('!I',msg.data[current_field_offset : current_field_offset+field_size])[0] )
elif command == bebaproto.OFPSC_EXP_SET_U_EXTRACTOR:
self.update_scope[table_id] = []
for f in range(field_count):
current_field_offset = fields_offset+field_size*f
self.update_scope[table_id].append( struct.unpack('!I',msg.data[current_field_offset : current_field_offset+field_size])[0] )
else:
LOG.debug("ERROR: no fields in lookup/update scope!")
# OFPExpMsgKeyExtract msg is dropped
return
elif command == bebaproto.OFPSC_EXP_SET_FLOW_STATE:
# We should send a FlowMod MODIFY by converting 'keys' into FlowMod's match fields and 'state' into OFPActionSetField(reg0=state) '''
'''
TODO: timeouts handling. Up to now timeouts are ignored (see comments below in OFPAT_EXP_SET_STATE)
TODO: 'state_mask' handling
Until now 'state_mask' is ignored because in OF1.3 SetField actions does not allow mask (only OF1.5 allows it with EXT-314)
In fact ovs-ofctl translates a set_field into a reg_load when we force OF version to 1.3.
sudo ovs-ofctl add-flow s1 -O OpenFlow13 "table=0 action=set_field:1/5->reg0" --> actions=load:0x1->NXM_NX_REG0[0],load:0->NXM_NX_REG0[2]
sudo ovs-ofctl add-flow s1 -O OpenFlow13 "table=0 action=set_field:1->reg0" --> actions=set_field:0x1->reg0
Seacrh for "set_field:value[/mask]->dst" in http://openvswitch.org/support/dist-docs/ovs-ofctl.8.txt
Ryu API for OF1.3 does not include anymore NXActionRegLoad. If state_mask is 0xFFFFFFFF we can use set_field, otherwise
we need another strategy. Maybe porting NXActionRegLoad from OF1.0?
'''
(table_id, key_count, state, state_mask, hard_rollback, idle_rollback, hard_timeout, idle_timeout) = struct.unpack(bebaproto.OFP_EXP_STATE_MOD_SET_FLOW_STATE_PACK_STR, msg.data[command_offset:command_offset+struct.calcsize(bebaproto.OFP_EXP_STATE_MOD_SET_FLOW_STATE_PACK_STR)])
if key_count>0:
lookup_fields = {}
key_starting_offset = command_offset+struct.calcsize(bebaproto.OFP_EXP_STATE_MOD_SET_FLOW_STATE_PACK_STR)
key_offset = 0
# Parse the remaning payload to get the matching values of all lookup fields
for f in self.lookup_scope[table_id]:
field_bytes_num = ofproto_parser.OFPMatchField._FIELDS_HEADERS[f](f,0,0).oxm_len()
# if f is ofproto.OXM_OF_ETH_SRC then field_name would be 'eth_dst'
field_name = ofproto_parser._NXFlowSpec._parse_subfield( bytearray(struct.pack('!IH',f,0)) )[0]
key = list(struct.unpack('!'+'B'*field_bytes_num, msg.data[key_starting_offset+key_offset:key_starting_offset+key_offset+field_bytes_num]))
# We'd like something like lookup_fields['eth_dst']='00:00:00:0a:0a:0a'
lookup_fields[field_name] = self.bytes_to_match_value(f,key)
key_offset += field_bytes_num
self.add_prereq_match_to_dict(self.lookup_scope[table_id],lookup_fields)
match = ofproto_parser.OFPMatch(reg1=1,**lookup_fields)
actions = [ofproto_parser.OFPActionSetField(reg1=0),ofproto_parser.OFPActionSetField(reg0=state)]
inst = [ofproto_parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, actions)]
mod = ofproto_parser.OFPFlowMod(datapath=self, cookie=0, cookie_mask=0,table_id=get_state_table_id(table_id),
command=ofproto.OFPFC_ADD, idle_timeout=0, hard_timeout=0, priority=100, buffer_id=ofproto.OFP_NO_BUFFER,
out_port=ofproto.OFPP_ANY, out_group=ofproto.OFPG_ANY, match=match, instructions=inst)
super(OVSDatapath, self).send_msg(mod)
else:
LOG.debug("ERROR: empty key in STATE_MOD message!")
return
elif command == bebaproto.OFPSC_EXP_DEL_FLOW_STATE:
# We should send a FlowMod DELETE by converting 'keys' into FlowMod's match fields
(table_id, key_count) = struct.unpack(bebaproto.OFP_EXP_STATE_MOD_DEL_FLOW_STATE_PACK_STR, msg.data[command_offset:command_offset+struct.calcsize(bebaproto.OFP_EXP_STATE_MOD_DEL_FLOW_STATE_PACK_STR)])
if key_count>0:
lookup_fields = {}
key_starting_offset = command_offset+struct.calcsize(bebaproto.OFP_EXP_STATE_MOD_DEL_FLOW_STATE_PACK_STR)
key_offset = 0
# Parse the remaning payload to get the matching values of all lookup fields
for f in self.lookup_scope[table_id]:
field_bytes_num = ofproto_parser.OFPMatchField._FIELDS_HEADERS[f](f,0,0).oxm_len()
# if f is ofproto.OXM_OF_ETH_SRC then field_name would be 'eth_dst'
field_name = ofproto_parser._NXFlowSpec._parse_subfield( bytearray(struct.pack('!IH',f,0)) )[0]
key = list(struct.unpack('!'+'B'*field_bytes_num, msg.data[key_starting_offset+key_offset:key_starting_offset+key_offset+field_bytes_num]))
# We'd like something like lookup_fields['eth_dst']='00:00:00:0a:0a:0a'
lookup_fields[field_name] = self.bytes_to_match_value(f,key)
key_offset += field_bytes_num
self.add_prereq_match_to_dict(self.lookup_scope[table_id],lookup_fields)
match = ofproto_parser.OFPMatch(reg1=1,**lookup_fields)
mod = ofproto_parser.OFPFlowMod(datapath=self, cookie=0, cookie_mask=0,table_id=get_state_table_id(table_id),
command=ofproto.OFPFC_DELETE, idle_timeout=0, hard_timeout=0, priority=100, buffer_id=ofproto.OFP_NO_BUFFER,
out_port=ofproto.OFPP_ANY, out_group=ofproto.OFPG_ANY, match=match)
super(OVSDatapath, self).send_msg(mod)
else:
LOG.debug("ERROR: empty key in STATE_MOD message!")
return
elif command == bebaproto.OFPSC_EXP_SET_GLOBAL_STATE:
''' TODO: global states could be implemented by prepending a stage with just one table miss entry that sets reg8=global state value.
We should send a FlowMod ADD. NB get_state_table_id() and get_flow_table_id() return value should be sincreased by 1 '''
return
elif command == bebaproto.OFPSC_EXP_RESET_GLOBAL_STATE:
''' TODO: We could send a FlowMod MOD that sets reg8=0 (or that just do GotoTable(1) ) in the table miss entry'''
return
elif isinstance(msg,ofproto_parser.OFPExperimenterStatsRequest) and msg.experimenter==0xBEBABEBA:
if msg.exp_type==bebaproto.OFPMP_EXP_STATE_STATS:
''' TODO: In Open vSwitch the state table is a simple flow table => we could send a OFPMultipartRequest, maybe '''
elif msg.exp_type==bebaproto.OFPMP_EXP_GLOBAL_STATE_STATS:
''' TODO: in Open vSwitch, global states are a flow entry in the first table => we could send a OFPMultipartRequest, maybe '''
elif msg.exp_type==bebaproto.OFPMP_EXP_STATE_STATS_AND_DELETE:
''' TODO '''
return
elif isinstance(msg,ofproto_parser.OFPFlowMod):
# [step 1 ] check for the presence of any Beba action in OFPInstructionActions
for instr in msg.instructions:
if isinstance(instr, ofproto_parser.OFPInstructionActions) and instr.type in [ofproto.OFPIT_WRITE_ACTIONS , ofproto.OFPIT_APPLY_ACTIONS]:
filtered_action_set = []
for act in instr.actions:
if isinstance(act, ofproto_parser.OFPActionExperimenterUnknown) and act.experimenter == 0xBEBABEBA:
(act_type,) = struct.unpack('!I', act.data[:struct.calcsize('!I')])
if act_type == bebaproto.OFPAT_EXP_SET_STATE:
(act_type, state, state_mask, table_id, hard_rollback, idle_rollback, hard_timeout, idle_timeout) = struct.unpack(bebaproto.OFP_EXP_ACTION_SET_STATE_PACK_STR, act.data[:struct.calcsize(bebaproto.OFP_EXP_ACTION_SET_STATE_PACK_STR)])
''' TODO: timeouts handling. Up to now timeouts are ignored because OF flow entry's timeouts can be set only when a flow entry is added! (e.g. created for the first time) '''
''' TODO: multiple rollback states
Rollback state!=0 could be supported with 2 learn actions, one with high priority (say 200) with the user-defined timeout and load:state->reg0,
the other with the classic priority 100, no timeouts and load:rollback->reg0. But how can we manage a state transitions with 2 (I/H) possible rollbacks? '''
specs = [ofproto_parser.NXFlowSpecMatch(dst=('reg1', 0),n_bits=32,src=1),
ofproto_parser.NXFlowSpecLoad(dst=('reg1',0),n_bits=32,src=0)]
specs.extend(self.generate_NXFlowSpecMatch_and_prereq(table_id))
specs.extend(self.generate_NXFlowSpecLoad(state,state_mask))
learn_action = ofproto_parser.NXActionLearn(table_id=get_state_table_id(table_id),priority=100,
specs=specs)
filtered_action_set.append(learn_action)
elif act_type == bebaproto.OFPAT_EXP_SET_GLOBAL_STATE:
''' TODO we could add an action learn() that install a flow entry in table 0 which sets reg8=global state value, with mask '''
else:
# non-Beba actions are left unchanged