Newer
Older
# Copyright 2022-2024 ETSI SDG TeraFlowSDN (TFS) (https://tfs.etsi.org/)
#
# 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.
"""
P4Runtime manager.
"""
import enum
import os
import queue
import time
import logging
from collections import Counter, OrderedDict
from threading import Thread
from tabulate import tabulate
from p4.v1 import p4runtime_pb2
from p4.config.v1 import p4info_pb2
try:
from .p4_client import P4RuntimeClient, P4RuntimeException,\
P4RuntimeWriteException, WriteOperation, parse_p4runtime_error
from .p4_context import P4RuntimeEntity, P4Type, Context
from .p4_global_options import make_canonical_if_option_set
from .p4_common import encode,\
parse_resource_string_from_json, parse_resource_integer_from_json,\
parse_resource_bytes_from_json, parse_match_operations_from_json,\
parse_action_parameters_from_json, parse_integer_list_from_json,\
parse_replicas_from_json
from .p4_exception import UserError, InvalidP4InfoError
except ImportError:
from p4_client import P4RuntimeClient, P4RuntimeException,\
P4RuntimeWriteException, WriteOperation, parse_p4runtime_error
from p4_context import P4RuntimeEntity, P4Type, Context
from p4_global_options import make_canonical_if_option_set
from p4_common import encode,\
parse_resource_string_from_json, parse_resource_integer_from_json,\
parse_resource_bytes_from_json, parse_match_operations_from_json,\
parse_action_parameters_from_json, parse_integer_list_from_json
from p4_exception import UserError, InvalidP4InfoError
# Logger instance
LOGGER = logging.getLogger(__name__)
# Global P4Runtime context
CONTEXT = Context()
# Global P4Runtime client
KEY_TABLE = "table"
KEY_ACTION = "action"
KEY_ACTION_PROFILE = "action_profile"
KEY_COUNTER = "counter"
KEY_DIR_COUNTER = "direct_counter"
KEY_METER = "meter"
KEY_DIR_METER = "direct_meter"
KEY_CTL_PKT_METADATA = "controller_packet_metadata"
KEY_DIGEST = "digest"
# Extra resource keys
KEY_CLONE_SESSION = "clone_session"
KEY_ENDPOINT = "endpoint"
def get_context():
"""
Return P4 context.
:return: context object
"""
return CONTEXT
def get_table_type(table):
"""
Assess the type of P4 table based upon the matching scheme.
:param table: P4 table
:return: P4 table type
"""
for m_f in table.match_fields:
# LPM and range are special forms of ternary
if m_f.match_type in [
p4info_pb2.MatchField.TERNARY,
p4info_pb2.MatchField.LPM,
p4info_pb2.MatchField.RANGE
]:
is_ternary = True
if is_ternary:
return p4info_pb2.MatchField.TERNARY
return p4info_pb2.MatchField.EXACT
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
def match_type_to_str(match_type):
"""
Convert table match type to string.
:param match_type: table match type object
:return: table match type string
"""
if match_type == p4info_pb2.MatchField.EXACT:
return "Exact"
if match_type == p4info_pb2.MatchField.LPM:
return "LPM"
if match_type == p4info_pb2.MatchField.TERNARY:
return "Ternary"
if match_type == p4info_pb2.MatchField.RANGE:
return "Range"
if match_type == p4info_pb2.MatchField.OPTIONAL:
return "Optional"
return None
class P4Manager:
"""
Class to manage the runtime entries of a P4 pipeline.
"""
def __init__(self, device_id: int, ip_address: str, port: int,
election_id: tuple, role_name=None, ssl_options=None):
self.__id = device_id
self.__ip_address = ip_address
self.__port = int(port)
self.__grpc_endpoint = f"{self.__ip_address}:{self.__port}"
self.key_id = ip_address+str(port)
CLIENTS[self.key_id] = P4RuntimeClient(
self.__id, self.__grpc_endpoint, election_id, role_name, ssl_options)
self.local_client = CLIENTS[self.key_id]
# Internal memory for whitebox management
# | -> P4 entities
self.p4_objects = {}
# | -> P4 entities
self.table_entries = {}
self.action_profile_members = {}
self.action_profile_groups = {}
self.counter_entries = {}
self.direct_counter_entries = {}
self.meter_entries = {}
self.direct_meter_entries = {}
self.clone_session_entries = {}
self.multicast_groups = {}
def start(self, p4bin_path, p4info_path):
"""
Start the P4 manager. This involves:
(i) setting the forwarding pipeline of the target switch,
(ii) creating a P4 context object,
(iii) Discovering all the entities of the pipeline, and
(iv) initializing necessary data structures of the manager
:param p4bin_path: Path to the P4 binary file
:param p4info_path: Path to the P4 info file
:return: void
"""
if not p4bin_path or not os.path.exists(p4bin_path):
LOGGER.warning("P4 binary file not found")
if not p4info_path or not os.path.exists(p4info_path):
LOGGER.warning("P4 info file not found")
# Forwarding pipeline is only set iff both files are present
if p4bin_path and p4info_path:
try:
self.local_client.set_fwd_pipe_config(p4info_path, p4bin_path)
except FileNotFoundError as ex:
LOGGER.critical(ex)
raise FileNotFoundError(ex) from ex
except P4RuntimeException as ex:
LOGGER.critical("Error when setting config")
LOGGER.critical(ex)
raise P4RuntimeException(ex) from ex
except Exception as ex: # pylint: disable=broad-except
LOGGER.critical("Error when setting config")
self.__p4info = self.local_client.get_p4info()
except P4RuntimeException as ex:
LOGGER.critical("Error when retrieving P4Info")
LOGGER.critical(ex)
raise P4RuntimeException(ex) from ex
CONTEXT.set_p4info(self.__p4info)
self.__discover_objects()
self.__init_objects()
LOGGER.info("P4Runtime manager started")
def stop(self):
"""
Stop the P4 manager. This involves:
(i) tearing the P4Runtime client down and
(ii) cleaning up the manager's internal memory
:return: void
"""
# gRPC client must already be instantiated
# Trigger connection tear down with the P4Runtime server
# Remove client entry from global dictionary
CLIENTS.pop(self.key_id)
self.__clear()
LOGGER.info("P4Runtime manager stopped")
def __clear(self):
"""
Reset basic members of the P4 manager.
:return: void
"""
self.__id = None
self.__ip_address = None
self.__port = None
self.__grpc_endpoint = None
self.__clear_state()
def __clear_state(self):
"""
Reset the manager's internal memory.
:return: void
"""
self.table_entries.clear()
self.action_profile_members.clear()
self.action_profile_groups.clear()
self.counter_entries.clear()
self.direct_counter_entries.clear()
self.meter_entries.clear()
self.direct_meter_entries.clear()
self.clone_session_entries.clear()
self.multicast_groups.clear()
self.p4_objects.clear()
def __init_objects(self):
"""
Parse the discovered P4 objects and initialize internal memory for all
the underlying P4 entities.
:return: void
"""
global KEY_TABLE, KEY_ACTION, KEY_ACTION_PROFILE, \
KEY_COUNTER, KEY_DIR_COUNTER, \
KEY_METER, KEY_DIR_METER, \
KEY_CTL_PKT_METADATA, KEY_DIGEST, KEYS_P4
KEY_TABLE = P4Type.table.name
KEY_ACTION = P4Type.action.name
KEY_ACTION_PROFILE = P4Type.action_profile.name
KEY_COUNTER = P4Type.counter.name
KEY_DIR_COUNTER = P4Type.direct_counter.name
KEY_METER = P4Type.meter.name
KEY_DIR_METER = P4Type.direct_meter.name
KEY_CTL_PKT_METADATA = P4Type.controller_packet_metadata.name
KEY_DIGEST = P4Type.digest.name
KEYS_P4 = [
KEY_TABLE, KEY_ACTION, KEY_ACTION_PROFILE,
KEY_COUNTER, KEY_DIR_COUNTER,
KEY_METER, KEY_DIR_METER,
KEY_CTL_PKT_METADATA, KEY_DIGEST
]
assert (k for k in KEYS_P4)
if not self.p4_objects:
LOGGER.warning(
"Cannot initialize internal memory without discovering "
"the pipeline\'s P4 objects")
return
# Initialize all sorts of entries
if KEY_TABLE in self.p4_objects:
for table in self.p4_objects[KEY_TABLE]:
self.table_entries[table.name] = []
if KEY_ACTION_PROFILE in self.p4_objects:
for act_prof in self.p4_objects[KEY_ACTION_PROFILE]:
self.action_profile_members[act_prof.name] = []
self.action_profile_groups[act_prof.name] = []
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
if KEY_COUNTER in self.p4_objects:
for cnt in self.p4_objects[KEY_COUNTER]:
self.counter_entries[cnt.name] = []
if KEY_DIR_COUNTER in self.p4_objects:
for d_cnt in self.p4_objects[KEY_DIR_COUNTER]:
self.direct_counter_entries[d_cnt.name] = []
if KEY_METER in self.p4_objects:
for meter in self.p4_objects[KEY_METER]:
self.meter_entries[meter.name] = []
if KEY_DIR_METER in self.p4_objects:
for d_meter in self.p4_objects[KEY_DIR_METER]:
self.direct_meter_entries[d_meter.name] = []
def __discover_objects(self):
"""
Discover and store all P4 objects.
:return: void
"""
self.__clear_state()
for obj_type in P4Type:
for obj in P4Objects(obj_type):
if obj_type.name not in self.p4_objects:
self.p4_objects[obj_type.name] = []
self.p4_objects[obj_type.name].append(obj)
def get_table(self, table_name):
"""
Get a P4 table by name.
:param table_name: P4 table name
:return: P4 table object
"""
if KEY_TABLE not in self.p4_objects:
return None
for table in self.p4_objects[KEY_TABLE]:
if table.name == table_name:
return table
return None
def get_tables(self):
"""
Get a list of all P4 tables.
:return: list of P4 tables or empty list
"""
if KEY_TABLE not in self.p4_objects:
return []
return self.p4_objects[KEY_TABLE]
def get_action(self, action_name):
"""
Get action by name.
:param action_name: name of a P4 action
:return: action object or None
"""
if KEY_ACTION not in self.p4_objects:
return None
for action in self.p4_objects[KEY_ACTION]:
if action.name == action_name:
return action
return None
def get_actions(self):
"""
Get a list of all P4 actions.
:return: list of P4 actions or empty list
"""
if KEY_ACTION not in self.p4_objects:
return []
return self.p4_objects[KEY_ACTION]
def get_action_profile(self, action_prof_name):
"""
Get action profile by name.
:param action_prof_name: name of the action profile
:return: action profile object or None
"""
if KEY_ACTION_PROFILE not in self.p4_objects:
return None
for action_prof in self.p4_objects[KEY_ACTION_PROFILE]:
if action_prof.name == action_prof_name:
return action_prof
return None
def get_action_profiles(self):
"""
Get a list of all P4 action profiles.
:return: list of P4 action profiles or empty list
"""
if KEY_ACTION_PROFILE not in self.p4_objects:
return []
return self.p4_objects[KEY_ACTION_PROFILE]
def get_counter(self, cnt_name):
"""
Get counter by name.
:param cnt_name: name of a P4 counter
:return: counter object or None
"""
if KEY_COUNTER not in self.p4_objects:
return None
for cnt in self.p4_objects[KEY_COUNTER]:
if cnt.name == cnt_name:
return cnt
return None
def get_counters(self):
"""
Get a list of all P4 counters.
:return: list of P4 counters or empty list
"""
if KEY_COUNTER not in self.p4_objects:
return []
return self.p4_objects[KEY_COUNTER]
def get_direct_counter(self, dir_cnt_name):
"""
Get direct counter by name.
:param dir_cnt_name: name of a direct P4 counter
:return: direct counter object or None
"""
if KEY_DIR_COUNTER not in self.p4_objects:
return None
for d_cnt in self.p4_objects[KEY_DIR_COUNTER]:
if d_cnt.name == dir_cnt_name:
return d_cnt
return None
def get_direct_counters(self):
"""
Get a list of all direct P4 counters.
:return: list of direct P4 counters or empty list
"""
if KEY_DIR_COUNTER not in self.p4_objects:
return []
return self.p4_objects[KEY_DIR_COUNTER]
def get_meter(self, meter_name):
"""
Get meter by name.
:param meter_name: name of a P4 meter
:return: meter object or None
"""
if KEY_METER not in self.p4_objects:
return None
for meter in self.p4_objects[KEY_METER]:
if meter.name == meter_name:
return meter
return None
def get_meters(self):
"""
Get a list of all P4 meters.
:return: list of P4 meters or empty list
"""
if KEY_METER not in self.p4_objects:
return []
return self.p4_objects[KEY_METER]
def get_direct_meter(self, dir_meter_name):
"""
Get direct meter by name.
:param dir_meter_name: name of a direct P4 meter
:return: direct meter object or None
"""
if KEY_DIR_METER not in self.p4_objects:
return None
for d_meter in self.p4_objects[KEY_DIR_METER]:
if d_meter.name == dir_meter_name:
return d_meter
return None
def get_direct_meters(self):
"""
Get a list of all direct P4 meters.
:return: list of direct P4 meters or empty list
"""
if KEY_DIR_METER not in self.p4_objects:
return []
return self.p4_objects[KEY_DIR_METER]
def get_ctl_pkt_metadata(self, ctl_pkt_meta_name):
"""
Get a packet replication object by name.
:param ctl_pkt_meta_name: name of a P4 packet replication object
:return: P4 packet replication object or None
"""
if KEY_CTL_PKT_METADATA not in self.p4_objects:
return None
for pkt_meta in self.p4_objects[KEY_CTL_PKT_METADATA]:
if ctl_pkt_meta_name == pkt_meta.name:
return pkt_meta
return None
def get_digest(self, digest_name):
"""
Get a digest object by name.
:param digest_name: name of a digest object
:return: digest object or None
"""
if KEY_DIGEST not in self.p4_objects:
return None
for dg in self.p4_objects[KEY_DIGEST]:
if dg == digest_name.name:
return digest_name
return None
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
def get_resource_keys(self):
"""
Retrieve the available P4 resource keys.
:return: list of P4 resource keys
"""
return list(self.p4_objects.keys())
def count_active_entries(self):
"""
Count the number of active entries across all supported P4 entities.
:return: active number of entries
"""
tot_cnt = \
self.count_table_entries_all() + \
self.count_counter_entries_all() + \
self.count_direct_counter_entries_all() + \
self.count_meter_entries_all() + \
self.count_direct_meter_entries_all() + \
self.count_action_prof_member_entries_all() + \
self.count_action_prof_group_entries_all()
return tot_cnt
############################################################################
# Table methods
############################################################################
def get_table_names(self):
"""
Retrieve a list of P4 table names.
:return: list of P4 table names
"""
if KEY_TABLE not in self.p4_objects:
return []
return list(table.name for table in self.p4_objects[KEY_TABLE])
def get_table_entries(self, table_name, action_name=None):
"""
Get a list of P4 table entries by table name and optionally by action.
:param table_name: name of a P4 table
:param action_name: action name
:return: list of P4 table entries or None
"""
if table_name not in self.table_entries:
return None
self.table_entries[table_name].clear()
self.table_entries[table_name] = []
try:
entries = TableEntry(self.local_client, table_name).read()
assert self.local_client
for table_entry in entries:
self.table_entries[table_name].append(table_entry)
return self.table_entries[table_name]
except P4RuntimeException as ex:
LOGGER.error("Failed to get table %s entries: %s",
table_name, str(ex))
return []
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
def table_entries_to_json(self, table_name):
"""
Encode all entries of a P4 table into a JSON object.
:param table_name: name of a P4 table
:return: JSON object with table entries
"""
if (KEY_TABLE not in self.p4_objects) or \
not self.p4_objects[KEY_TABLE]:
LOGGER.warning("No table entries to retrieve\n")
return {}
table_res = {}
for table in self.p4_objects[KEY_TABLE]:
if not table.name == table_name:
continue
entries = self.get_table_entries(table.name)
if len(entries) == 0:
continue
table_res["table-name"] = table_name
for ent in entries:
entry_match_field = "\n".join(ent.match.fields())
entry_match_type = match_type_to_str(
ent.match.match_type(entry_match_field))
table_res["id"] = ent.id
table_res["match-fields"] = []
for match_field in ent.match.fields():
table_res["match-fields"].append(
{
"match-field": match_field,
"match-value": ent.match.value(match_field),
"match-type": entry_match_type
}
)
table_res["actions"] = []
table_res["actions"].append(
{
"action-id": ent.action.id(),
"action": ent.action.alias()
}
)
table_res["priority"] = ent.priority
table_res["is-default"] = ent.is_default
table_res["idle-timeout"] = ent.idle_timeout_ns
if ent.metadata:
table_res["metadata"] = ent.metadata
return table_res
def count_table_entries(self, table_name, action_name=None):
"""
Count the number of entries in a P4 table.
:param table_name: name of a P4 table
:param action_name: action name
:return: number of P4 table entries or negative integer
upon missing table
"""
count = 0
try:
entries = TableEntry(self.local_client, table_name).read()
count = sum(1 for _ in entries)
except Exception as e: # pylint: disable=broad-except
LOGGER.error("Failed to read entries of table: %s", table_name)
return count
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
def count_table_entries_all(self):
"""
Count all entries in a P4 table.
:return: number of P4 table entries
"""
total_cnt = 0
for table_name in self.get_table_names():
cnt = self.count_table_entries(table_name)
if cnt < 0:
continue
total_cnt += cnt
return total_cnt
def table_entry_operation_from_json(
self, json_resource, operation: WriteOperation):
"""
Parse a JSON-based table entry and insert/update/delete it
into/from the switch.
:param json_resource: JSON-based table entry
:param operation: Write operation (i.e., insert, modify, delete)
to perform.
:return: inserted entry or None in case of parsing error
"""
table_name = parse_resource_string_from_json(
json_resource, "table-name")
match_map = parse_match_operations_from_json(json_resource)
action_name = parse_resource_string_from_json(
json_resource, "action-name")
action_params = parse_action_parameters_from_json(json_resource)
priority = parse_resource_integer_from_json(json_resource, "priority")
metadata = parse_resource_bytes_from_json(json_resource, "metadata")
if operation in [WriteOperation.insert, WriteOperation.update]:
LOGGER.info("Table entry to insert/update: %s", json_resource)
return self.insert_table_entry(
table_name=table_name,
match_map=match_map,
action_name=action_name,
action_params=action_params,
priority=priority,
metadata=metadata if metadata else None
)
if operation == WriteOperation.delete:
LOGGER.info("Table entry to delete: %s", json_resource)
return self.delete_table_entry(
table_name=table_name,
match_map=match_map,
action_name=action_name,
action_params=action_params,
priority=priority
)
return None
def insert_table_entry_exact(self,
table_name, match_map, action_name, action_params, metadata,
cnt_pkt=-1, cnt_byte=-1):
"""
Insert an entry into an exact match table.
:param table_name: P4 table name
:param match_map: Map of match operations
:param action_name: Action name
:param action_params: Map of action parameters
:param metadata: table metadata
:param cnt_pkt: packet count
:param cnt_byte: byte count
:return: inserted entry
"""
assert match_map, "Table entry without match operations is not accepted"
assert action_name, "Table entry without action is not accepted"
table_entry = TableEntry(self.local_client, table_name)(action=action_name)
for match_k, match_v in match_map.items():
table_entry.match[match_k] = match_v
for action_k, action_v in action_params.items():
table_entry.action[action_k] = action_v
if metadata:
table_entry.metadata = metadata
if cnt_pkt > 0:
table_entry.counter_data.packet_count = cnt_pkt
if cnt_byte > 0:
table_entry.counter_data.byte_count = cnt_byte
ex_msg = ""
try:
table_entry.insert()
LOGGER.info("Inserted exact table entry: %s", table_entry)
except (P4RuntimeException, P4RuntimeWriteException) as ex:
ex_msg = str(ex)
LOGGER.warning(ex)
# Table entry exists, needs to be modified
if "ALREADY_EXISTS" in ex_msg:
table_entry.modify()
LOGGER.info("Updated exact table entry: %s", table_entry)
def insert_table_entry_ternary(self,
table_name, match_map, action_name, action_params, metadata,
priority, cnt_pkt=-1, cnt_byte=-1):
"""
Insert an entry into a ternary match table.
:param table_name: P4 table name
:param match_map: Map of match operations
:param action_name: Action name
:param action_params: Map of action parameters
:param metadata: table metadata
:param priority: entry priority
:param cnt_pkt: packet count
:param cnt_byte: byte count
:return: inserted entry
"""
assert match_map, "Table entry without match operations is not accepted"
assert action_name, "Table entry without action is not accepted"
table_entry = TableEntry(self.local_client, table_name)(action=action_name)
for match_k, match_v in match_map.items():
table_entry.match[match_k] = match_v
for action_k, action_v in action_params.items():
table_entry.action[action_k] = action_v
if metadata:
table_entry.metadata = metadata
if cnt_pkt > 0:
table_entry.counter_data.packet_count = cnt_pkt
if cnt_byte > 0:
table_entry.counter_data.byte_count = cnt_byte
ex_msg = ""
try:
table_entry.insert()
LOGGER.info("Inserted ternary table entry: %s", table_entry)
except (P4RuntimeException, P4RuntimeWriteException) as ex:
ex_msg = str(ex)
LOGGER.error(ex)
# Table entry exists, needs to be modified
if "ALREADY_EXISTS" in ex_msg:
table_entry.modify()
LOGGER.info("Updated ternary table entry: %s", table_entry)
def insert_table_entry_range(self,
table_name, match_map, action_name, action_params, metadata,
priority, cnt_pkt=-1, cnt_byte=-1): # pylint: disable=unused-argument
"""
Insert an entry into a range match table.
:param table_name: P4 table name
:param match_map: Map of match operations
:param action_name: Action name
:param action_params: Map of action parameters
:param metadata: table metadata
:param priority: entry priority
:param cnt_pkt: packet count
:param cnt_byte: byte count
:return: inserted entry
"""
assert match_map, "Table entry without match operations is not accepted"
assert action_name, "Table entry without action is not accepted"
raise NotImplementedError(
"Range-based table insertion not implemented yet")
def insert_table_entry_optional(self,
table_name, match_map, action_name, action_params, metadata,
priority, cnt_pkt=-1, cnt_byte=-1): # pylint: disable=unused-argument
"""
Insert an entry into an optional match table.
:param table_name: P4 table name
:param match_map: Map of match operations
:param action_name: Action name
:param action_params: Map of action parameters
:param metadata: table metadata
:param priority: entry priority
:param cnt_pkt: packet count
:param cnt_byte: byte count
:return: inserted entry
"""
assert match_map, "Table entry without match operations is not accepted"
assert action_name, "Table entry without action is not accepted"
raise NotImplementedError(
"Optional-based table insertion not implemented yet")
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
def insert_table_entry(self, table_name,
match_map, action_name, action_params,
priority, metadata=None, cnt_pkt=-1, cnt_byte=-1):
"""
Insert an entry into a P4 table.
This method has internal logic to discriminate among:
(i) Exact matches,
(ii) Ternary matches,
(iii) LPM matches,
(iv) Range matches, and
(v) Optional matches
:param table_name: name of a P4 table
:param match_map: map of match operations
:param action_name: action name
:param action_params: map of action parameters
:param priority: entry priority
:param metadata: entry metadata
:param cnt_pkt: packet count
:param cnt_byte: byte count
:return: inserted entry
"""
table = self.get_table(table_name)
assert table, \
"P4 pipeline does not implement table " + table_name
table_type = get_table_type(table)
if not table_type:
msg = f"Table {table_name} is undefined, cannot insert entry"
LOGGER.error(msg)
raise UserError(msg)
LOGGER.debug("Table {}: {}".format(table_name, match_type_to_str(table_type)))
if table_type == p4info_pb2.MatchField.EXACT:
return self.insert_table_entry_exact(
table_name, match_map, action_name, action_params, metadata,
cnt_pkt, cnt_byte)
# Ternary and LPM matches are supported
[p4info_pb2.MatchField.TERNARY, p4info_pb2.MatchField.LPM]:
return self.insert_table_entry_ternary(
table_name, match_map, action_name, action_params, metadata,
priority, cnt_pkt, cnt_byte)
# TODO: Cover RANGE match # pylint: disable=W0511
if table_type == p4info_pb2.MatchField.RANGE:
return self.insert_table_entry_range(
table_name, match_map, action_name, action_params, metadata,
priority, cnt_pkt, cnt_byte)
# TODO: Cover OPTIONAL match # pylint: disable=W0511
if table_type == p4info_pb2.MatchField.OPTIONAL:
return self.insert_table_entry_optional(
table_name, match_map, action_name, action_params, metadata,
priority, cnt_pkt, cnt_byte)
return None
def delete_table_entry(self, table_name,
match_map, action_name, action_params, priority=0):
"""
Delete an entry from a P4 table.
:param table_name: name of a P4 table
:param match_map: map of match operations
:param action_name: action name
:param action_params: map of action parameters
:param priority: entry priority
:return: deleted entry
"""
table = self.get_table(table_name)
assert table, \
"P4 pipeline does not implement table " + table_name
table_type = get_table_type(table)
if not table_type:
msg = f"Table {table_name} is undefined, cannot delete entry"
LOGGER.error(msg)
raise UserError(msg)
table_entry = TableEntry(self.local_client, table_name)(action=action_name)
for match_k, match_v in match_map.items():
table_entry.match[match_k] = match_v
for action_k, action_v in action_params.items():
table_entry.action[action_k] = action_v
[p4info_pb2.MatchField.TERNARY, p4info_pb2.MatchField.LPM]:
if priority == 0:
msg = f"Table {table_name} is ternary, priority must be != 0"
LOGGER.error(msg)
raise UserError(msg)
# TODO: Ensure correctness of RANGE & OPTIONAL # pylint: disable=W0511
[p4info_pb2.MatchField.RANGE, p4info_pb2.MatchField.OPTIONAL]:
raise NotImplementedError(
"Range and optional-based table deletion not implemented yet")
table_entry.priority = priority
ex_msg = ""
try:
table_entry.delete()
LOGGER.info("Deleted entry %s from table: %s", table_entry, table_name)
except (P4RuntimeException, P4RuntimeWriteException) as ex:
ex_msg = str(ex)
LOGGER.warning(ex)
# Table entry exists, needs to be modified
if "NOT_FOUND" in ex_msg:
# TODO: No way to discriminate between a modified entry and an actual table miss
LOGGER.warning("Table entry was initially modified, thus cannot be removed: %s", table_entry)
return table_entry
def delete_table_entries(self, table_name):
"""
Delete all entries of a P4 table.