Esempio n. 1
0
def extract_RJ45_ports_index():
    # Cross check 'platform.json' and 'hwsku.json' to extract the RJ45 port index if exists.
    hwsku_path = device_info.get_path_to_hwsku_dir()
    platform_file = device_info.get_path_to_port_config_file()
    platform_dict = load_json_file(platform_file)['interfaces']
    hwsku_file = os.path.join(hwsku_path, HWSKU_JSON)
    hwsku_dict = load_json_file(hwsku_file)['interfaces']
    port_name_to_index_map_dict = {}
    RJ45_port_index_list = []

    # Compose a interface name to index mapping from 'platform.json'
    for i, (key, value) in enumerate(platform_dict.items()):
        if PORT_INDEX_KEY in value:
            index_raw = value[PORT_INDEX_KEY]
            # The index could be "1" or "1, 1, 1, 1"
            index = index_raw.split(',')[0]
            port_name_to_index_map_dict[key] = index

    if not bool(port_name_to_index_map_dict):
        return None

    # Check if "port_type" specified as "RJ45", if yes, add the port index to the list.
    for i, (key, value) in enumerate(hwsku_dict.items()):
        if key in port_name_to_index_map_dict and PORT_TYPE_KEY in value and value[
                PORT_TYPE_KEY] == RJ45_PORT_TYPE:
            RJ45_port_index_list.append(
                int(port_name_to_index_map_dict[key]) - 1)

    return RJ45_port_index_list if bool(RJ45_port_index_list) else None
Esempio n. 2
0
def get_port_config(hwsku=None, platform=None, port_config_file=None, hwsku_config_file=None, asic=None):
    config_db = db_connect_configdb()
    # If available, Read from CONFIG DB first
    if config_db is not None and port_config_file is None:

        port_data = config_db.get_table("PORT")
        if bool(port_data):
            ports = ast.literal_eval(json.dumps(port_data))
            port_alias_map = {}
            port_alias_asic_map = {}
            for intf_name in ports.keys():
                port_alias_map[ports[intf_name]["alias"]] = intf_name
            return (ports, port_alias_map, port_alias_asic_map)

    if not port_config_file:
        port_config_file = device_info.get_path_to_port_config_file(hwsku, asic)
        if not port_config_file:
            return ({}, {}, {})


    # Read from 'platform.json' file
    if port_config_file.endswith('.json'):
        if not hwsku_config_file:
             hwsku_json_file = get_hwsku_file_name(hwsku, platform)
             if not hwsku_json_file:
                return ({}, {}, {})
        else:
            hwsku_json_file = hwsku_config_file

        return parse_platform_json_file(hwsku_json_file, port_config_file)

    # If 'platform.json' file is not available, read from 'port_config.ini'
    else:
        return parse_port_config_file(port_config_file)
Esempio n. 3
0
def cli():
    """sfputil - Command line utility for managing SFP transceivers"""

    if os.geteuid() != 0:
        click.echo("Root privileges are required for this operation")
        sys.exit(1)

    # Load platform-specific sfputil class
    err = load_platform_sfputil()
    if err != 0:
        sys.exit(2)

    # Load port info
    try:
        if multi_asic.is_multi_asic():
            # For multi ASIC platforms we pass DIR of port_config_file_path and the number of asics
            (platform_path,
             hwsku_path) = device_info.get_paths_to_platform_and_hwsku_dirs()

            # Load platform module from source
            platform_sfputil.read_all_porttab_mappings(
                hwsku_path, multi_asic.get_num_asics())
        else:
            # For single ASIC platforms we pass port_config_file_path and the asic_inst as 0
            port_config_file_path = device_info.get_path_to_port_config_file()
            platform_sfputil.read_porttab_mappings(port_config_file_path, 0)
    except Exception as e:
        log.log_error("Error reading port info (%s)" % str(e), True)
        sys.exit(3)
Esempio n. 4
0
def platform_sfputil_read_porttab_mappings():
    global platform_porttab_mapping_read

    if platform_porttab_mapping_read:
        return 0

    try:

        if multi_asic.is_multi_asic():
            # For multi ASIC platforms we pass DIR of port_config_file_path and the number of asics
            (platform_path,
             hwsku_path) = device_info.get_paths_to_platform_and_hwsku_dirs()

            # Load platform module from source
            platform_sfputil.read_all_porttab_mappings(
                hwsku_path, multi_asic.get_num_asics())
        else:
            # For single ASIC platforms we pass port_config_file_path and the asic_inst as 0
            port_config_file_path = device_info.get_path_to_port_config_file()
            platform_sfputil.read_porttab_mappings(port_config_file_path, 0)

        platform_porttab_mapping_read = True
    except Exception as e:
        click.echo("Error reading port info (%s)" % str(e))
        sys.exit(1)

    return 0
Esempio n. 5
0
def breakout(ctx):
    """Show Breakout Mode information by interfaces"""
    # Reading data from Redis configDb
    config_db = ConfigDBConnector()
    config_db.connect()
    ctx.obj = {'db': config_db}

    try:
        cur_brkout_tbl = config_db.get_table('BREAKOUT_CFG')
    except Exception as e:
        click.echo("Breakout table is not present in Config DB")
        raise click.Abort()

    if ctx.invoked_subcommand is None:
        # Get port capability from platform and hwsku related files
        hwsku_path = device_info.get_path_to_hwsku_dir()
        platform_file = device_info.get_path_to_port_config_file()
        platform_dict = readJsonFile(platform_file)['interfaces']
        hwsku_file = os.path.join(hwsku_path, HWSKU_JSON)
        hwsku_dict = readJsonFile(hwsku_file)['interfaces']

        if not platform_dict or not hwsku_dict:
            click.echo("Can not load port config from {} or {} file".format(
                platform_file, hwsku_file))
            raise click.Abort()

        for port_name in platform_dict:
            cur_brkout_mode = cur_brkout_tbl[port_name]["brkout_mode"]

            # Update deafult breakout mode and current breakout mode to platform_dict
            platform_dict[port_name].update(hwsku_dict[port_name])
            platform_dict[port_name]["Current Breakout Mode"] = cur_brkout_mode

            # List all the child ports if present
            child_port_dict = get_child_ports(port_name, cur_brkout_mode,
                                              platform_file)
            if not child_port_dict:
                click.echo(
                    "Cannot find ports from {} file ".format(platform_file))
                raise click.Abort()

            child_ports = natsorted(list(child_port_dict.keys()))

            children, speeds = [], []
            # Update portname and speed of child ports if present
            for port in child_ports:
                speed = config_db.get_entry('PORT', port).get('speed')
                if speed is not None:
                    speeds.append(str(int(speed) // 1000) + 'G')
                    children.append(port)

            platform_dict[port_name]["child ports"] = ",".join(children)
            platform_dict[port_name]["child port speeds"] = ",".join(speeds)

        # Sorted keys by name in natural sort Order for human readability
        parsed = OrderedDict((k, platform_dict[k])
                             for k in natsorted(list(platform_dict.keys())))
        click.echo(json.dumps(parsed, indent=4))
Esempio n. 6
0
    def __initialize_sfp(self):
        sfputil_helper = SfpUtilHelper()
        port_config_file_path = device_info.get_path_to_port_config_file()
        sfputil_helper.read_porttab_mappings(port_config_file_path, 0)

        from .sfp import Sfp
        for index in range(0, NUM_SFP):
            sfp = Sfp(index, sfputil_helper.logical[index])
            self._sfp_list.append(sfp)
        self.sfp_module_initialized = True
def get_breakout_mode(hwsku=None, platform=None, port_config_file=None):
    if not port_config_file:
        port_config_file = device_info.get_path_to_port_config_file(hwsku)
        if not port_config_file:
            return None
    if port_config_file.endswith('.json'):
        hwsku_json_file = get_hwsku_file_name(hwsku, platform)
        if not hwsku_json_file:
            raise Exception("'hwsku_json' file does not exist!!! This file is necessary to proceed forward.")

        return parse_breakout_mode(hwsku_json_file)
    else:
        return None
Esempio n. 8
0
def load_port_config():
    try:
        if multi_asic.is_multi_asic():
            # For multi ASIC platforms we pass DIR of port_config_file_path and the number of asics
            (platform_path, hwsku_path) = device_info.get_paths_to_platform_and_hwsku_dirs()

            # Load platform module from source
            platform_sfputil.read_all_porttab_mappings(hwsku_path, multi_asic.get_num_asics())
        else:
            # For single ASIC platforms we pass port_config_file_path and the asic_inst as 0
            port_config_file_path = device_info.get_path_to_port_config_file()
            platform_sfputil.read_porttab_mappings(port_config_file_path, 0)
    except Exception as e:
        log.log_error("Error reading port info ({})".format(str(e)), True)
        return False

    return True
Esempio n. 9
0
def cli():
    """sfputil - Command line utility for managing SFP transceivers"""

    if os.geteuid() != 0:
        click.echo("Root privileges are required for this operation")
        sys.exit(1)

    # Load platform-specific sfputil class
    err = load_platform_sfputil()
    if err != 0:
        sys.exit(2)

    # Load port info
    try:
        port_config_file_path = device_info.get_path_to_port_config_file()
        platform_sfputil.read_porttab_mappings(port_config_file_path)
    except Exception as e:
        log.log_error("Error reading port info (%s)" % str(e), True)
        sys.exit(3)
Esempio n. 10
0
    def init(self):
        global platform_sfputil
        global platform_chassis

        self.log_info("Start daemon init...")
        config_db, metadata_tbl, metadata_dict = {}, {}, {}
        is_vs = False

        namespaces = multi_asic.get_front_end_namespaces()
        for namespace in namespaces:
            asic_id = multi_asic.get_asic_index_from_namespace(namespace)
            config_db[asic_id] = daemon_base.db_connect("CONFIG_DB", namespace)
            metadata_tbl[asic_id] = swsscommon.Table(config_db[asic_id],
                                                     "DEVICE_METADATA")

        (status, fvs) = metadata_tbl[0].get("localhost")

        if status is False:
            helper_logger.log_debug(
                "Could not retreive fieldvalue pairs for {}, inside config_db table {}"
                .format('localhost', metadata_tbl[0].getTableName()))
            return

        else:
            # Convert list of tuples to a dictionary
            metadata_dict = dict(fvs)
            if "platform" in metadata_dict:
                val = metadata_dict.get("platform", None)
                if val == "x86_64-kvm_x86_64-r0":
                    is_vs = True

        # Load new platform api class
        try:
            if is_vs is False:
                import sonic_platform.platform
                platform_chassis = sonic_platform.platform.Platform(
                ).get_chassis()
                self.log_info("chassis loaded {}".format(platform_chassis))
            # we have to make use of sfputil for some features
            # even though when new platform api is used for all vendors.
            # in this sense, we treat it as a part of new platform api.
            # we have already moved sfputil to sonic_platform_base
            # which is the root of new platform api.
            import sonic_platform_base.sonic_sfp.sfputilhelper
            platform_sfputil = sonic_platform_base.sonic_sfp.sfputilhelper.SfpUtilHelper(
            )
        except Exception as e:
            self.log_warning("Failed to load chassis due to {}".format(
                repr(e)))

        # Load platform specific sfputil class
        if platform_chassis is None or platform_sfputil is None:
            if is_vs is False:
                try:
                    platform_sfputil = self.load_platform_util(
                        PLATFORM_SPECIFIC_MODULE_NAME,
                        PLATFORM_SPECIFIC_CLASS_NAME)
                except Exception as e:
                    self.log_error("Failed to load sfputil: {}".format(str(e)),
                                   True)
                    sys.exit(SFPUTIL_LOAD_ERROR)

        if multi_asic.is_multi_asic():
            # Load the namespace details first from the database_global.json file.
            swsscommon.SonicDBConfig.initializeGlobalConfig()

        # Load port info
        try:
            if multi_asic.is_multi_asic():
                # For multi ASIC platforms we pass DIR of port_config_file_path and the number of asics
                (platform_path, hwsku_path
                 ) = device_info.get_paths_to_platform_and_hwsku_dirs()
                platform_sfputil.read_all_porttab_mappings(
                    hwsku_path, self.num_asics)
            else:
                # For single ASIC platforms we pass port_config_file_path and the asic_inst as 0
                port_config_file_path = device_info.get_path_to_port_config_file(
                )
                platform_sfputil.read_porttab_mappings(port_config_file_path,
                                                       0)
        except Exception as e:
            self.log_error("Failed to read port info: {}".format(str(e)), True)
            sys.exit(PORT_CONFIG_LOAD_ERROR)

        # Connect to STATE_DB and create ycable tables
        state_db = {}

        # Get the namespaces in the platform
        namespaces = multi_asic.get_front_end_namespaces()
        for namespace in namespaces:
            asic_id = multi_asic.get_asic_index_from_namespace(namespace)
            state_db[asic_id] = daemon_base.db_connect("STATE_DB", namespace)
        """
        # TODO need to decide if we need warm start capability in this ycabled daemon
        warmstart = swsscommon.WarmStart()
        warmstart.initialize("ycabled", "pmon")
        warmstart.checkWarmStart("ycabled", "pmon", False)
        is_warm_start = warmstart.isWarmStart()
        """

        # Make sure this daemon started after all port configured
        self.log_info("Wait for port config is done")

        # Init port y_cable status table
        y_cable_helper.init_ports_status_for_y_cable(platform_sfputil,
                                                     platform_chassis,
                                                     self.y_cable_presence,
                                                     self.stop_event, is_vs)
Esempio n. 11
0
#!/usr/bin/env python
# This script runs on the DUT and is intended to retrieve the portmapping from logical interfaces to physical ones
# The way the port mapping retrieved is exactly the same as what xcvrd does

import json

import sonic_platform_base.sonic_sfp.sfputilhelper
from sonic_py_common import device_info

# load and parse the port configuration file on DUT
port_config_path = device_info.get_path_to_port_config_file()
platform_sfputil = sonic_platform_base.sonic_sfp.sfputilhelper.SfpUtilHelper()
platform_sfputil.read_porttab_mappings(port_config_path)

# print the mapping to stdout in json format
print json.dumps(platform_sfputil.logical_to_physical)

# json will be loaded by sonic-mgmt