-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtif_updater.py
1680 lines (1525 loc) · 73.9 KB
/
tif_updater.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 ast
from concurrent import futures
import ipaddress
import json
from multiprocessing import Process
import os
from pathlib import Path
import re
import subprocess
import tempfile
from typing import Union
import grpc
from google.protobuf.json_format import MessageToDict, ParseDict
import jinja2
from orchestrator_utils.til import orchestrator_msg_pb2_grpc, orchestrator_msg_pb2
from orchestrator_utils.til.orchestrator_msg_pb2 import TIFControlRequest, TIFControlResponse
from orchestrator_utils.til.tif_control_pb2 import DpPort, Lag, RoutingTableConfiguration
from orchestrator_utils.bfrt_proto import bfruntime_pb2, bfruntime_pb2_grpc
from orchestrator_utils.logger.logger import init_logger
from orchestrator_utils.tools.accelerator_type import find_python_acceleratorTypeEnum
from orchestrator_utils.third_party.licensed.sde_versions import SDEVersion
from orchestrator_utils.p4.v1 import p4runtime_pb2, p4runtime_pb2_grpc
from orchestrator_utils.p4.tmp import p4config_pb2
from orchestrator_utils.p4.bmv2 import helper as p4info_help
from conf.grpc_settings import TIF_ADDRESS, maxMsgLength
from conf.in_updater_settings import ACCELERATOR_CONFIGURATION, AcceleratorTemplates
from conf.initializaton_files.port_conf import DEFAULT_PORTS
class TIFUpdateException(Exception):
"""Exception raised for errors during TIF update.
Attributes:
message -- explanation of the error
"""
pass
class TIFControlException(Exception):
"""
Exception raised for TIF control errors.
Attributes:
message -- explanation of the error
"""
pass
def is_valid_mac(address):
"""
Check if the provided string is a valid MAC address.
"""
# Regular expression to match the MAC address
mac_pattern = re.compile(r'^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$')
return bool(mac_pattern.match(address))
def is_valid_ipv4(address):
try:
ipaddress.IPv4Address(address)
return True
except ValueError:
return False
class TIFUpdater(Process, orchestrator_msg_pb2_grpc.TIFUpdateCommunicatorServicer, orchestrator_msg_pb2_grpc.TIFControlCommunicatorServicer):
"""
The Tenant INC Framework Updater process. This handles the accelerator code and configuration update as well as the management of the accelerator.
"""
tofino_grpc_address = "localhost:50052"
bmv2_grpc_address = "localhost:9000" # If using BMv2, the GRPC port must be set to this or change properly!
applied_forwarding_pipeline_configs = {}
applied_table_entries = {}
scheduled_table_entries = {}
management_tenant_id = 0
def __init__(self, device_name, group=None, target=None, name=None, args=(), kwargs={}, daemon=None, bfrt_template_path = "conf/initializaton_files/templates/") -> None:
super().__init__(group, target, name, args, kwargs, daemon=daemon)
self.grpc_server = grpc.server(futures.ThreadPoolExecutor(10), options=[('grpc.max_send_message_length', maxMsgLength), ('grpc.max_receive_message_length', maxMsgLength)])
orchestrator_msg_pb2_grpc.add_TIFUpdateCommunicatorServicer_to_server(self, self.grpc_server)
orchestrator_msg_pb2_grpc.add_TIFControlCommunicatorServicer_to_server(self, self.grpc_server)
self.grpc_server.add_insecure_port(TIF_ADDRESS)
self.logger = init_logger(self.__class__.__name__)
for accelerator, configuration in ACCELERATOR_CONFIGURATION.items():
if configuration["enabled"] :
self.applied_forwarding_pipeline_configs[accelerator] = None
self.bfrt_templates_location = bfrt_template_path
self.switch_config_path = "conf/switch-configuration.json"
if os.path.exists(self.switch_config_path):
self.load_switch_configuration()
else:
self.switch_configuration = {
"lag_ecmp_groups" : {},
"nexthop_map": {},
"ipv4_host_entries": {},
"arp_table_host_entries": {},
"tenant_rules": {},
}
if device_name is not None and self.switch_configuration["initialized_ports"] is None:
self.switch_configuration["initialized_ports"] = DEFAULT_PORTS[device_name]
@staticmethod
def _build_tenant_cnf_id(tenant_id, tenant_func_name):
"""
Build a tenant configuration ID.
Parameters:
-----------
tenant_id : int
The tenant ID.
tenant_func_name : str
The tenant function name.
Returns:
--------
str: The tenant configuration ID.
"""
return str(tenant_id) + "_" + tenant_func_name
def run(self) -> None:
super().run()
self.running = True
self.grpc_server.start()
self.logger.info("TIFUpdater started")
def terminate(self) -> None:
self.running = False
self.grpc_server.stop(10)
self.logger.info("Got Terminate. Stopping GRPC server.")
def save_switch_configuration(self):
"""
Save the switch configuration to a file.
"""
with open(self.switch_config_path, "w") as f:
json.dump(self.switch_configuration, f, indent=2)
def load_switch_configuration(self):
"""
Load the switch configuration from a file.
"""
with open(self.switch_config_path, "r") as f:
self.switch_configuration = json.load(f)
def pull_config(self, acceleratorType : orchestrator_msg_pb2.AcceleratorType, address = None):
"""
Pull Forwarding Pipeline Config from the given accelerator.
Parameters:
-----------
acceleratorType : AcceleratorType
accelerator type from where the config should be pulled
address : str, optional
GRPC address from where configuration should be pulled.
Raises:
-------
TIFUpdateException:
If no valid accelerator type is specified.
"""
if acceleratorType == orchestrator_msg_pb2.ACCELERATOR_TYPE_TNA:
fwd_pipeline_conf = self.pull_ForwardingPipelineConfig_from_tofino(address)
self.applied_forwarding_pipeline_configs[find_python_acceleratorTypeEnum(acceleratorType).value] = fwd_pipeline_conf
elif acceleratorType == orchestrator_msg_pb2.ACCELERATOR_TYPE_BMV2:
fwd_pipeline_conf = self.pull_ForwardingPipelineConfig_from_bmv2(address)
self.applied_forwarding_pipeline_configs[find_python_acceleratorTypeEnum(acceleratorType).value] = fwd_pipeline_conf
else:
raise TIFUpdateException("No valid accelerator type specified!")
def GetTIFCode(self, request, context):
"""
GPRC GetTIFCode implementation for TIFUpdateCommunicator which is used for returning applied TIF for a specified accelerator hardware.
"""
if request.acceleratorType == orchestrator_msg_pb2.ACCELERATOR_TYPE_TNA:
try:
fwd_pipeline_confs = self.pull_ForwardingPipelineConfig_from_tofino()
self.applied_forwarding_pipeline_configs[find_python_acceleratorTypeEnum(request.acceleratorType).value] = fwd_pipeline_confs
# TODO: Multiple Forwarding Pipeline Config are not supported
return orchestrator_msg_pb2.TIFResponse(
status= 200,
message = "TIF pulled successfully",
bfFwdPipelineConfig = self.convert_to_bfruntime_fwd_pipeline_conf_message(fwd_pipeline_confs)
)
except KeyError as err:
return orchestrator_msg_pb2.TIFResponse(
status = 404,
message = "TIF is not available on Chip"
)
except Exception as ex:
return orchestrator_msg_pb2.TIFResponse(
status = 500,
message = "Error while pulling TIF:" + ex.__str__()
)
elif request.acceleratorType == orchestrator_msg_pb2.ACCELERATOR_TYPE_BMV2:
try:
fwd_pipeline_confs = self.pull_ForwardingPipelineConfig_from_bmv2()
self.applied_forwarding_pipeline_configs[find_python_acceleratorTypeEnum(request.acceleratorType).value] = fwd_pipeline_confs
# TODO: Multiple Forwarding Pipeline Config are not supported
return orchestrator_msg_pb2.TIFResponse(
status= 200,
message = "TIF pulled successfully",
bmv2ForwardingPipelineConfig = self.convert_to_bfruntime_fwd_pipeline_conf_message(fwd_pipeline_confs)
)
except KeyError as err:
return orchestrator_msg_pb2.TIFResponse(
status = 404,
message = "TIF is not available on Chip"
)
except Exception as ex:
return orchestrator_msg_pb2.TIFResponse(
status = 500,
message = "Error while pulling TIF:" + ex.__str__()
)
else:
return orchestrator_msg_pb2.TIFResponse(
status = 400,
message = "Accelerator Type was unspecified or invalid! Please provide a valid type!"
)
def UpdateTIFCode(self, request, context):
"""
GPRC UpdateTIFCode implementation for TIFUpdateCommunicator which is used for updating or applying TIF to a accelerator hardware.
"""
try:
acc_type = ""
if request.acceleratorType == orchestrator_msg_pb2.ACCELERATOR_TYPE_TNA:
acc_type = "TNA"
self.send_SetForwardingPipelineConfig_request_to_tofino(request.bfFwdPipelineConfigRequest)
elif request.acceleratorType == orchestrator_msg_pb2.ACCELERATOR_TYPE_BMV2:
acc_type = "BMv2"
self.send_SetForwardingPipelineConfig_request_to_bmv2(request)
else:
return orchestrator_msg_pb2.TIFResponse(
status = 404,
message = "Accelerator type unknown or specified."
)
return orchestrator_msg_pb2.TIFResponse(
status = 200,
message= "TIF to {} applied.".format(acc_type)
)
except Exception as ex:
return orchestrator_msg_pb2.TIFResponse(
status=500,
message= "Error while updating TIF: {}".format(ex.__str__())
)
def InitializeHardware(self, request, context):
"""
GPRC InitializeHardware implementation for TIFUpdateCommunicator which is used for initializing the hardware after TIF was applied or updated.
"""
if request.acceleratorType == orchestrator_msg_pb2.ACCELERATOR_TYPE_TNA:
### Hardware initialization must be done (e.g., using SAL or similar frameworks), since it will reset if the config is changed.
### Due to the software license of the abstraction layer this is omitted.
if SDEVersion.SDE_WITH_SAL == ACCELERATOR_CONFIGURATION["tofino"]["initialization_method"]:
return orchestrator_msg_pb2.TIFResponse(
status=200,
message="Hardware initialized."
)
elif SDEVersion.SDE_WITHOUT_SAL == ACCELERATOR_CONFIGURATION["tofino"]["initialization_method"]:
try:
self._run_port_setup()
self._run_tif_initialization_setup_script()
except Exception as ex:
self.logger.exception(ex)
return TIFControlResponse(
status=500,
message="Error while initialize ports: {}".format(str(ex))
)
self.logger.debug("Initialized ports successful.")
return TIFControlResponse(
status=200,
message="Initialized ports successful."
)
else:
return TIFControlResponse(
status=500,
message="Unsupported Hardware initialization method."
)
elif request.acceleratorType == orchestrator_msg_pb2.ACCELERATOR_TYPE_BMV2:
# No need to initialize hardware if using BMv2
pass
else:
return orchestrator_msg_pb2.TIFControlResponse(
status = 404,
message = "Accelerator type unkmown or unspecified."
)
def GetTableEntries(self, request: TIFControlRequest, context):
"""
Get the table entries from the switch configuration.
Parameters:
-----------
request (TIFControlRequest):
The control request object.
context:
The context object.
Returns:
--------
TIFControlResponse: The control response object containing the table entries.
"""
try:
if request.tenantMetadata.tenantId != self.management_tenant_id:
tenant_cnf_id = self._build_tenant_cnf_id(request.tenantMetadata.tenantId, request.tenantMetadata.tenantFuncName)
if tenant_cnf_id in self.switch_configuration["tenant_rules"].keys():
return TIFControlResponse(
status=200,
message="Got Table Entries successfully",
runtimeRules=[ParseDict(rule, RoutingTableConfiguration()) for rule in self.switch_configuration["tenant_rules"][tenant_cnf_id]]
)
else:
return TIFControlResponse(
status=200,
message="Got Table Entries successfully",
arpHostEntries=[ParseDict({"key": entry["ip"], "nextHopId": entry["nexthop_id"]}, RoutingTableConfiguration()) for entry in self.switch_configuration["arp_table_host_entries"]],
ipv4HostEntries=[ParseDict({"key": entry["ip"], "nextHopId": entry["nexthop_id"]}, RoutingTableConfiguration()) for entry in self.switch_configuration["ipv4_host_entries"]],
nexthopMapEntries=[ParseDict({"key": key, "nextHopId": value}, RoutingTableConfiguration()) for key, value in self.switch_configuration["nexthop_map"].items()],
)
except Exception as ex:
self.logger.exception(ex)
return TIFControlResponse(
status=500,
message="Error while getting table entries: {}".format(str(ex))
)
def AddTableEntries(self, request : TIFControlRequest, context):
"""
Add table entries to the switch configuration.
Parameters:
-----------
request (TIFControlRequest):
The request object containing the table entries.
context:
The context object for the gRPC request.
Returns:
--------
TIFControlResponse: The response object indicating the status of the operation.
"""
def find_ip_in_entries(entry_list, value):
"""
Find the index of an IP address in a list of entries.
Parameters:
-----------
entry_list (list):
The list of entries to search.
value:
The IP address to find.
Returns:
--------
int: The index of the IP address in the list, or -1 if not found.
"""
for i, entry in enumerate(entry_list):
if entry["ip"] == value:
return i
return -1
try:
tables = {}
# The method assumes the checks against access control are done before this point.
if request.runtimeRules:
if self.switch_configuration["tenant_rules"].get(self._build_tenant_cnf_id(request.tenantMetadata.tenantId, request.tenantMetadata.tenantFuncName)) is None:
self.switch_configuration["tenant_rules"][self._build_tenant_cnf_id(request.tenantMetadata.tenantId, request.tenantMetadata.tenantFuncName)] = []
for rule in request.runtimeRules:
rule = MessageToDict(rule)
rule["matches"] = ast.literal_eval(rule["matches"][0])
if isinstance(rule["matches"], str):
rule["matches"] = ast.literal_eval(rule["matches"])
if len(rule["matches"]) != 0:
for key_name, key in rule["matches"].items():
if is_valid_mac(str(key)):
rule["matches"][key_name] = "'{}'".format(key)
elif is_valid_ipv4(str(key)):
rule["matches"][key_name] = "'{}'".format(key)
rule["actionParams"] = ast.literal_eval(rule["actionParams"][0])
if isinstance(rule["actionParams"], str):
rule["actionParams"] = ast.literal_eval(rule["actionParams"])
if len(rule["actionParams"]) != 0:
for key_name, key in rule["actionParams"].items():
if is_valid_mac(str(key)):
rule["actionParams"][key_name] = "'{}'".format(key)
elif is_valid_ipv4(str(key)):
rule["actionParams"][key_name] = "'{}'".format(key)
self.switch_configuration["tenant_rules"][self._build_tenant_cnf_id(request.tenantMetadata.tenantId, request.tenantMetadata.tenantFuncName)].append(rule)
if self.applied_table_entries.get("tenant_rules") is not None:
if rule not in self.applied_table_entries["tenant_rules"]:
tables["tenant_rules"].append(rule)
else:
self.applied_table_entries["tenant_rules"] = []
tables["tenant_rules"] = [rule]
if request.arpHostEntries:
for entry in request.arpHostEntries:
index = find_ip_in_entries(self.switch_configuration["arp_table_host_entries"], entry.key)
if index == -1 :
self.switch_configuration["arp_table_host_entries"].append({"ip": entry.key, "nexthop_id": entry.nextHopId})
if self.applied_table_entries.get("arp_table_host_entries") is not None:
if {"ip": entry.key, "nexthop_id": entry.nextHopId} not in self.applied_table_entries["arp_table_host_entries"]:
tables["arp_table"].append((f'"{entry.key}"', entry.nextHopId))
else:
tables["arp_table"] = [(f'"{entry.key}"', entry.nextHopId)]
else:
return TIFControlResponse(
status= 400
)
if request.ipv4HostEntries:
for entry in request.ipv4HostEntries:
index = find_ip_in_entries(self.switch_configuration["ipv4_host_entries"], entry.key)
if index == -1 :
self.switch_configuration["ipv4_host_entries"].append({"ip": entry.key, "nexthop_id": entry.nextHopId})
if self.applied_table_entries.get("ipv4_host_entries") is not None:
if {"ip": entry.key, "nexthop_id": entry.nextHopId} not in self.applied_table_entries["ipv4_host_entries"]:
tables["ipv4_host"].append((f'"{entry.key}"', entry.nextHopId))
else:
tables["ipv4_host"] = [(f'"{entry.key}"', entry.nextHopId)]
else:
return TIFControlResponse(
status= 400
)
if request.nexthopMapEntries:
for entry in request.nexthopMapEntries:
if entry.key not in self.switch_configuration["nexthop_map"].keys():
self.switch_configuration["nexthop_map"][entry.key] = entry.nextHopId
if self.applied_table_entries.get("nexthop_map") is not None:
if entry.key not in self.applied_table_entries["nexthop_map"]:
tables["nexthop"].append((f'"{entry.key}"', entry.nextHopId))
else:
tables["nexthop"] = [(f'"{entry.key}"', entry.nextHopId)]
else:
return TIFControlResponse(
status= 400
)
bfrt_python_code = self._build_table_entry_bfrt_python_code("add", tables)
self.logger.debug("BFRuntime Python Code: {}".format(bfrt_python_code))
self._run_bfshell_bfrt_python(bfrt_python_code)
if request.runtimeRules:
self.applied_table_entries.update({"tenant_rules": {self._build_tenant_cnf_id(request.tenantMetadata.tenantId, request.tenantMetadata.tenantFuncName): tables["tenant_rules"]},}) # Add the applied tenant table entries to the applied table entries list.
if "tenant_rules" in tables.keys():
tables.pop("tenant_rules")
self.applied_table_entries.update(tables) # Add the other applied table entries to the applied table entries list.
self.save_switch_configuration()
except Exception as ex:
self.logger.exception(ex)
return TIFControlResponse(
status= 500,
message="Error while adding table entries: {}".format(str(ex))
)
return TIFControlResponse(
status = 200,
)
def UpdateTableEntries(self, request : TIFControlRequest, context):
"""
Updates the table entries in the switch configuration based on the provided request.
Parameters:
-----------
request (TIFControlRequest):
The request containing the table entries to be updated.
context:
The context of the request.
Returns:
--------
TIFControlResponse: The response indicating the status of the update operation.
"""
def check_if_equal(rule1, rule2):
"""
Check if two rules are equal.
Parameters:
-----------
rule1 (dict):
The first rule to compare.
rule2 (dict):
The second rule to compare.
Returns:
--------
bool: True if the rules are equal, False otherwise.
"""
return rule1["ip"] == rule2["ip"] and rule1["nexthop_id"] == rule2["nexthop_id"]
def find_ip_in_entries(entry_list, value):
"""
Finds the index of an IP address in a list of entries.
Parameters:
-----------
entry_list (list):
The list of entries to search in.
value:
The IP address to find.
Returns:
--------
int: The index of the IP address in the list, or -1 if not found.
"""
for i, entry in enumerate(entry_list):
if entry["ip"] == value:
return i
return -1
def get_index_of_rule(rule, table):
"""
Get the index of a rule in a table.
Parameters:
-----------
rule (dict):
The rule to find.
table (list):
The table to search in.
Returns:
--------
int: The index of the rule in the table, or -1 if not found.
"""
for i, r in enumerate(table):
if r["table"] == rule["table"] and r["matches"] == rule["matches"] :
return i
return -1
def search_rule(rule, table):
"""
Search for a rule in a table.
Parameters:
-----------
rule (dict):
The rule to search for.
table (list):
The table to search in.
Returns:
--------
dict: The rule found in the table, or None if not found.
"""
for r in table:
if r["table"] == rule["table"] and r["matches"] == rule["matches"]:
return r
return None
tables = {}
try:
if request.runtimeRules:
for rule in request.runtimeRules:
rule = MessageToDict(rule)
rule["matches"] = ast.literal_eval(rule["matches"][0])
if isinstance(rule["matches"], str):
rule["matches"] = ast.literal_eval(rule["matches"])
if len(rule["matches"]) != 0:
for key_name, key in rule["matches"].items():
if is_valid_mac(str(key)):
rule["matches"][key_name] = "'{}'".format(key)
elif is_valid_ipv4(str(key)):
rule["matches"][key_name] = "'{}'".format(key)
rule["actionParams"] = ast.literal_eval(rule["actionParams"][0])
if isinstance(rule["actionParams"], str):
rule["actionParams"] = ast.literal_eval(rule["actionParams"])
if len(rule["actionParams"]) != 0:
for key_name, key in rule["actionParams"].items():
if is_valid_mac(str(key)):
rule["actionParams"][key_name] = "'{}'".format(key)
elif is_valid_ipv4(str(key)):
rule["actionParams"][key_name] = "'{}'".format(key)
tenant_cnf_id = self._build_tenant_cnf_id(request.tenantMetadata.tenantId, request.tenantMetadata.tenantFuncName)
if tenant_cnf_id in self.switch_configuration["tenant_rules"].keys():
index = get_index_of_rule(rule, self.switch_configuration["tenant_rules"][tenant_cnf_id])
if index == -1:
return TIFControlResponse(
status= 400,
message="Error while updating table entries: Entry {} in table {} does not exist!".format(rule, "tenant_rules")
)
else:
self.switch_configuration["tenant_rules"][tenant_cnf_id][index] = rule
if self.applied_table_entries.get("tenant_rules") is not None:
if search_rule(rule, self.applied_table_entries["tenant_rules"][tenant_cnf_id]) is not None:
if tables.get("tenant_rules") is not None:
tables["tenant_rules"].append(rule)
else:
tables["tenant_rules"] = [rule]
else:
tables["tenant_rules"] = [rule]
if request.arpHostEntries:
for entry in request.arpHostEntries:
index = find_ip_in_entries(self.switch_configuration["arp_table_host_entries"], entry.key)
if index == -1 :
self.switch_configuration["arp_table_host_entries"].append({"ip": entry.key, "nexthop_id": entry.nextHopId})
if self.applied_table_entries.get("arp_table") is not None:
if {"ip": entry.key, "nexthop_id": entry.nextHopId} not in self.applied_table_entries["arp_table"]:
# tables["arp_table"].append((entry.key, entry.nextHopId))
return TIFControlResponse(
status= 404,
message="Error while updating table entries: Entry {} in table {} does not exist!".format(entry.key, "arp_table")
)
else:
tables["arp_table"].append((f'"{entry.key}"', entry.nextHopId))
else:
tables["arp_table"] = [(f'"{entry.key}"', entry.nextHopId)]
else:
if not check_if_equal(self.switch_configuration["arp_table_host_entries"][index], {"ip": entry.key, "nexthop_id": entry.nextHopId}):
self.switch_configuration["arp_table_host_entries"][index] = {"ip": entry.key, "nexthop_id": entry.nextHopId}
if not isinstance(self.applied_table_entries.get("arp_table"), list):
tables["arp_table"] = [(f'"{entry.key}"', entry.nextHopId)]
else:
if "arp_table" not in tables.keys():
tables["arp_table"] = [(f'"{entry.key}"', entry.nextHopId)]
else:
tables["arp_table"].append((f'"{entry.key}"', entry.nextHopId))
if request.ipv4HostEntries:
for entry in request.ipv4HostEntries:
index = find_ip_in_entries(self.switch_configuration["ipv4_host_entries"], entry.key)
if index == -1 :
# We can only update existing entries since Tofino support atomic operations!
return TIFControlResponse(
status= 400,
message="Error while updating table entries: Entry {} in table {} does not exist!".format(entry.key, "ipv4_host_entries")
)
else:
self.switch_configuration["ipv4_host_entries"][index] = {"ip": entry.key, "nexthop_id": entry.nextHopId}
if not isinstance(self.applied_table_entries.get("ipv4_host_entries"), list):
tables["ipv4_host"] = [(f'"{entry.key}"', entry.nextHopId)]
else:
if "ipv4_host" not in tables.keys():
tables["ipv4_host"] = [(f'"{entry.key}"', entry.nextHopId)]
else:
tables["ipv4_host"].append((f'"{entry.key}"', entry.nextHopId))
if request.nexthopMapEntries:
for entry in request.nexthopMapEntries:
self.switch_configuration["nexthop_map"][entry.key] = entry.nextHopId
if self.applied_table_entries.get("nexthop_map") is not None:
if entry.key in self.applied_table_entries["nexthop_map"]:
tables["nexthop"].append((f'"{entry.key}"', entry.nextHopId))
else:
return TIFControlResponse(
status= 400,
message="Error while updating table entries: Entry {} in table {} does not exist!".format(entry.key, "nexthop_map")
)
else:
if "nexthop" not in tables.keys():
tables["nexthop"] = [(f'"{entry.key}"', entry.nextHopId)]
else:
tables["nexthop"].append((f'"{entry.key}"', entry.nextHopId))
bfrt_python_code = self._build_table_entry_bfrt_python_code("update", tables)
self._run_bfshell_bfrt_python(bfrt_python_code)
self.applied_table_entries.update(tables)
self.save_switch_configuration()
except Exception as ex:
self.logger.exception(ex)
return TIFControlResponse(
status= 500,
message="Error while updating table entries: {}".format(str(ex))
)
return TIFControlResponse(
status = 200,
)
def DeleteTableEntries(self, request : TIFControlRequest, context):
"""
Deletes table entries based on the provided request.
Parameters:
-----------
request (TIFControlRequest):
The request object containing the entries to be deleted.
context:
The context object for the gRPC request.
Returns:
--------
TIFControlResponse: The response object indicating the status of the operation.
"""
def find_ip_in_entries(entry_list, value):
"""
Helper function to find the index of an IP address in a list of entries.
Parameters:
-----------
entry_list (list):
The list of entries to search in.
value:
The IP address to search for.
Returns:
--------
int: The index of the IP address in the list, or -1 if not found.
"""
for i, entry in enumerate(entry_list):
if entry["ip"] == value:
return i
return -1
try:
tables = {}
tables["arp_table"] = []
tables["ipv4_host"] = []
tables["nexthop"] = []
tables["tenant_rules"] = []
if request.runtimeRules:
tables["tenant_rules"] = []
for rule in request.runtimeRules:
tenant_cnf_id = self._build_tenant_cnf_id(request.tenantMetadata.tenantId, request.tenantMetadata.tenantFuncName)
rule = MessageToDict(rule)
rule["matches"] = ast.literal_eval(rule["matches"][0])
rule["actionParams"] = ast.literal_eval(rule["actionParams"][0])
if isinstance(rule["matches"], str):
rule["matches"] = ast.literal_eval(rule["matches"])
if isinstance(rule["actionParams"], str):
rule["actionParams"] = ast.literal_eval(rule["actionParams"])
if len(rule["matches"]) != 0:
for key_name, key in rule["matches"].items():
if is_valid_mac(str(key)):
rule["matches"][key_name] = "'{}'".format(key)
elif is_valid_ipv4(str(key)):
rule["matches"][key_name] = "'{}'".format(key)
if isinstance(rule["actionParams"], list):
rule["actionParams"] = ast.literal_eval(rule["actionParams"][0])
if len(rule["actionParams"]) != 0:
for key_name, key in rule["actionParams"].items():
if is_valid_mac(str(key)):
rule["actionParams"][key_name] = "'{}'".format(key)
elif is_valid_ipv4(str(key)):
rule["actionParams"][key_name] = "'{}'".format(key)
if tenant_cnf_id in self.switch_configuration["tenant_rules"].keys():
index = self.switch_configuration["tenant_rules"][tenant_cnf_id].index(rule)
if index == -1:
return TIFControlResponse(
status = 404,
message="Error while deleting table entries: Entry {} in table {} does not exist!".format(rule, "tenant_rules")
)
else:
rule = self.switch_configuration["tenant_rules"][tenant_cnf_id].pop(index)
if len(self.switch_configuration["tenant_rules"][tenant_cnf_id]) == 0:
del self.switch_configuration["tenant_rules"][tenant_cnf_id]
if self.applied_table_entries.get("tenant_rules") is not None:
if rule in self.applied_table_entries["tenant_rules"][tenant_cnf_id]:
index = self.applied_table_entries["tenant_rules"][tenant_cnf_id].index(rule)
if index != -1:
tables["tenant_rules"].append(rule)
else:
return TIFControlResponse(
status = 404,
message="Error while deleting table entries: Entry {} in table {} does not exist!".format(rule, "tenant_rules")
)
else:
return TIFControlResponse(
status = 404,
message="Error while deleting table entries: Entry {} in table {} does not exist!".format(rule, "tenant_rules")
)
else:
return TIFControlResponse(
status = 404,
message="Error while deleting table entries: Entry {} in table {} does not exist!".format(rule, "tenant_rules")
)
if request.arpHostEntries:
for entry in request.arpHostEntries:
index = find_ip_in_entries(self.switch_configuration["arp_table_host_entries"], entry.key)
if index == -1 :
return TIFControlResponse(
status = 404
)
else:
rule = self.switch_configuration["arp_table_host_entries"].pop(index)
if self.applied_table_entries.get("arp_table") is not None:
if rule in self.applied_table_entries["arp_table"]:
tables["arp_table"].append((f'"{rule["ip"]}"', rule["nexthop_id"]))
else:
return TIFControlResponse(
status = 404
)
if request.ipv4HostEntries:
for entry in request.ipv4HostEntries:
index = find_ip_in_entries(self.switch_configuration["ipv4_host_entries"], entry.key)
if index == -1 :
return TIFControlResponse(
status = 404
)
else:
rule = self.switch_configuration["ipv4_host_entries"].pop(index)
if self.applied_table_entries.get("ipv4_host") is not None:
if rule not in self.applied_table_entries["ipv4_host"]:
tables["ipv4_host"].append((f'"{rule["ip"]}"', rule["nexthop_id"]))
if request.nexthopMapEntries:
for entry in request.nexthopMapEntries:
self.switch_configuration["nexthop_map"].pop(entry.key)
if self.applied_table_entries.get("nexthop") is not None:
if entry.key not in self.applied_table_entries["nexthop"]:
tables["nexthop"].append(entry.key)
bfrt_python_code = self._build_table_entry_bfrt_python_code("delete", tables)
self._run_bfshell_bfrt_python(bfrt_python_code)
# Remove the deleted table entries from the applied table entries list.
for table in self.applied_table_entries.keys():
if table in tables.keys():
if table == "tenant_rules":
for rule in tables[table]:
self.applied_table_entries[table][self._build_tenant_cnf_id(request.tenantMetadata.tenantId, request.tenantMetadata.tenantFuncName)].remove(rule)
else:
self.applied_table_entries[table].remove(tables[table])
self.save_switch_configuration()
except Exception as ex:
self.logger.exception(ex)
return TIFControlResponse(
status= 500,
message="Error while deleting table entries: {}".format(str(ex))
)
return TIFControlResponse(
status = 200,
)
def GetLAGConfiguration(self, request : TIFControlRequest, context):
"""
Retrieves the LAG (Link Aggregation Group) configuration.
Parameters:
----------
request (TIFControlRequest):
The request object containing the LAG groups.
context:
The context object for the gRPC request.
Returns:
--------
TIFControlResponse: The response object containing the LAG configuration.
Raises:
-------
Exception: If there is an error while getting the LAG configuration.
"""
try:
if len(request.lagGroups) > 0:
return TIFControlResponse(
status = 200,
message = "",
lagGroups = [ParseDict(self.switch_configuration["lag_ecmp_groups"][self._get_lag_name(lag.id)], Lag()) for lag in request.lagGroups if self._get_lag_name(lag.id) is not None]
)
else:
return TIFControlResponse(
status = 200,
message = "",
lagGroups = [ParseDict(lag, Lag()) for name, lag in self.switch_configuration["lag_ecmp_groups"].items()]
)
except Exception as ex:
self.logger.exception(ex)
return TIFControlResponse(
status= 500,
message="Error while getting LAG configuration: {}".format(str(ex))
)
def AddLAG(self, request: TIFControlRequest, context):
"""
Adds a Link Aggregation Group (LAG) to the switch configuration.
Parameters:
----------
request (TIFControlRequest):
The request object containing the LAG information.
context:
The context object for the gRPC request.
Returns:
--------
TIFControlResponse: The response object indicating the status of the LAG addition.
Raises:
-------
Exception: If an error occurs while adding the LAG(s).
"""
try:
for lag in request.lagGroups:
if self._get_lag_name(lag.id) is not None:
return TIFControlResponse(
status=400,
message="Adding LAG(s) failed: LAG already exists!"
)
else:
lag_num = len(self.switch_configuration["lag_ecmp_groups"]) + 1
self.switch_configuration["lag_ecmp_groups"]["lag_" + str(lag_num)] = {
"id": lag.id,
"memberbase": lag.memberbase,
"dp_ports": [{"portId": port.portId, "active": port.active} for port in lag.dp_ports]
}
self._run_tif_initialization_setup_script()
self.save_switch_configuration()
return TIFControlResponse(
status=200,
message="Adding LAG(s) successful"
)
except Exception as ex:
self.logger.exception(ex)
return TIFControlResponse(
status=500,
message="Error while adding LAG(s): {}".format(str(ex))
)
def UpdateLAG(self, request : TIFControlRequest, context):
"""
Update the Link Aggregation Groups (LAGs) based on the provided request.
Parameters:
----------
request (TIFControlRequest):
The request object containing the LAG groups to be updated.
context:
The context object for the gRPC request.
Returns:
--------
TIFControlResponse: The response object indicating the status of the LAG update operation.
"""
try:
for lag in request.lagGroups:
lag_name = self._get_lag_name(lag.id)
if lag_name is not None:
self.switch_configuration["lag_ecmp_groups"][lag_name] = {
"id" : lag.id,
"memberbase": lag.memberbase,
"dp_ports" : [{"portId": port.portId, "active": port.active} for port in lag.dp_ports]
}
else:
return TIFControlResponse(
status=400,
message="Updating LAG(s) failed: Does not exist!"
)
self._run_tif_initialization_setup_script()
self.save_switch_configuration()
return TIFControlResponse(
status=200,
message="Updating LAG(s) successful"
)
except Exception as ex:
self.logger.exception(ex)
return TIFControlResponse(
status=500,
message="Error while updating LAG(s): {}".format(str(ex))
)
def DeleteLAG(self, request : TIFControlRequest, context):
"""
Deletes the specified LAG(s) from the switch configuration.
Parameters:
----------
request (TIFControlRequest):
The request object containing the LAG(s) to be deleted.
context:
The context object for the gRPC request.
Returns:
--------
TIFControlResponse: The response object indicating the status of the LAG deletion operation.
"""
try:
for lag in request.lagGroups:
lag_name = self._get_lag_name(lag.id)
if lag_name is not None:
self.switch_configuration["lag_ecmp_groups"].pop(lag_name)
else:
return TIFControlResponse(
status=400,
message="Deleting LAG(s) failed: Does not exist!"
)
self._run_tif_initialization_setup_script()
self.save_switch_configuration()
return TIFControlResponse(
status=200,
message="Deleting LAG(s) successful"
)
except Exception as ex:
self.logger.exception(ex)
return TIFControlResponse(
status=500,
message="Error while deleting LAG(s): {}".format(str(ex))
)
def GetLAGMemberState(self, request: TIFControlRequest, context):
"""
Get the member state of the LAG groups.
Parameters:
----------
request (TIFControlRequest):
The request object containing the LAG groups.
context:
The context object.
Returns:
--------
TIFControlResponse: The response object containing the member state of the LAG groups.
"""
try:
if len(request.lagGroups) > 0:
lagGroups = []
for lag in request.lagGroups: