|
| 1 | +""" |
| 2 | +Bridge/Port mapping utility library. |
| 3 | +""" |
| 4 | +import swsssdk |
| 5 | +import re |
| 6 | + |
| 7 | +SONIC_ETHERNET_RE_PATTERN = "^Ethernet(\d+)$" |
| 8 | +SONIC_PORTCHANNEL_RE_PATTERN = "^PortChannel(\d+)$" |
| 9 | + |
| 10 | +def get_index(if_name): |
| 11 | + """ |
| 12 | + OIDs are 1-based, interfaces are 0-based, return the 1-based index |
| 13 | + Ethernet N = N + 1 |
| 14 | + PortChannel N = N + 1000 |
| 15 | + """ |
| 16 | + return get_index_from_str(if_name.decode()) |
| 17 | + |
| 18 | + |
| 19 | +def get_index_from_str(if_name): |
| 20 | + """ |
| 21 | + OIDs are 1-based, interfaces are 0-based, return the 1-based index |
| 22 | + Ethernet N = N + 1 |
| 23 | + PortChannel N = N + 1000 |
| 24 | + """ |
| 25 | + patterns = { |
| 26 | + SONIC_ETHERNET_RE_PATTERN: 1, |
| 27 | + SONIC_PORTCHANNEL_RE_PATTERN: 1000 |
| 28 | + } |
| 29 | + |
| 30 | + for pattern, baseidx in patterns.items(): |
| 31 | + match = re.match(pattern, if_name) |
| 32 | + if match: |
| 33 | + return int(match.group(1)) + baseidx |
| 34 | + |
| 35 | +def get_interface_oid_map(db): |
| 36 | + """ |
| 37 | + Get the Interface names from Counters DB |
| 38 | + """ |
| 39 | + db.connect('COUNTERS_DB') |
| 40 | + if_name_map = db.get_all('COUNTERS_DB', 'COUNTERS_PORT_NAME_MAP', blocking=True) |
| 41 | + if_id_map = {sai_oid: if_name for if_name, sai_oid in if_name_map.items() |
| 42 | + # only map the interface if it's a style understood to be a SONiC interface. |
| 43 | + if get_index(if_name) is not None} |
| 44 | + |
| 45 | + return if_name_map, if_id_map |
| 46 | + |
| 47 | +def get_bridge_port_map(db): |
| 48 | + """ |
| 49 | + Get the Bridge port mapping from ASIC DB |
| 50 | + """ |
| 51 | + db.connect('ASIC_DB') |
| 52 | + if_br_oid_map = {} |
| 53 | + br_port_str = db.keys('ASIC_DB', "ASIC_STATE:SAI_OBJECT_TYPE_BRIDGE_PORT:*") |
| 54 | + if not br_port_str: |
| 55 | + return |
| 56 | + |
| 57 | + offset = len("ASIC_STATE:SAI_OBJECT_TYPE_BRIDGE_PORT:") |
| 58 | + oid_pfx = len("oid:0x") |
| 59 | + for br_s in br_port_str: |
| 60 | + # Example output: ASIC_STATE:SAI_OBJECT_TYPE_BRIDGE_PORT:oid:0x3a000000000616 |
| 61 | + br_port_id = br_s[(offset + oid_pfx):] |
| 62 | + ent = db.get_all('ASIC_DB', br_s, blocking=True) |
| 63 | + if b"SAI_BRIDGE_PORT_ATTR_PORT_ID" in ent: |
| 64 | + port_id = ent[b"SAI_BRIDGE_PORT_ATTR_PORT_ID"][oid_pfx:] |
| 65 | + if_br_oid_map[br_port_id] = port_id |
| 66 | + |
| 67 | + return if_br_oid_map |
| 68 | + |
0 commit comments