Exemplo n.º 1
0
def interface(ctx, interface_name):
    """Interface-related configuration tasks"""
    config_db = ConfigDBConnector()
    config_db.connect()
    ctx.obj = {}
    ctx.obj['config_db'] = config_db
    if get_interface_naming_mode() == "alias":
        ctx.obj['interface_name'] = interface_alias_to_name(interface_name)
        if ctx.obj['interface_name'] is None:
            ctx.fail("'interface_name' is None!")
    else:
        ctx.obj['interface_name'] = interface_name
Exemplo n.º 2
0
def _clear_qos():
    QOS_TABLE_NAMES = [
        'TC_TO_PRIORITY_GROUP_MAP', 'MAP_PFC_PRIORITY_TO_QUEUE',
        'TC_TO_QUEUE_MAP', 'DSCP_TO_TC_MAP', 'SCHEDULER',
        'PFC_PRIORITY_TO_PRIORITY_GROUP_MAP', 'PORT_QOS_MAP', 'WRED_PROFILE',
        'QUEUE', 'CABLE_LENGTH', 'BUFFER_POOL', 'BUFFER_PROFILE', 'BUFFER_PG',
        'BUFFER_QUEUE'
    ]
    config_db = ConfigDBConnector()
    config_db.connect()
    for qos_table in QOS_TABLE_NAMES:
        config_db.delete_table(qos_table)
Exemplo n.º 3
0
def address():
    """Show IP address configured for management interface"""

    config_db = ConfigDBConnector()
    config_db.connect()

    # Fetching data from config_db for MGMT_INTERFACE
    mgmt_ip_data = config_db.get_table('MGMT_INTERFACE')
    for key in natsorted(list(mgmt_ip_data.keys())):
        click.echo("Management IP address = {0}".format(key[1]))
        click.echo("Management Network Default Gateway = {0}".format(
            mgmt_ip_data[key]['gwaddr']))
Exemplo n.º 4
0
def getConnectionInfo(linenum):
    config_db = ConfigDBConnector()
    config_db.connect()
    entry = config_db.get_entry(CONSOLE_PORT_TABLE, str(linenum))

    conf_baud = "-" if BAUD_KEY not in entry else entry[BAUD_KEY]
    act_baud = DEFAULT_BAUD if conf_baud == "-" else conf_baud
    flow_control = False
    if FLOW_KEY in entry and entry[FLOW_KEY] == "1":
        flow_control = True

    return (act_baud, conf_baud, flow_control)
 def __init__(self):
     self.config_db = ConfigDBConnector()
     self.config_db.connect()
     self.state_db = SonicV2Connector()
     self.state_db.connect(STATE_DB)
     self._portchannel_intfs = None
     self.up_portchannels = None
     self.netlink_api = IPRoute()
     self.sniffer = None
     self.self_ip = ''
     self.packet_filter = ''
     self.sniff_intfs = []
Exemplo n.º 6
0
def _get_neighbor_ipaddress_list_by_hostname(hostname):
    """Returns list of strings, each containing an IP address of neighbor with
       hostname <hostname>. Returns empty list if <hostname> not a neighbor
    """
    addrs = []
    config_db = ConfigDBConnector()
    config_db.connect()
    bgp_sessions = config_db.get_table('BGP_NEIGHBOR')
    for addr, session in bgp_sessions.iteritems():
        if session.has_key('name') and session['name'] == hostname:
            addrs.append(addr)
    return addrs
Exemplo n.º 7
0
def reload(filename):
    """Clear current configuration and import a previous saved config DB dump file."""
    #Stop services before config push
    _stop_services()
    config_db = ConfigDBConnector()
    config_db.connect()
    client = config_db.redis_clients[config_db.CONFIG_DB]
    client.flushdb()
    command = "{} -j {} --write-to-db".format(SONIC_CFGGEN_PATH, filename)
    run_command(command, display_cmd=True)
    client.set(config_db.INIT_INDICATOR, 1)
    _restart_services()
Exemplo n.º 8
0
    def __init__(self):
        self.yang_acl = None
        self.requested_session = None
        self.tables_db_info = {}
        self.rules_db_info = {}
        self.rules_info = {}
        self.sessions_db_info = {}
        self.configdb = ConfigDBConnector()
        self.configdb.connect()

        self.read_tables_info()
        self.read_rules_info()
        self.read_sessions_info()
Exemplo n.º 9
0
def get_localhost_info(field):
    try:
        config_db = ConfigDBConnector()
        config_db.connect()

        metadata = config_db.get_table('DEVICE_METADATA')

        if 'localhost' in metadata and field in metadata['localhost']:
            return metadata['localhost'][field]
    except Exception:
        pass

    return None
Exemplo n.º 10
0
def get_routes():
    db = ConfigDBConnector()
    db.db_connect('APPL_DB')
    print_message(syslog.LOG_DEBUG, "APPL DB connected for routes")
    keys = db.get_keys('ROUTE_TABLE')

    valid_rt = []
    for k in keys:
        if not is_local(k):
            valid_rt.append(add_prefix_ifnot(k.lower()))

    print_message(syslog.LOG_DEBUG, json.dumps({"ROUTE_TABLE": sorted(valid_rt)}, indent=4))
    return sorted(valid_rt)
Exemplo n.º 11
0
def get_route_entries():
    db = ConfigDBConnector()
    db.db_connect('ASIC_DB')
    print_message(syslog.LOG_DEBUG, "ASIC DB connected")
    keys = db.get_keys('ASIC_STATE:SAI_OBJECT_TYPE_ROUTE_ENTRY', False)

    rt = []
    for k in keys:
        e = k.lower().split("\"", -1)[3]
        if not is_local(e):
            rt.append(e)
    print_message(syslog.LOG_DEBUG, json.dumps({"ASIC_ROUTE_ENTRY": sorted(rt)}, indent=4))
    return sorted(rt)
Exemplo n.º 12
0
    def __init__(self, namespace, socket=None):
        """
        Version string format:
           version_<major>_<minor>_<build>
              major: starting from 1, sequentially incrementing in master
                     branch.
              minor: in github branches, minor version stays in 0. This minor
                     version creates space for private branches derived from
                     github public branches. These private branches shall use
                     none-zero values.
              build: sequentially increase within a minor version domain.
        """
        self.CURRENT_VERSION = 'version_1_0_4'

        self.TABLE_NAME      = 'VERSIONS'
        self.TABLE_KEY       = 'DATABASE'
        self.TABLE_FIELD     = 'VERSION'

        db_kwargs = {}
        if socket:
            db_kwargs['unix_socket_path'] = socket

        if namespace is None:
            self.configDB = ConfigDBConnector(**db_kwargs)
        else:
            self.configDB = ConfigDBConnector(use_unix_socket_path=True, namespace=namespace, **db_kwargs)
        self.configDB.db_connect('CONFIG_DB')

        self.appDB = SonicV2Connector(host='127.0.0.1')
        if self.appDB is not None:
            self.appDB.connect(self.appDB.APPL_DB)

        version_info = device_info.get_sonic_version_info()
        asic_type = version_info.get('asic_type')
        self.asic_type = asic_type

        if asic_type == "mellanox":
            from mellanox_buffer_migrator import MellanoxBufferMigrator
            self.mellanox_buffer_migrator = MellanoxBufferMigrator(self.configDB)
Exemplo n.º 13
0
def remove_static_all(ctx):
    """Remove all Static related configutation"""

    config_db = ConfigDBConnector()
    config_db.connect()

    tables = ['STATIC_NAT', 'STATIC_NAPT']

    for table_name in tables:
        table_dict = config_db.get_table(table_name)
        if table_dict:
            for table_key_name in table_dict.keys():
                config_db.set_entry(table_name, table_key_name, None)
Exemplo n.º 14
0
def memory():
    """Show kdump memory information"""
    kdump_memory = "0M-2G:256M,2G-4G:320M,4G-8G:384M,8G-:448M"
    config_db = ConfigDBConnector()
    if config_db is not None:
        config_db.connect()
        table_data = config_db.get_table('KDUMP')
        if table_data is not None:
            config_data = table_data.get('config')
            if config_data is not None:
                kdump_memory_from_db = config_data.get('memory')
                if kdump_memory_from_db is not None:
                    kdump_memory = kdump_memory_from_db
    click.echo("Memory Reserved: {}".format(kdump_memory))
Exemplo n.º 15
0
def getLineNumber(target, deviceBool):
    if not deviceBool:
        return target

    config_db = ConfigDBConnector()
    config_db.connect()

    devices = getAllDevices()
    for device in devices:
        if DEVICE_KEY in device and device[DEVICE_KEY] == target:
            return device[LINE_KEY]

    click.echo("Device {} does not exist".format(target))
    sys.exit(ERR_DEV)
    return ""
Exemplo n.º 16
0
def get_localhost_info(field, config_db=None):
    try:
        # TODO: enforce caller to provide config_db explicitly and remove its default value
        if not config_db:
            config_db = ConfigDBConnector()
            config_db.connect()

        metadata = config_db.get_table('DEVICE_METADATA')

        if 'localhost' in metadata and field in metadata['localhost']:
            return metadata['localhost'][field]
    except Exception:
        pass

    return None
Exemplo n.º 17
0
def interface_name_is_valid(interface_name):
    """Check if the interface name is valid
    """
    config_db = ConfigDBConnector()
    config_db.connect()
    port_dict = config_db.get_table('PORT')

    if interface_name is not None:
        if not port_dict:
            click.echo("port_dict is None!")
            raise click.Abort()
        for port_name in port_dict.keys():
            if interface_name == port_name:
                return True
    return False
Exemplo n.º 18
0
def warm_restart(ctx, redis_unix_socket_path):
    """warm_restart-related configuration tasks"""
    kwargs = {}
    if redis_unix_socket_path:
        kwargs['unix_socket_path'] = redis_unix_socket_path
    config_db = ConfigDBConnector(**kwargs)
    config_db.connect(wait_for_init=False)

    # warm restart enable/disable config is put in stateDB, not persistent across cold reboot, not saved to config_DB.json file
    state_db = SonicV2Connector(host='127.0.0.1')
    state_db.connect(state_db.STATE_DB, False)
    TABLE_NAME_SEPARATOR = '|'
    prefix = 'WARM_RESTART_ENABLE_TABLE' + TABLE_NAME_SEPARATOR
    ctx.obj = {'db': config_db, 'state_db': state_db, 'prefix': prefix}
    pass
Exemplo n.º 19
0
    def __init__(self):
        self.yang_acl = None
        self.requested_session = None
        self.tables_db_info = {}
        self.rules_db_info = {}
        self.rules_info = {}
        self.sessions_db_info = {}
        self.configdb = ConfigDBConnector()
        self.configdb.connect()
        self.appdb = SonicV2Connector(host="127.0.0.1")
        self.appdb.connect(self.appdb.APPL_DB)

        self.read_tables_info()
        self.read_rules_info()
        self.read_sessions_info()
Exemplo n.º 20
0
def num_dumps():
    """Show kdump max number of dump files"""
    kdump_num_dumps = "3"
    config_db = ConfigDBConnector()
    if config_db is not None:
        config_db.connect()
        table_data = config_db.get_table('KDUMP')
        if table_data is not None:
            config_data = table_data.get('config')
            if config_data is not None:
                kdump_num_dumps_from_db = config_data.get('num_dumps')
                if kdump_num_dumps_from_db is not None:
                    kdump_num_dumps = kdump_num_dumps_from_db
    click.echo("Maximum number of Kernel Core files Stored: {}".format(
        kdump_num_dumps))
Exemplo n.º 21
0
def filter_out_local_interfaces(keys):
    rt = []
    local_if = set(['eth0', 'lo', 'docker0'])

    db = ConfigDBConnector()
    db.db_connect('APPL_DB')

    for k in keys:
        e = db.get_entry('ROUTE_TABLE', k)
        if not e:
            # Prefix might have been added. So try w/o it.
            e = db.get_entry('ROUTE_TABLE', k.split("/")[0])
        if not e or (e['ifname'] not in local_if):
            rt.append(k)

    return rt
Exemplo n.º 22
0
def get_hwsku():
    """
    Retrieve the device's hardware SKU identifier

    Returns:
        A string containing the device's hardware SKU identifier
    """
    config_db = ConfigDBConnector()
    config_db.connect()

    metadata = config_db.get_table('DEVICE_METADATA')

    if 'localhost' in metadata and 'hwsku' in metadata['localhost']:
        return metadata['localhost']['hwsku']

    return ""
Exemplo n.º 23
0
def enabled():
    """Show if kdump is enabled or disabled"""
    kdump_is_enabled = False
    config_db = ConfigDBConnector()
    if config_db is not None:
        config_db.connect()
        table_data = config_db.get_table('KDUMP')
        if table_data is not None:
            config_data = table_data.get('config')
            if config_data is not None:
                if config_data.get('enabled').lower() == 'true':
                    kdump_is_enabled = True
    if kdump_is_enabled:
        click.echo("kdump is enabled")
    else:
        click.echo("kdump is disabled")
Exemplo n.º 24
0
def interface_name_to_alias(interface_name):
    """Return alias interface name if default name is given as argument
    """
    config_db = ConfigDBConnector()
    config_db.connect()
    port_dict = config_db.get_table('PORT')

    if interface_name is not None:
        if not port_dict:
            click.echo("port_dict is None!")
            raise click.Abort()
        for port_name in port_dict.keys():
            if interface_name == port_name:
                return port_dict[port_name]['alias']

    return None
Exemplo n.º 25
0
def connect_config_db_for_ns(namespace=DEFAULT_NAMESPACE):
    """
    The function connects to the config DB for a given namespace and
    returns the handle
    If no namespace is provided, it will connect to the db in the
    default namespace.
    In case of multi ASIC, the default namespace is the database
    instance running the on the host

    Returns:
      handle to the config_db for a namespace
    """
    SonicDBConfig.load_sonic_global_db_config()
    config_db = ConfigDBConnector(namespace=namespace)
    config_db.connect()
    return config_db
Exemplo n.º 26
0
def load_minigraph():
    """Reconfigure based on minigraph."""
    config_db = ConfigDBConnector()
    config_db.connect()
    client = config_db.redis_clients[config_db.CONFIG_DB]
    client.flushdb()
    if os.path.isfile('/etc/sonic/init_cfg.json'):
        command = "{} -m -j /etc/sonic/init_cfg.json --write-to-db".format(
            SONIC_CFGGEN_PATH)
    else:
        command = "{} -m --write-to-db".format(SONIC_CFGGEN_PATH)
    run_command(command, display_cmd=True)
    client.set(config_db.INIT_INDICATOR, True)
    #FIXME: After config DB daemon is implemented, we'll no longer need to restart every service.
    _restart_services()
    print "Please note setting loaded from minigraph will be lost after system reboot. To preserve setting, run `config save`."
def get_tam_int_ifa_ts_supported(args):
    api_response = {}

    # connect to APPL_DB
    app_db = ConfigDBConnector()
    app_db.db_connect('APPL_DB')

    key = 'SWITCH_TABLE:switch'
    data = app_db.get(app_db.APPL_DB, key, 'tam_int_ifa_ts_supported')

    if data and data == 'True':
        api_response['feature'] = data
    else:
        api_response['feature'] = 'False'

    show_cli_output("show_tam_ifa_ts_feature_supported.j2", api_response)
Exemplo n.º 28
0
def reload(filename):
    """Clear current configuration and import a previous saved config DB dump file."""
    config_db = ConfigDBConnector()
    config_db.connect()
    client = config_db.redis_clients[config_db.CONFIG_DB]
    client.flushdb()
    command = "{} -j {} --write-to-db".format(SONIC_CFGGEN_PATH, filename)
    run_command(command, display_cmd=True)
    client.set(config_db.INIT_INDICATOR, True)
    command = "{} -j {} -v \"DEVICE_METADATA['localhost']['hostname']\"".format(
        SONIC_CFGGEN_PATH, filename)
    p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
    p.wait()
    hostname = p.communicate()[0].strip()
    _change_hostname(hostname)
    _restart_services()
Exemplo n.º 29
0
def interface_alias_to_name(interface_alias):
    """Return default interface name if alias name is given as argument
    """
    config_db = ConfigDBConnector()
    config_db.connect()
    port_dict = config_db.get_table('PORT')

    if interface_alias is not None:
        if not port_dict:
            click.echo("port_dict is None!")
            raise click.Abort()
        for port_name in natsorted(port_dict.keys()):
            if interface_alias == port_dict[port_name]['alias']:
                return port_name
        click.echo("Invalid interface {}".format(interface_alias))

    return None
Exemplo n.º 30
0
def update_dhcp_mgmt_ip_info():
    app_db = ConfigDBConnector()
    app_db.db_connect('APPL_DB', wait_for_init=False, retry_on=True)
    appdb_entry = {}
    appdb_entry["NULL"] = "NULL"

    op = sys.argv[2]
    plen = ipaddress.ip_network((0, sys.argv[4])).prefixlen
    key = sys.argv[1] + ":" + sys.argv[3] + "/" + str(plen)
    syslog.syslog(
        syslog.LOG_INFO,
        "update_dhcp_mgmt_ip_info : op -  {}, key - {}".format(op, key))
    if op == "add":
        app_db.set_entry(APP_MGMT_INTF_TABLE, key, appdb_entry)
    elif op == "del":
        app_db.delete_entry(APP_MGMT_INTF_TABLE, key)
    return