-
Notifications
You must be signed in to change notification settings - Fork 23
/
tdicli.py
2332 lines (2041 loc) · 92.3 KB
/
tdicli.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
#
# Copyright(c) 2021 Intel Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import print_function
from traitlets.config import Config
from prompt_toolkit.input.defaults import create_input
from prompt_toolkit.output.defaults import create_output
from prompt_toolkit.application.current import get_app_session
from ctypes import *
import sys
import os
import builtins
import keyword
import IPython
import types
import tabulate
import pdb
import re
import atexit
import json
import operator
import copy
from tdiTable import TdiTable
from tdiTable import TdiTableError
from tdiInfo import TdiInfo
from tdiTableEntry import TableEntry
from tdiDefs import *
from ipaddress import ip_address as ip
from netaddr import EUI as mac
import logging
# below are loaded and unloaded in sys modules main everytime
# python cli is logged in and out
_tdi_context = {}
tdi = None
# below are loaded in sys modules main once at the
# first python cli login and maintained throughout
ipython_app = None
tdi_session_dict = {}
# regular global variables
sess_type = POINTER(c_uint)
class CIntfTdi:
target_type_cls = TargetType
def __init__(self, dev_id, table_cls, info_cls, driver_path):
self._dev_id = dev_id
self._driver = CDLL(driver_path)
self.TdiTable = table_cls
self.TdiInfo = info_cls
sts = self._init_programs()
if sts == -1:
return sts
self._init_wrapper()
def _init_wrapper(self):
#self.gflags = self._driver.tdi_generic_flag_support()
def tdi_table_entry_get(tbl_hdl, session, dev_tgt, key, data, flag):
return self._driver.tdi_table_entry_get(tbl_hdl, session, dev_tgt, flag, key, data)
setattr(self, 'tdi_table_entry_get', tdi_table_entry_get)
def tdi_table_entry_get_by_handle(tbl_hdl, session, dev_tgt, ent_hdl, key, data, flag):
return self._driver.tdi_table_entry_get_by_handle(tbl_hdl, session, dev_tgt, flag, ent_hdl, key, data)
setattr(self, 'tdi_table_entry_get_by_handle', tdi_table_entry_get_by_handle)
def tdi_table_entry_handle_get(tbl_hdl, session, dev_tgt, key, handle):
flags = self.get_flags()
return self._driver.tdi_table_entry_handle_get(tbl_hdl, session, dev_tgt, flags, key, handle)
setattr(self, 'tdi_table_entry_handle_get', tdi_table_entry_handle_get)
def tdi_table_entry_key_get(tbl_hdl, session, dev_tgt, handle, e_tgt, key):
flags = self.get_flags()
return self._driver.tdi_table_entry_key_get(tbl_hdl, session, dev_tgt, flags, handle, e_tgt, key)
setattr(self, 'tdi_table_entry_key_get', tdi_table_entry_key_get)
def tdi_table_entry_get_first(tbl_hdl, session, dev_tgt, key, data, flag):
return self._driver.tdi_table_entry_get_first(tbl_hdl, session, dev_tgt, flag, key, data)
setattr(self, 'tdi_table_entry_get_first', tdi_table_entry_get_first)
def tdi_table_entry_get_next_n(tbl_hdl, session, dev_tgt, key, keys, data, n, num_ret, flag):
return self._driver.tdi_table_entry_get_next_n(tbl_hdl, session, dev_tgt, flag, key, keys, data, n, num_ret)
setattr(self, 'tdi_table_entry_get_next_n', tdi_table_entry_get_next_n)
def tdi_table_default_entry_get(tbl_hdl, session, dev_tgt, data, flag):
return self._driver.tdi_table_default_entry_get(tbl_hdl, session, dev_tgt, flag, data)
setattr(self, 'tdi_table_default_entry_get', tdi_table_default_entry_get)
def tdi_table_default_entry_set(tbl_hdl, session, dev_tgt, data):
flags = self.get_flags()
return self._driver.tdi_table_default_entry_set(tbl_hdl, session, dev_tgt, flags, data)
setattr(self, 'tdi_table_default_entry_set', tdi_table_default_entry_set)
def tdi_table_default_entry_reset(tbl_hdl, session, dev_tgt):
flags = self.get_flags()
return self._driver.tdi_table_default_entry_reset(tbl_hdl, session, dev_tgt, flags)
setattr(self, 'tdi_table_default_entry_reset', tdi_table_default_entry_reset)
def tdi_table_usage_get(tbl_hdl, session, dev_tgt, count, flag):
return self._driver.tdi_table_usage_get(tbl_hdl, session, dev_tgt, flag, count)
setattr(self, 'tdi_table_usage_get', tdi_table_usage_get)
def tdi_table_size_get(tbl_hdl, session, dev_tgt, count):
flags = self.get_flags()
return self._driver.tdi_table_size_get(tbl_hdl, session, dev_tgt, flags, count)
setattr(self, 'tdi_table_size_get', tdi_table_size_get)
def tdi_table_attributes_set(tbl_hdl, session, dev_tgt, attr):
flags = self.get_flags()
return self._driver.tdi_table_attributes_set(tbl_hdl, session, dev_tgt, flags, attr)
setattr(self, 'tdi_table_attributes_set', tdi_table_attributes_set)
def tdi_table_attributes_get(tbl_hdl, session, dev_tgt, attr):
flags = self.get_flags()
return self._driver.tdi_table_attributes_get(tbl_hdl, session, dev_tgt, flags, attr)
setattr(self, 'tdi_table_attributes_get', tdi_table_attributes_get)
def tdi_table_clear(tbl_hdl, session, dev_tgt):
flags = self.get_flags()
return self._driver.tdi_table_clear(tbl_hdl, session, dev_tgt, flags)
setattr(self, 'tdi_table_clear', tdi_table_clear)
def tdi_table_entry_del(tbl_hdl, session, dev_tgt, key):
flags = self.get_flags()
return self._driver.tdi_table_entry_del(tbl_hdl, session, dev_tgt, flags, key)
setattr(self, 'tdi_table_entry_del', tdi_table_entry_del)
def tdi_table_entry_add(tbl_hdl, session, dev_tgt, flags, key, data):
return self._driver.tdi_table_entry_add(tbl_hdl, session, dev_tgt, flags, key, data)
setattr(self, 'tdi_table_entry_add', tdi_table_entry_add)
def tdi_table_entry_mod(tbl_hdl, session, dev_tgt, flags, key, data):
return self._driver.tdi_table_entry_mod(tbl_hdl, session, dev_tgt, flags, key, data)
setattr(self, 'tdi_table_entry_mod', tdi_table_entry_mod)
def tdi_table_entry_mod_inc(tbl_hdl, session, dev_tgt, key, data, flag):
# Translate flag to generic flags, MOD_INC_DEL is 2nd bit.
flags = c_uint64(0)
if flag == True:
flags = c_uint64(1 << 1)
return self._driver.tdi_table_entry_mod_inc(tbl_hdl, session, dev_tgt, flags, key, data)
setattr(self, 'tdi_table_entry_mod_inc', tdi_table_entry_mod_inc)
def _init_programs(self):
# tdi session need _device hdl
self.device_type = POINTER(c_uint)
self._device = self.device_type()
sts = self._driver.tdi_device_get(self._dev_id, byref(self._device))
# testing for num devices
num_devices = c_int(-1)
sts = self._driver.tdi_num_device_id_list_get(byref(num_devices))
array_type = c_uint32 * num_devices.value
devices = array_type()
sts = self._driver.tdi_device_id_list_get(byref(devices))
for dev in devices:
logging.debug("device_id_list="+str(dev))
num_names = c_int(-1)
self._driver.tdi_num_p4_names_get(self._dev_id, byref(num_names))
print("We've found {} p4 programs for device {}:".format(num_names.value, self._dev_id))
array_type = c_char_p * num_names.value
p4_names = array_type()
# why don't need to annotation for self._dev_id to c_int(self._dev_id)
self._driver.tdi_p4_names_get(self._dev_id, p4_names)
self.handle_type = POINTER(self.TdiHandle)
self.handle_key_type = POINTER(self.TdiHandle)
self.handle_target_type = POINTER(self.TdiHandle)
self.annotation_type = self.TdiAnnotation
self.flags_type = POINTER(c_uint)
flag=0
self._flags = self.flags_type()
self._driver.tdi_flags_create(flag, byref(self._flags))
self.tdi_idle_timeout_cb_type = CFUNCTYPE(c_int, POINTER(self.TdiDevTgt), self.handle_type, c_void_p)
self.tdi_tbl_operations_cb_type = CFUNCTYPE(None, POINTER(self.TdiDevTgt), c_void_p)
self.learn_cb_type = CFUNCTYPE(c_int, POINTER(self.TdiDevTgt), sess_type, POINTER(self.handle_type), c_uint, self.handle_type, c_void_p)
self.port_status_notif_cb_type = CFUNCTYPE(c_int, self.handle_target_type, self.handle_key_type, c_bool, c_void_p)
self.selector_table_update_cb_type = CFUNCTYPE(None, sess_type, POINTER(self.TdiDevTgt), c_void_p, c_uint, c_uint, c_int, c_bool)
self.infos = {}
for name in p4_names:
print(name.decode('ascii'))
info = self.TdiInfo(self, name)
if info == -1:
return -1
self.infos[name] = info
self._flags = self.flags_type()
self.target_type = POINTER(c_uint)
self._target = self.target_type()
sts = self._driver.tdi_target_create(self.get_device(), byref(self._target))
if not sts == 0:
print("Error, unable to create TDI Runtime session")
return -1
def _devcall(self):
pdb.set_trace()
def _complete_operations(self):
sts = self._driver.tdi_session_complete_operations(tdi_session_dict[self._dev_id])
if sts != 0:
raise Exception("Error: complete_operations failed")
def _begin_batch(self):
sts = self._driver.tdi_begin_batch(tdi_session_dict[self._dev_id])
if sts != 0:
raise Exception("Error: begin_batch failed")
def _end_batch(self):
sts = self._driver.tdi_end_batch(tdi_session_dict[self._dev_id])
if sts != 0:
raise Exception("Error: end_batch failed")
def _flush_batch(self, synchronous=True):
sts = self._driver.tdi_flush_batch(tdi_session_dict[self._dev_id], c_bool(synchronous))
if sts != 0:
raise Exception("Error: flush_batch failed")
def _begin_transaction(self, atomic=True):
sts = self._driver.tdi_begin_transaction(tdi_session_dict[self._dev_id], c_bool(atomic))
if sts != 0:
raise Exception("Error: begin_transaction failed")
def _verify_transaction(self):
sts = self._driver.tdi_verify_transaction(tdi_session_dict[self._dev_id])
if sts != 0:
raise Exception("Error: verify_transaction failed")
def _commit_transaction(self, synchronous=True):
sts = self._driver.tdi_commit_transaction(tdi_session_dict[self._dev_id], c_bool(synchronous))
if sts != 0:
raise Exception("Error: commit_transaction failed")
def _abort_transaction(self):
sts = self._driver.tdi_abort_transaction(tdi_session_dict[self._dev_id])
if sts != 0:
raise Exception("Error: abort_transaction failed")
def err_str(self, sts):
estr = c_char_p()
self._driver.bf_rt_err_str(c_int(sts), byref(estr))
return estr.value.decode('ascii')
class TdiHandle(Structure):
_fields_ = [("unused", c_int)]
class TdiDevTgt(Structure):
_fields_ = [("dev_id", c_int)]
def __str__(self):
ret_val = ""
for name, type_ in self._fields_:
ret_val += name + ": " + str(getattr(self, name)) + "\n"
return ret_val
class TdiTargetHandle(Structure):
_fields_ = [("unused", c_int)]
class TdiFlagsHandle(Structure):
_fields_ = [("unused", c_int)]
class TdiAnnotation(Structure):
_fields_ = [("name", c_char_p), ("value", c_char_p)]
def get_driver(self):
return self._driver
def get_dev_id(self):
return self._dev_id
def get_session(self):
return tdi_session_dict[self._dev_id]
def get_device(self):
return self._device
def get_dev_tgt(self):
return self._target
def get_flags(self):
return byref(self._flags)
class TableEntryDumper:
def __init__(self, table, data_fields_imp_level_thresh=1):
self.table = table
self.entries = {}
self.key_headers = []
self.data_headers = {}
self.data_fields_imp_level_thresh = data_fields_imp_level_thresh
def prune_unwanted_data_fields(self, data_fields, data_content):
data_fields_to_prune = []
for name, info in data_fields.items():
# By default, we assume the imp_level of the field to be 1
imp_level = 1
for item in info.annotations:
if item[0] == "$bfrt_field_imp_level":
imp_level = int(item[1])
break
if imp_level < self.data_fields_imp_level_thresh:
data_fields_to_prune.append(name)
for item in data_fields_to_prune:
del data_fields[item]
del data_content[item]
def __call__(self, key_hdls, data_hdls, action_ids, print_zero=True):
if not len(self.key_headers) == len(self.table.key_fields.keys()):
for field in sorted(self.table.key_fields.values(), key=lambda x: x.id):
self.key_headers.append(field.name.decode('ascii'))
for i in range(0, len(key_hdls)):
key = key_hdls[i]
data = data_hdls[i]
action = None
if len(self.table.actions) > 0:
action = self.table.action_id_name_map[action_ids[i]]
key_content = self.table._get_key_fields(key)
if not isinstance(key_content, dict):
return
data_content = self.table._get_data_fields(data, action)
if not isinstance(data_content, dict):
return
data_fields = copy.copy(self.table.data_fields)
act_str = ""
if action is not None:
data_fields = copy.copy(self.table.actions[action]["data_fields"])
act_str = action.decode('ascii')
# only display the fields whose importance level is above the set
# threshold
self.prune_unwanted_data_fields(data_fields, data_content)
if act_str not in self.entries.keys():
self.entries[act_str] = []
data_headers = []
for field in sorted(data_fields.values(), key=lambda x: x.id):
data_headers.append(field.name.decode('ascii'))
self.data_headers[act_str] = data_headers
ent = {'key_content' : key_content, 'data_content' : data_content, 'data_fields' : data_fields}
self.entries[act_str].append(ent)
def print_table(self, regex_strs=None, print_zero=True):
for action, entries in self.entries.items():
str_entries = []
for e in entries:
ent = []
regex_accept = True
for name in self.key_headers:
cname = name.encode('ascii')
str_rep = self.table.key_fields[cname].stringify_output(e['key_content'][cname])
if regex_strs is not None:
if not self._check_regex(str_rep, regex_strs[cname]):
regex_accept = False
ent.append(str_rep)
if not regex_accept:
continue
all_zero = True
for name in self.data_headers[action]:
cname = name.encode('ascii')
if cname in e['data_content']:
if isinstance(e['data_content'][cname], list):
for elem in e['data_content'][cname]:
if elem != 0:
all_zero = False
break
elif e['data_content'][cname] != 0:
all_zero = False
#
ent.append(e['data_fields'][cname].stringify_output(e['data_content'][cname]))
else:
ent.append("N/A")
if print_zero or not all_zero:
str_entries.append(ent)
if not action == "":
print("{} entries for action: {}".format(self.table.name, action))
print(tabulate.tabulate(str_entries, headers=(self.key_headers + self.data_headers[action])))
print('\n')
def dump_entry_objs(self, regex_strs=None):
objs = []
for action, entries in self.entries.items():
for e in entries:
regex_accept = True
for name in self.key_headers:
cname = name.encode('ascii')
str_rep = self.table.key_fields[cname].stringify_output(e['key_content'][cname])
if regex_strs is not None:
if not self._check_regex(str_rep, regex_strs[cname]):
regex_accept = False
if not regex_accept:
continue
if action == '':
action = None
objs.append(TableEntry(self.table, e['key_content'], e['data_content'], action))
return objs
def dump_json(self):
objs = self.dump_entry_objs()
raws = [x.raw() for x in objs]
return json.dumps(raws)
def _check_regex(self, str_rep, pattern):
if pattern is None:
return True
if isinstance(pattern, list):
for idx, val in enumerate(pattern):
if val is None:
continue
try:
res = re.search(str(val), str_rep[idx])
except Exception as e:
print("regex error: {}".format(str(e)))
continue
if res is None:
return False
return True
pattern = str(pattern)
try:
res = re.search(pattern, str_rep)
except Exception as e:
print("Error: {}".format(str(e)))
return True
if res is not None:
return True
return False
class TDIContext:
"""
This superclass provides node and leaf subclasses with callability.
When called, the aforementioned objects' available commands are
loaded into python's global namespace. When another object is
called, the old commands are unloaded and replaced.
"""
# TDIContext obj() will call obj.__call__()
def __call__(self):
global _tdi_context
for name in _tdi_context['cur_context']:
delattr(sys.modules['__main__'],name)
_tdi_context['cur_context'] = []
for name, child in self._get_children().items():
_tdi_context['cur_context'].append(name)
setattr(sys.modules['__main__'], name, child)
print(self.__doc__)
_tdi_context['parent'] = self._parent_node
_tdi_context['cur_node'] = self
tmp = self
name = []
while tmp != None:
name.append(tmp._name)
tmp = tmp._parent_node
name.reverse()
set_prompt(".".join(name))
def _get_name(self):
return self._name
def _set_name(self, name):
self._name = name.replace('$', '')
class TesterInt:
def __init__(self, val, iterlen=8):
self.intval = val
self.iterlen = iterlen
def __int__(self):
return self.intval
def __iter__(self):
self.curiter = 0
return self
def __next__(self):
if self.curiter == self.iterlen:
raise StopIteration
self.curiter += 1
return self.intval
def __getitem__(self, idx):
if not isinstance(idx, int):
raise TypeError
if not idx < self.iterlen:
raise IndexError
return self.intval
def __len__(self):
return self.iterlen
class TDINode(TDIContext):
"""
This class represents non-leaf nodes in the TDI Runtime CLI's command tree.
Its sole purpose is to organize available commands.
"""
def __init__(self, name, cintf, parent_node=None):
self._set_name(name)
self._cintf = cintf
if parent_node is not None and isinstance(parent_node, TDINode):
self._parent_node = parent_node
self._parent_node._add_child(self)
else:
self._parent_node = None
self._children = []
self._commands = {}
self._commands["dump"] = getattr(self, "dump")
self._commands["info"] = getattr(self, "info")
def dump(self, table=False, from_hw=False, return_ents=False, print_zero=True):
for child in self._children:
if isinstance(child, TDINode):
child.dump(table=table, from_hw=from_hw, return_ents=return_ents, print_zero=print_zero)
elif (isinstance(child, TDILeaf) and "dump" in child._c_tbl.supported_commands):
child.dump(table=table, json=False, from_hw=from_hw, return_ents=return_ents, print_zero=print_zero)
def clear(self, batch=True):
for child in self._children:
if ((isinstance(child, TDILeaf) and "clear" in child._c_tbl.supported_commands) or (isinstance(child, TDINode))):
child.clear(batch)
def tdi_info(self, return_info=True, print_info=True):
print("This a test tdi")
info = self._get_full_leaf_info()
table_rows = []
res = []
for i in info:
table_rows.append(i[:-1])
if return_info:
res.append({"full_name": i[0],
"type": i[1],
"usage": i[2],
"capacity": i[3],
"node": i[4]})
if print_info:
print("Tables under this node:")
print(tabulate.tabulate(table_rows, headers=["Full Table Name", "Type", "Usage", "Capacity"]))
if return_info:
return res
def info(self, return_info=False, print_info=True):
info = self._get_full_leaf_info()
table_rows = []
res = []
for i in info:
table_rows.append(i[:-1])
if return_info:
res.append({"full_name": i[0],
"type": i[1],
"usage": i[2],
"capacity": i[3],
"node": i[4]})
if print_info:
print("Tables under this node:")
print(tabulate.tabulate(table_rows, headers=["Full Table Name", "Type", "Usage", "Capacity"]))
if return_info:
return res
def _get_full_leaf_info(self):
info = []
for k, v in self._get_children().items():
if isinstance(v, TDILeaf) or isinstance(v, TDINode):
info += v._get_full_leaf_info()
return info
def _add_child(self, child):
self._children.append(child)
exec("self.{} = child".format(child._get_name()))
def _get_children(self):
children = {}
for child in self._children:
children[child._get_name()] = child
for name, command in self._commands.items():
children[name] = command
return children
def _set_doc(self):
docstr = "Available symbols:\n"
child_names = []
for child in self._children:
type_ = "Node"
if isinstance(child, TDILeaf):
type_ = "Table"
if isinstance(child, TDILrnLeaf):
type_ = "Learn-digest"
child_names.append((child._get_name(), type_))
for name, command in self._commands.items():
child_names.append((name, "Command"))
for name, description in sorted(child_names):
docstr += "{:<20} - {}\n".format(name, description)
self.__doc__ = docstr
def _simple_tester(self):
for child in self._children:
child._simple_tester()
def _make_dep_tester_funcs(self):
tested = []
def test_table(leaf):
sts = 0
if leaf in tested:
return sts
if not leaf.has_keys:
return sts
if leaf._c_tbl.table_type_cls.table_type_str(leaf._c_tbl.get_type()) in leaf._c_tbl.no_usage_tables():
return sts
if leaf._c_tbl.get_id() in leaf._c_tbl._tdi_info.tbl_dep_map:
for dep_id in leaf._c_tbl._tdi_info.tbl_dep_map[leaf._c_tbl.get_id()]:
dep_leaf = leaf._c_tbl._tdi_info.tbl_id_map[dep_id].frontend
if dep_leaf is None:
print("Error: dep_test initialization did not finish!")
return -1
sts = test_table(dep_leaf)
if not sts == 0:
return sts
print("Testing table: {}".format(leaf._name))
sts = leaf._test_all_adds()
tested.append(leaf)
return sts
def cleanup():
tested.reverse()
for leaf in tested:
for ent in leaf.get(regex=True, print_ents=False):
ent.remove()
return test_table, cleanup
def _dep_tester(self, test_func=None):
sts = 0
root = False
cleanup = None
if test_func is None:
test_func, cleanup = self._make_dep_tester_funcs()
root = True
for child in self._children:
sts |= child._dep_tester(test_func)
if cleanup is not None:
cleanup()
if root:
if sts == 0:
print("dep_test_success")
else:
print("dep_test_failed")
return sts
# default callbacks
def _default_operation_callback(dev_id, pipe_id, direction, parser_id):
print("operation complete - dev_id: {}, pipe_id: {}, direction: {}, parser_id: {}".format(dev_id, pipe_id, direction, parser_id))
def _learn_fields_print(dev_id, pipe_id, direction, parser_id, session, data):
print("Device id: {}\n"
"Pipe id: {}\n"
"Direction: {}\n"
"Parser id: {}\n".format(dev_id, pipe_id, direction, parser_id))
print("Learn data:\n{}".format(data))
return 0
class TDILeaf(TDIContext):
"""
This class creates easy to type, autocompleted python entrypoints to the
TDI Runtime API. Each instance of the class represents one table. It exposes
Add, modify commands for each action type (or one of each for the table if
said table has no actions). It also exposes get and dump commands for
retrieving information from TDI Runtime.
"""
def __init__(self, name, c_tbl, cintf, parent_node=None, children=None):
self._set_name(name)
self._c_tbl = c_tbl
self._cintf = cintf
c_tbl.set_frontend(self)
self._children = {}
#
# Link the TDI Command Object Tree
#
if parent_node is not None and isinstance(parent_node, TDINode):
self._parent_node = parent_node
self._parent_node._add_child(self)
else:
self._parent_node = None
#
# If some children were provided add them
#
if children is not None:
for c in children:
self._add_child(c)
#
# Setup Methods and Attributes for Leaf Command Node
#
self._adds = {}
self._mods = {}
self._mods_inc = {}
self._dels = []
self._gets = []
self._entries = {}
self._init_table_methods()
self._init_string_choices()
for cmd in self._c_tbl.supported_commands:
try:
self._children[cmd] = getattr(self,cmd)
except:
logging.debug("CLI log: Command {} is not ready or available".format(cmd))
pass
self._set_docstring()
# if self._c_tbl.table_type_cls.table_type_str(self._c_tbl.get_type()) in self._c_tbl.unimplemented_tables:
# print("CLI Err: Unimplemented Command Object {}".format(self._name))
# return
# else:
# print("CLI Log: Implemented Command Object {}".format(self._name))
# for cmd in self._children:
# print("CLI log: Command {}".format(cmd))
def _add_child(self, child):
self._children[child._name] = child
child._parent_node = self
exec("self.{} = child".format(child._get_name()))
def info(self, return_info=False, print_info=True):
res = {
"table_name": self._name,
"full_name": self._c_tbl.name,
"type": self._c_tbl.table_type_cls.table_type_str(self._c_tbl.get_type()),
"usage": self._c_tbl.get_usage(),
"capacity": self._c_tbl.get_capacity(),
"key_fields": [],
"data_fields": [],
}
if print_info:
print("Table Name: {}".format(res["table_name"]))
print("Full Name: {}".format(res["full_name"]))
print("Type: {}".format(res["type"]))
print("Usage: {}".format(res["usage"]))
print("Capacity: {}\n".format(res["capacity"]))
print("Key Fields:")
key_rows = []
headers = ["Name", "Type", "Size", "Required", "Read Only"]
for info in sorted(self._c_tbl.key_fields.values(), key=lambda x: x.id):
field = [info.name.decode('ascii'), self._c_tbl.key_match_type_cls.key_match_type_str(info.type), info.size, info.required, info.read_only]
key_rows += [field]
res["key_fields"] += [{"name": field[0],
"type": field[1],
"size": field[2],
"required": field[3],
"read_only": field[4]}]
if print_info:
print(tabulate.tabulate(key_rows, headers=headers))
if len(self._c_tbl.actions) == 0:
data_rows = []
for info in sorted(self._c_tbl.data_fields.values(), key=lambda x: x.id):
field = [info.name.decode('ascii'), self._c_tbl.data_type_cls.data_type_str(info.data_type), info.size, info.required, info.read_only]
data_rows += [field]
res["data_fields"] += [{"name": field[0],
"type": field[1],
"size": field[2],
"required": field[3],
"read_only": field[4]}]
if print_info:
print("\nData Fields:\n{}\n".format(tabulate.tabulate(data_rows, headers=headers)))
else:
res["data_fields"] = {}
print()
for name, act_info in self._c_tbl.actions.items():
data_rows = []
res["data_fields"][name.decode('ascii')] = []
for info in sorted(act_info['data_fields'].values(), key=lambda x: x.id):
field = [info.name.decode('ascii'), self._c_tbl.data_type_cls.data_type_str(info.data_type), info.size, info.required, info.read_only]
data_rows += [field]
res["data_fields"][name.decode('ascii')] += [{"name": field[0],
"type": field[1],
"size": field[2],
"required": field[3],
"read_only": field[4]}]
if print_info:
print("Data Fields for action {}:\n{}\n".format(name.decode('ascii'), tabulate.tabulate(data_rows, headers=headers)))
if return_info:
return res
def clear(self, batch=True):
self._c_tbl.clear(batch)
def dump(self, table=False, json=False, from_hw=False, return_ents=False, print_zero=True):
"""Dump all entries of table including default entry if applicable
"""
table_type = self._c_tbl.table_type_cls.table_type_str(self._c_tbl.get_type())
print("----- {} Dump Start -----".format(self._name))
if "get_default" in self._c_tbl.supported_commands and (not (return_ents or json)):
print("Default Entry:")
try:
d_ent = self.get_default(print_ent=False)
pstr, _ = self._c_tbl.print_entry(d_ent.key, d_ent.data, d_ent.action.encode('ascii') if d_ent.action else d_ent.action)
print(pstr[11:])
except TdiTableError as e:
print(e)
if not table and not json and not return_ents:
stream_printer = self._c_tbl.make_entry_stream_printer()
try:
self._c_tbl.dump(stream_printer, from_hw, print_zero=print_zero)
except TdiTableError as e:
print(e)
print("----- {} Dump End -----\n".format(self._name))
if json:
print("Table must be true to produce json output")
return None
else:
field_display_default_threshold = 1
# For the time being, we only support printing a subset of the data
# fields when the table is either "PORT_CFG" or "PORT_STAT"
# Thus if the table is neither of those, then always print all the
# fields. Thus we set the level_thresh to 1
if table_type in ["PORT_CFG", "PORT_STAT"] and table is True:
field_display_default_threshold = 2
printer = TableEntryDumper(self._c_tbl, field_display_default_threshold)
ret = self._c_tbl.dump(printer, from_hw)
if ret == 0:
if json:
return printer.dump_json()
elif return_ents:
return printer.dump_entry_objs()
else:
printer.print_table(print_zero=print_zero)
print("----- {} Dump End -----".format(self._name))
else:
return None
def add_from_json(self, entry_blob):
if isinstance(entry_blob, str):
jents = json.loads(entry_blob)
try:
for ent in jents:
if not ent['table_name'] == self._c_tbl.name:
print("Error: table mismatch for entry {}.".format(ent))
skey = ent['key']
sdata = ent['data']
saction = ent['action']
key = {}
data = {}
action = None
if saction is not None:
action = saction.encode('ascii')
for k, v in skey.items():
key[k.encode('ascii')] = v
for k, v in sdata.items():
data[k.encode('ascii')] = v
# In dump output, the Register datafield is in the form of list of 4 elements, one per pipe.
# But the Register datafield is BYTE_STREAM
# so picking the first element of the list as input for Register datafield.
if type(v) is list:
try:
if action is None:
data_field = self._c_tbl.data_fields[k.encode('ascii')]
else:
data_field = self._c_tbl.actions[action]["data_fields"][k.encode('ascii')]
data_type = self._c_tbl.data_type_cls.data_type_str(data_field.data_type)
if data_type in ["UINT64", "BYTE_STREAM", "BOOL"] and ('$bfrt_field_class', 'register_data') in data_field.annotations:
data[k.encode('ascii')] = v[0]
except:
pass
parsed_keys, parsed_data = self._c_tbl.parse_str_input("add_from_json", key, data, action)
if parsed_keys == -1:
return
if parsed_data == -1:
return
self._c_tbl.add_entry(parsed_keys, parsed_data, action)
except Exception as e:
print("Error: {}".format(str(e)))
else:
print("Input must be string produced by dump command for this table.")
def _create_attributes(self, key_fields={}, data_fields={}):
return
def _create_operations(self):
method_name = "operation_register_sync"
if method_name in self._c_tbl.supported_commands:
def operation_register_sync(self, callback=None):
if callback is None:
callback = _default_operation_callback
self._c_tbl.operation_register_sync(callback)
bound_method = operation_register_sync.__get__(self, self.__class__)
self.operation_register_sync = bound_method
self._children[method_name] = getattr(self, method_name)
method_name = "operation_counter_sync"
if method_name in self._c_tbl.supported_commands:
def operation_counter_sync(self, callback=None):
if callback is None:
callback = _default_operation_callback
self._c_tbl.operation_counter_sync(callback)
bound_method = operation_counter_sync.__get__(self, self.__class__)
self.operation_counter_sync = bound_method
self._children[method_name] = getattr(self, method_name)
method_name = "operation_hit_state_update"
if method_name in self._c_tbl.supported_commands:
def operation_hit_state_update(self, callback=None):
if callback is None:
callback = _default_operation_callback
self._c_tbl.operation_hit_state_update(callback)
bound_method = operation_hit_state_update.__get__(self, self.__class__)
self.operation_hit_state_update = bound_method
self._children[method_name] = getattr(self, method_name)
def _get_children(self):
return self._children
def _get_full_leaf_info(self):
return [[self._c_tbl.name,
self._c_tbl.table_type_cls.table_type_str(self._c_tbl.get_type()),
self._c_tbl.get_usage(),
self._c_tbl.get_capacity(),
self]]
def _test_all_adds(self):
for i, (ent_gen, params) in enumerate(self._entries.values()):
if i > 1:
return 0
kwargs = {}
for p in params:
kwargs[p] = TesterInt(i)
ent = ent_gen(**kwargs)
if ent is None:
return -1
ent.push()
return 0
def _simple_tester(self):
print("Testing adds for table {}".format(self._name))
for add, params in self._adds.values():
for i in range(1, 9):
kwargs = {}
for p in params:
kwargs[p] = TesterInt(i)
add(**kwargs)
for i in range(1, 9):
for d_func, d_params in self._dels:
kwargs = {}
for p in d_params:
kwargs[p] = TesterInt(i)
d_func(**kwargs)
print("Testing mods for table {}".format(self._name))
add, a_params = list(self._adds.values())[0]
kwargs = {}
for p in a_params:
kwargs[p] = TesterInt(1)
add(**kwargs)
for mod, params in self._mods.values():
kwargs = {}
for p in params:
kwargs[p] = TesterInt(1)
mod(**kwargs)
for d_func, d_params in self._dels:
kwargs = {}
for p in d_params:
kwargs[p] = TesterInt(1)
d_func(**kwargs)
print("Test for table {} completed\n".format(self._name))
def _dep_tester(self, test_func):
sts = test_func(self)
if not sts == 0:
print("Error: dep test for table {} failed!".format(self._name))
return sts
"""
This function dynamically creates a docstring for our leaf exposing
user-relevant information about key fields, actions, data fields for the
corresponding table.
"""
def _set_docstring(self):
full_table_name = self._c_tbl.name
key_docstring = ""
actdata_docstring = ""