def add(address, timeout, key, auth_type, port, pri, use_mgmt_vrf): """Specify a TACACS+ server""" if not is_ipaddress(address): click.echo('Invalid ip address') return config_db = ConfigDBConnector() config_db.connect() old_data = config_db.get_entry('TACPLUS_SERVER', address) if old_data != {}: click.echo('server %s already exists' % address) else: data = { 'tcp_port': str(port), 'priority': pri } if auth_type is not None: data['auth_type'] = auth_type if timeout is not None: data['timeout'] = str(timeout) if key is not None: data['passkey'] = key if use_mgmt_vrf : data['vrf'] = "mgmt" config_db.set_entry('TACPLUS_SERVER', address, data)
def load_minigraph(): """Reconfigure based on minigraph.""" log_info("'load_minigraph' executing...") #Stop services before config push _stop_services() 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 = "{} -H -m -j /etc/sonic/init_cfg.json --write-to-db".format(SONIC_CFGGEN_PATH) else: command = "{} -H -m --write-to-db".format(SONIC_CFGGEN_PATH) run_command(command, display_cmd=True) client.set(config_db.INIT_INDICATOR, 1) run_command('pfcwd start_default', display_cmd=True) if os.path.isfile('/etc/sonic/acl.json'): run_command("acl-loader update full /etc/sonic/acl.json", display_cmd=True) run_command("config qos reload", display_cmd=True) # Write latest db version string into db db_migrator='/usr/bin/db_migrator.py' if os.path.isfile(db_migrator) and os.access(db_migrator, os.X_OK): run_command(db_migrator + ' -o set_version') #FIXME: After config DB daemon is implemented, we'll no longer need to restart every service. _restart_services() click.echo("Please note setting loaded from minigraph will be lost after system reboot. To preserve setting, run `config save`.")
def remove(session_name): """ Delete mirror session """ config_db = ConfigDBConnector() config_db.connect() config_db.set_entry("MIRROR_SESSION", session_name, None)
def _is_neighbor_ipaddress(ipaddress): """Returns True if a neighbor has the IP address <ipaddress>, False if not """ config_db = ConfigDBConnector() config_db.connect() entry = config_db.get_entry('BGP_NEIGHBOR', ipaddress) return True if entry else False
def del_table_key(table, entry, key): config_db = ConfigDBConnector() config_db.connect() data = config_db.get_entry(table, entry) if data: if key in data: del data[key] config_db.set_entry(table, entry, data)
def delete(address): """Delete a TACACS+ server""" if not is_ipaddress(address): click.echo('Invalid ip address') return config_db = ConfigDBConnector() config_db.connect() config_db.set_entry('TACPLUS_SERVER', address, None)
def _change_bgp_session_status_by_addr(ipaddress, status, verbose): """Start up or shut down BGP session by IP address """ verb = 'Starting' if status == 'up' else 'Shutting' click.echo("{} {} BGP session with neighbor {}...".format(verb, status, ipaddress)) config_db = ConfigDBConnector() config_db.connect() config_db.mod_entry('bgp_neighbor', ipaddress, {'admin_status': status})
def vlan(ctx, redis_unix_socket_path): """VLAN-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) ctx.obj = {'db': config_db} pass
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)
class Db(object): def __init__(self): self.cfgdb = ConfigDBConnector() self.cfgdb.connect() self.db = SonicV2Connector(host="127.0.0.1") self.db.connect(self.db.APPL_DB) self.db.connect(self.db.CONFIG_DB) self.db.connect(self.db.STATE_DB) def get_data(self, table, key): data = self.cfgdb.get_table(table) return data[key] if key in data else None
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
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']))
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)
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
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()
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
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)
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))
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))
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
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
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
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 ""
class DBSyncDaemon(SonicSyncDaemon): """ A Thread that listens to changes in CONFIG DB, and contains handlers to configure lldpd accordingly. """ def __init__(self): super(DBSyncDaemon, self).__init__() self.config_db = ConfigDBConnector() self.config_db.connect() logger.info("[lldp dbsyncd] Connected to configdb") self.port_table = {} def run_command(self, command): p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) stdout = p.communicate()[0] p.wait() if p.returncode != 0: logger.error("[lldp dbsyncd] command execution returned {}. " "Command: '{}', stdout: '{}'".format(p.returncode, command, stdout)) def port_handler(self, key, data): """ Handle updates in 'PORT' table. """ # we're interested only in description for now if self.port_table[key].get("description") != data.get("description"): new_descr = data.get("description", " ") logger.info("[lldp dbsyncd] Port {} description changed to {}." .format(key, new_descr)) self.run_command("lldpcli configure lldp portidsubtype local {} description '{}'" .format(key, new_descr)) # update local cache self.port_table[key] = data def run(self): self.port_table = self.config_db.get_table('PORT') # supply LLDP_LOC_ENTRY_TABLE and lldpd with correct values on start for port_name, attributes in self.port_table.items(): self.run_command("lldpcli configure lldp portidsubtype local {} description '{}'" .format(port_name, attributes.get("description", " "))) # subscribe for further changes self.config_db.subscribe('PORT', lambda table, key, data: self.port_handler(key, data)) logger.info("[lldp dbsyncd] Subscribed to configdb PORT table") self.config_db.listen()
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 ""
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
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")
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
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 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()
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 port_dict.keys(): if interface_alias == port_dict[port_name]['alias']: return port_name # Interface alias not in port_dict, just return interface_alias return interface_alias
def create(session_name, src_ip, dst_ip, gre_type, dscp, ttl, queue): """ Create mirror session. """ configdb = ConfigDBConnector() configdb.connect() session_info = { "src_ip": src_ip, "dst_ip": dst_ip, "gre_type": gre_type, "dscp": dscp, "ttl": ttl, "queue": queue } configdb.set_entry("MIRROR_SESSION", session_name, session_info)
def snmptrap (ctx): """Show SNMP agent Trap server configuration""" config_db = ConfigDBConnector() config_db.connect() traptable = config_db.get_table('SNMP_TRAP_CONFIG') header = ['Version', 'TrapReceiverIP', 'Port', 'VRF', 'Community'] body = [] for row in traptable: if row == "v1TrapDest": ver=1 elif row == "v2TrapDest": ver=2 else: ver=3 body.append([ver, traptable[row]['DestIp'], traptable[row]['DestPort'], traptable[row]['vrf'], traptable[row]['Community']]) click.echo(tabulate(body, header))
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
def set_interface_naming_mode(mode): """Modify SONIC_CLI_IFACE_MODE env variable in user .bashrc """ user = os.getenv('SUDO_USER') bashrc_ifacemode_line = "export SONIC_CLI_IFACE_MODE={}".format(mode) # Ensure all interfaces have an 'alias' key in PORT dict config_db = ConfigDBConnector() config_db.connect() port_dict = config_db.get_table('PORT') if not port_dict: click.echo("port_dict is None!") raise click.Abort() for port_name in port_dict.keys(): try: if port_dict[port_name]['alias']: pass except KeyError: click.echo("Platform does not support alias mapping") raise click.Abort() if not user: user = os.getenv('USER') if user != "root": bashrc = "/home/{}/.bashrc".format(user) else: click.get_current_context().fail( "Cannot set interface naming mode for root user!") f = open(bashrc, 'r') filedata = f.read() f.close() if "SONIC_CLI_IFACE_MODE" not in filedata: newdata = filedata + bashrc_ifacemode_line newdata += "\n" else: newdata = re.sub(r"export SONIC_CLI_IFACE_MODE=\w+", bashrc_ifacemode_line, filedata) f = open(bashrc, 'w') f.write(newdata) f.close() click.echo("Please logout and log back in for changes take effect.")
def reload(filename, yes, load_sysinfo): """Clear current configuration and import a previous saved config DB dump file.""" if not yes: click.confirm( 'Clear current config and reload config from the file %s?' % filename, abort=True) log_info("'reload' executing...") if load_sysinfo: command = "{} -j {} -v DEVICE_METADATA.localhost.hwsku".format( SONIC_CFGGEN_PATH, filename) proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) cfg_hwsku, err = proc.communicate() if err: click.echo("Could not get the HWSKU from config file, exiting") sys.exit(1) else: cfg_hwsku = cfg_hwsku.strip() #Stop services before config push _stop_services() config_db = ConfigDBConnector() config_db.connect() client = config_db.redis_clients[config_db.CONFIG_DB] client.flushdb() if load_sysinfo: command = "{} -H -k {} --write-to-db".format(SONIC_CFGGEN_PATH, cfg_hwsku) run_command(command, display_cmd=True) command = "{} -j {} --write-to-db".format(SONIC_CFGGEN_PATH, filename) run_command(command, display_cmd=True) client.set(config_db.INIT_INDICATOR, 1) # Migrate DB contents to latest version db_migrator = '/usr/bin/db_migrator.py' if os.path.isfile(db_migrator) and os.access(db_migrator, os.X_OK): run_command(db_migrator + ' -o migrate') # We first run "systemctl reset-failed" to remove the "failed" # status from all services before we attempt to restart them _reset_failed_services() _restart_services()
def interface(): """Show VXLAN VTEP Information""" config_db = ConfigDBConnector() config_db.connect() # Fetching VTEP keys from config DB click.secho('VTEP Information:\n', bold=True, underline=True) vxlan_table = config_db.get_table('VXLAN_TUNNEL') vxlan_keys = vxlan_table.keys() vtep_sip = '0.0.0.0' if vxlan_keys is not None: for key in natsorted(vxlan_keys): key1 = key.split('|',1) vtepname = key1.pop(); if 'src_ip' in vxlan_table[key]: vtep_sip = vxlan_table[key]['src_ip'] if vtep_sip is not '0.0.0.0': output = '\tVTEP Name : ' + vtepname + ', SIP : ' + vxlan_table[key]['src_ip'] else: output = '\tVTEP Name : ' + vtepname click.echo(output) if vtep_sip is not '0.0.0.0': vxlan_table = config_db.get_table('VXLAN_EVPN_NVO') vxlan_keys = vxlan_table.keys() if vxlan_keys is not None: for key in natsorted(vxlan_keys): key1 = key.split('|',1) vtepname = key1.pop(); output = '\tNVO Name : ' + vtepname + ', VTEP : ' + vxlan_table[key]['source_vtep'] click.echo(output) vxlan_keys = config_db.keys('CONFIG_DB', "LOOPBACK_INTERFACE|*") loopback = 'Not Configured' if vxlan_keys is not None: for key in natsorted(vxlan_keys): key1 = key.split('|',2) if len(key1) == 3 and key1[2] == vtep_sip+'/32': loopback = key1[1] break output = '\tSource interface : ' + loopback if vtep_sip != '0.0.0.0': click.echo(output)
def set_interface_naming_mode(mode): """Modify SONIC_CLI_IFACE_MODE env variable in user .bashrc """ user = os.getenv('SUDO_USER') bashrc_ifacemode_line = "export SONIC_CLI_IFACE_MODE={}".format(mode) # Ensure all interfaces have an 'alias' key in PORT dict config_db = ConfigDBConnector() config_db.connect() port_dict = config_db.get_table('PORT') if not port_dict: click.echo("port_dict is None!") raise click.Abort() for port_name in port_dict.keys(): try: if port_dict[port_name]['alias']: pass except KeyError: click.echo("Platform does not support alias mapping") raise click.Abort() if not user: user = os.getenv('USER') if user != "root": bashrc = "/home/{}/.bashrc".format(user) else: click.get_current_context().fail("Cannot set interface naming mode for root user!") f = open(bashrc, 'r') filedata = f.read() f.close() if "SONIC_CLI_IFACE_MODE" not in filedata: newdata = filedata + bashrc_ifacemode_line newdata += "\n" else: newdata = re.sub(r"export SONIC_CLI_IFACE_MODE=\w+", bashrc_ifacemode_line, filedata) f = open(bashrc, 'w') f.write(newdata) f.close() click.echo("Please logout and log back in for changes take effect.")
def db_connect_configdb(): """ Connect to configdb """ config_db = ConfigDBConnector() if config_db is None: return None try: """ This could be blocking during the config load_minigraph phase, as the CONFIG_DB_INITIALIZED is not yet set in the configDB. We can ignore the check by using config_db.db_connect('CONFIG_DB') instead """ # Connect only if available & initialized config_db.connect(wait_for_init=False) except Exception as e: config_db = None return config_db
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)
def add(session_name, src_ip, dst_ip, dscp, ttl, gre_type, queue): """ Add mirror session """ config_db = ConfigDBConnector() config_db.connect() session_info = { "src_ip": src_ip, "dst_ip": dst_ip, "dscp": dscp, "ttl": ttl } if gre_type is not None: session_info['gre_type'] = gre_type if queue is not None: session_info['queue'] = queue config_db.set_entry("MIRROR_SESSION", session_name, session_info)
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') port_channel_dict = config_db.get_table('PORTCHANNEL') if get_interface_naming_mode() == "alias": interface_name = interface_alias_to_name(interface_name) 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 if port_channel_dict: for port_channel_name in port_channel_dict.keys(): if interface_name == port_channel_name: return True return False
def reload(filename, yes, load_sysinfo): """Clear current configuration and import a previous saved config DB dump file.""" if not yes: click.confirm('Clear current config and reload config from the file %s?' % filename, abort=True) log_info("'reload' executing...") if load_sysinfo: command = "{} -j {} -v DEVICE_METADATA.localhost.hwsku".format(SONIC_CFGGEN_PATH, filename) proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) cfg_hwsku, err = proc.communicate() if err: click.echo("Could not get the HWSKU from config file, exiting") sys.exit(1) else: cfg_hwsku = cfg_hwsku.strip() #Stop services before config push _stop_services() config_db = ConfigDBConnector() config_db.connect() client = config_db.redis_clients[config_db.CONFIG_DB] client.flushdb() if load_sysinfo: command = "{} -H -k {} --write-to-db".format(SONIC_CFGGEN_PATH, cfg_hwsku) run_command(command, display_cmd=True) command = "{} -j {} --write-to-db".format(SONIC_CFGGEN_PATH, filename) run_command(command, display_cmd=True) client.set(config_db.INIT_INDICATOR, 1) # Migrate DB contents to latest version db_migrator='/usr/bin/db_migrator.py' if os.path.isfile(db_migrator) and os.access(db_migrator, os.X_OK): run_command(db_migrator + ' -o migrate') _restart_services()
def add_table_kv(table, entry, key, val): config_db = ConfigDBConnector() config_db.connect() config_db.mod_entry(table, entry, {key:val})
def _get_all_neighbor_ipaddresses(): """Returns list of strings containing IP addresses of all BGP neighbors """ config_db = ConfigDBConnector() config_db.connect() return config_db.get_table('BGP_NEIGHBOR').keys()
def _get_hwsku(): config_db = ConfigDBConnector() config_db.connect() metadata = config_db.get_table('DEVICE_METADATA') return metadata['localhost']['hwsku']
def portchannel(ctx): config_db = ConfigDBConnector() config_db.connect() ctx.obj = {'db': config_db} pass
def interface(ctx): """Interface-related configuration tasks""" config_db = ConfigDBConnector() config_db.connect() ctx.obj = {} ctx.obj['config_db'] = config_db