Skip to content
p4_manager.py 199 KiB
Newer Older
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 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# 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
    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
CLIENT = None

# Constant P4 entities
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"


def get_context():
    """
    Return P4 context.

    :return: context object
    """
    return CONTEXT


def get_client():
    """
    Return P4 client.

    :return: P4Runtime client object
    """
    return CLIENT


def get_api_version():
    """
    Get the supported P4Runtime API version.

    :return: API version
    """
    return CLIENT.api_version()


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:
        if m_f.match_type == p4info_pb2.MatchField.EXACT:
            return p4info_pb2.MatchField.EXACT
        if m_f.match_type == p4info_pb2.MatchField.LPM:
            return p4info_pb2.MatchField.LPM
        if m_f.match_type == p4info_pb2.MatchField.TERNARY:
            return p4info_pb2.MatchField.TERNARY
        if m_f.match_type == p4info_pb2.MatchField.RANGE:
            return p4info_pb2.MatchField.RANGE
        if m_f.match_type == p4info_pb2.MatchField.OPTIONAL:
            return p4info_pb2.MatchField.OPTIONAL
    return None


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


def insert_table_entry_exact(
        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(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 P4RuntimeWriteException as ex:
        ex_msg = str(ex)
    except P4RuntimeException as ex:
        raise P4RuntimeException from 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)

    return table_entry


def insert_table_entry_ternary(
        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(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

    table_entry.priority = priority

    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 P4RuntimeWriteException as ex:
        ex_msg = str(ex)
    except P4RuntimeException as ex:
        raise P4RuntimeException from 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)

    return table_entry


def insert_table_entry_range(
        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(
        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")


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):
        global CLIENT

        self.__id = device_id
        self.__ip_address = ip_address
        self.__port = int(port)
        self.__endpoint = f"{self.__ip_address}:{self.__port}"
        CLIENT = P4RuntimeClient(
            self.__id, self.__endpoint, election_id, role_name, ssl_options)
        self.__p4info = None

        # Internal memory for whitebox management
        # | -> P4 entities
        self.p4_objects = {}

        # | -> P4 entities
        self.table_entries = {}
        self.counter_entries = {}
        self.direct_counter_entries = {}
        self.meter_entries = {}
        self.direct_meter_entries = {}
        self.multicast_groups = {}
        self.clone_session_entries = {}
        self.action_profile_members = {}
        self.action_profile_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:
                CLIENT.set_fwd_pipe_config(p4info_path, p4bin_path)
            except FileNotFoundError as ex:
                LOGGER.critical(ex)
                CLIENT.tear_down()
                raise FileNotFoundError(ex) from ex
            except P4RuntimeException as ex:
                LOGGER.critical("Error when setting config")
                LOGGER.critical(ex)
                CLIENT.tear_down()
                raise P4RuntimeException(ex) from ex
            except Exception as ex:  # pylint: disable=broad-except
                LOGGER.critical("Error when setting config")
                CLIENT.tear_down()
                raise Exception(ex) from ex

        try:
            self.__p4info = CLIENT.get_p4info()
        except P4RuntimeException as ex:
            LOGGER.critical("Error when retrieving P4Info")
            LOGGER.critical(ex)
            CLIENT.tear_down()
            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
        """
        global CLIENT

        # gRPC client must already be instantiated
        assert CLIENT

        # Trigger connection tear down with the P4Runtime server
        CLIENT.tear_down()
        CLIENT = None
        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.__endpoint = None
        self.__clear_state()

    def __clear_state(self):
        """
        Reset the manager's internal memory.

        :return: void
        """
        self.table_entries.clear()
        self.counter_entries.clear()
        self.direct_counter_entries.clear()
        self.meter_entries.clear()
        self.direct_meter_entries.clear()
        self.multicast_groups.clear()
        self.clone_session_entries.clear()
        self.action_profile_members.clear()
        self.action_profile_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_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
        assert (k for k in [
            KEY_TABLE, KEY_ACTION, KEY_ACTION_PROFILE,
            KEY_COUNTER, KEY_DIR_COUNTER,
            KEY_METER, KEY_DIR_METER,
            KEY_CTL_PKT_METADATA
        ])

        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_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] = []

        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] = []

    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_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:
            for count, table_entry in enumerate(
                    TableEntry(table_name)(action=action_name).read()):
                LOGGER.debug(
                    "Table %s - Entry %d\n%s", table_name, count, table_entry)
                self.table_entries[table_name].append(table_entry)
            return self.table_entries[table_name]
        except P4RuntimeException as ex:
            LOGGER.error(ex)
            return []

    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
        """
        entries = self.get_table_entries(table_name, action_name)
        if entries is None:
            return -1
        return len(entries)

    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.debug("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.debug("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(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

        if not get_table_type(table):
            msg = f"Table {table_name} is undefined, cannot insert entry"
            LOGGER.error(msg)
            raise UserError(msg)

        # Exact match is supported
        if get_table_type(table) == p4info_pb2.MatchField.EXACT:
            if priority != 0:
                msg = f"Table {table_name} is non-ternary, priority must be 0"
                LOGGER.error(msg)
                raise UserError(msg)
            return insert_table_entry_exact(
                table_name, match_map, action_name, action_params, metadata,
                cnt_pkt, cnt_byte)

        # Ternary and LPM matches are supported
        if get_table_type(table) in \
                [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)
            return 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 get_table_type(table) == p4info_pb2.MatchField.RANGE:
            return 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 get_table_type(table) == p4info_pb2.MatchField.OPTIONAL:
            return 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

        if not get_table_type(table):
            msg = f"Table {table_name} is undefined, cannot delete entry"
            LOGGER.error(msg)
            raise UserError(msg)

        table_entry = TableEntry(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 get_table_type(table) == p4info_pb2.MatchField.EXACT:
            if priority != 0:
                msg = f"Table {table_name} is non-ternary, priority must be 0"
                LOGGER.error(msg)
                raise UserError(msg)

        if get_table_type(table) in \
                [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
        if get_table_type(table) in \
                [p4info_pb2.MatchField.RANGE, p4info_pb2.MatchField.OPTIONAL]:
            raise NotImplementedError(
                "Range and optional-based table deletion not implemented yet")

        table_entry.priority = priority

        table_entry.delete()
        LOGGER.info("Deleted entry %s from table: %s", table_entry, table_name)

        return table_entry

    def delete_table_entries(self, table_name):
        """
        Delete all entries of a P4 table.

        :param table_name: name of a P4 table
        :return: void
        """
        table = self.get_table(table_name)
        assert table, \
            "P4 pipeline does not implement table " + table_name

        if not get_table_type(table):
            msg = f"Table {table_name} is undefined, cannot delete entry"
            LOGGER.error(msg)
            raise UserError(msg)

        TableEntry(table_name).read(function=lambda x: x.delete())