def disable(): """ Disable rif counter query """ configdb = ConfigDBConnector() configdb.connect() rif_info = {} rif_info['FLEX_COUNTER_STATUS'] = 'disable' configdb.mod_entry("FLEX_COUNTER_TABLE", "RIF", rif_info)
def disable(): """ Disable port counter query """ configdb = ConfigDBConnector() configdb.connect() port_info = {} port_info['FLEX_COUNTER_STATUS'] = DISABLE configdb.mod_entry("FLEX_COUNTER_TABLE", PORT_BUFFER_DROP, port_info)
def tacacs(): """Show TACACS+ configuration""" config_db = ConfigDBConnector() config_db.connect() output = '' data = config_db.get_table('TACPLUS') tacplus = { 'global': { 'auth_type': 'pap (default)', 'timeout': '5 (default)', 'passkey': '<EMPTY_STRING> (default)' } } if 'global' in data: tacplus['global'].update(data['global']) for key in tacplus['global']: output += ('TACPLUS global %s %s\n' % (str(key), str(tacplus['global'][key]))) data = config_db.get_table('TACPLUS_SERVER') if data != {}: for row in data: entry = data[row] output += ('\nTACPLUS_SERVER address %s\n' % row) for key in entry: output += (' %s %s\n' % (key, str(entry[key]))) click.echo(output)
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_2_0_3' 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') if namespace is None: self.appDB = ConfigDBConnector(**db_kwargs) else: self.appDB = ConfigDBConnector(use_unix_socket_path=True, namespace=namespace, **db_kwargs) self.appDB.db_connect('APPL_DB') self.stateDB = SonicV2Connector(host='127.0.0.1') if self.stateDB is not None: self.stateDB.connect(self.stateDB.STATE_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)
def remove_bindings(ctx): """Remove all Bindings for Dynamic configutation""" config_db = ConfigDBConnector() config_db.connect() binding_table_name = 'NAT_BINDINGS' binding_dict = config_db.get_table(binding_table_name) if binding_dict: for binding_key_name in binding_dict: config_db.set_entry(binding_table_name, binding_key_name, None)
def show_thresholds(self, resource): """ CRM Handler to display thresholds information. """ configdb = self.cfgdb if configdb is None: # Get the namespace list namespaces = multi_asic.get_namespace_list() configdb = ConfigDBConnector(namespace=namespaces[0]) configdb.connect() crm_info = configdb.get_entry('CRM', 'Config') header = ("Resource Name", "Threshold Type", "Low Threshold", "High Threshold") data = [] if crm_info: if resource == 'all': for res in ["ipv4_route", "ipv6_route", "ipv4_nexthop", "ipv6_nexthop", "ipv4_neighbor", "ipv6_neighbor", "nexthop_group_member", "nexthop_group", "acl_table", "acl_group", "acl_entry", "acl_counter", "fdb_entry", "ipmc_entry", "snat_entry", "dnat_entry", "mpls_inseg", "mpls_nexthop","srv6_nexthop", "srv6_my_sid_entry"]: try: data.append([res, crm_info[res + "_threshold_type"], crm_info[res + "_low_threshold"], crm_info[res + "_high_threshold"]]) except KeyError: pass else: try: data.append([resource, crm_info[resource + "_threshold_type"], crm_info[resource + "_low_threshold"], crm_info[resource + "_high_threshold"]]) except KeyError: pass else: click.echo('\nError! Could not get CRM configuration.') click.echo() click.echo(tabulate(data, headers=header, tablefmt="simple", missingval="")) click.echo()
def vrf(vrf_name): """Show vrf config""" config_db = ConfigDBConnector() config_db.connect() header = ['VRF', 'Interfaces'] body = [] vrf_dict = config_db.get_table('VRF') if vrf_dict: vrfs = [] if vrf_name is None: vrfs = list(vrf_dict.keys()) elif vrf_name in vrf_dict: vrfs = [vrf_name] for vrf in vrfs: intfs = get_interface_bind_to_vrf(config_db, vrf) if len(intfs) == 0: body.append([vrf, ""]) else: body.append([vrf, intfs[0]]) for intf in intfs[1:]: body.append(["", intf]) click.echo(tabulate(body, header))
def brief(): """Show vnet brief information""" config_db = ConfigDBConnector() config_db.connect() header = ['vnet name', 'vxlan tunnel', 'vni', 'peer list'] # Fetching data from config_db for VNET vnet_data = config_db.get_table('VNET') vnet_keys = natsorted(list(vnet_data.keys())) def tablelize(vnet_keys, vnet_data): table = [] for k in vnet_keys: r = [] r.append(k) r.append(vnet_data[k].get('vxlan_tunnel')) r.append(vnet_data[k].get('vni')) r.append(vnet_data[k].get('peer_list')) table.append(r) return table click.echo(tabulate(tablelize(vnet_keys, vnet_data), header))
def interval(poll_interval): """ Set rif counter query interval """ configdb = ConfigDBConnector() configdb.connect() rif_info = {} if poll_interval is not None: rif_info['POLL_INTERVAL'] = poll_interval configdb.mod_entry("FLEX_COUNTER_TABLE", "RIF", rif_info)
def interval(poll_interval): """ Set queue counter query interval """ configdb = ConfigDBConnector() configdb.connect() port_info = {} if poll_interval is not None: port_info['POLL_INTERVAL'] = poll_interval configdb.mod_entry("FLEX_COUNTER_TABLE", "PORT", port_info)
def configPfcAsym(interface, pfc_asym): """ PFC handler to configure asymmentric PFC. """ configdb = ConfigDBConnector() configdb.connect() configdb.mod_entry("PORT", interface, {'pfc_asym': pfc_asym})
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))
class Db(object): def __init__(self): self.cfgdb_clients = {} self.db_clients = {} self.cfgdb = ConfigDBConnector() self.cfgdb.connect() self.db = SonicV2Connector(host="127.0.0.1") for db_id in self.db.get_db_list(): self.db.connect(db_id) self.cfgdb_clients[constants.DEFAULT_NAMESPACE] = self.cfgdb self.db_clients[constants.DEFAULT_NAMESPACE] = self.db if multi_asic.is_multi_asic(): self.ns_list = multi_asic_ns_choices() for ns in self.ns_list: self.cfgdb_clients[ns] = ( multi_asic.connect_config_db_for_ns(ns)) self.db_clients[ns] = multi_asic.connect_to_all_dbs_for_ns(ns) def get_data(self, table, key): data = self.cfgdb.get_table(table) return data[key] if key in data else None
def readConfigDB(self): ''' Read the config in Config DB. Assign it in self.configdbJsonIn. Parameters: (void) Returns: (void) ''' self.sysLog(doPrint=True, msg='Reading data from Redis configDb') # Read from config DB on sonic switch data = dict() configdb = ConfigDBConnector() configdb.connect() sonic_cfggen.deep_update( data, sonic_cfggen.FormatConverter.db_to_output(configdb.get_config())) self.configdbJsonIn = sonic_cfggen.FormatConverter.to_serialized(data) self.sysLog(syslog.LOG_DEBUG, 'Reading Input from ConfigDB {}'.\ format(self.configdbJsonIn)) return
def show_summary(self): """ CRM Handler to display general information. """ configdb = self.cfgdb if configdb is None: # Get the namespace list namespaces = multi_asic.get_namespace_list() configdb = ConfigDBConnector(namespace=namespaces[0]) configdb.connect() crm_info = configdb.get_entry('CRM', 'Config') if crm_info: try: click.echo('\nPolling Interval: ' + crm_info['polling_interval'] + ' second(s)\n') except KeyError: click.echo('\nError! Could not get CRM configuration.\n') click.echo('\nError! Please configure polling interval.\n') else: click.echo('\nError! Could not get CRM configuration.\n')
def delete(address): """Delete a TACACS+ server""" if not clicommon.is_ipaddress(address): click.echo('Invalid ip address') return config_db = ConfigDBConnector() config_db.connect() config_db.set_entry('TACPLUS_SERVER', address, None)
def neighbors(): """Show vnet neighbors information""" config_db = ConfigDBConnector() config_db.connect() header = ['<vnet_name>', 'neighbor', 'mac_address', 'interfaces'] # Fetching data from config_db for interfaces intfs_data = config_db.get_table("INTERFACE") vlan_intfs_data = config_db.get_table("VLAN_INTERFACE") vnet_intfs = {} for k, v in intfs_data.items(): if 'vnet_name' in v: vnet_name = v['vnet_name'] if vnet_name in vnet_intfs: vnet_intfs[vnet_name].append(k) else: vnet_intfs[vnet_name] = [k] for k, v in vlan_intfs_data.items(): if 'vnet_name' in v: vnet_name = v['vnet_name'] if vnet_name in vnet_intfs: vnet_intfs[vnet_name].append(k) else: vnet_intfs[vnet_name] = [k] appl_db = SonicV2Connector() appl_db.connect(appl_db.APPL_DB) # Fetching data from appl_db for neighbors nbrs = appl_db.keys(appl_db.APPL_DB, "NEIGH_TABLE:*") nbrs_data = {} for nbr in nbrs if nbrs else []: tbl, intf, ip = nbr.split(":", 2) mac = appl_db.get(appl_db.APPL_DB, nbr, 'neigh') if intf in nbrs_data: nbrs_data[intf].append((ip, mac)) else: nbrs_data[intf] = [(ip, mac)] table = [] for k, v in vnet_intfs.items(): v = natsorted(v) header[0] = k table = [] for intf in v: if intf in nbrs_data: for ip, mac in nbrs_data[intf]: r = ["", ip, mac, intf] table.append(r) click.echo(tabulate(table, header)) click.echo() if not bool(vnet_intfs): click.echo(tabulate(table, header))
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: config_db.set_entry(table_name, table_key_name, None)
def __connect_to_redis(self): '''! Establishes connection to the redis DB @return False - If connection to the redis DB failed True - If connection to the redis DB is successful ''' # Connect to ConfigDB try: if self.configDB is None: self.configDB = ConfigDBConnector() self.configDB.connect() except: self.configDB = None return False # Connect to AppDB try: if self.applDB is None: self.applDB = SonicV2Connector() self.applDB.connect(self.applDB.APPL_DB) except: self.applDB = None return False return True
def getTwiceNatIdCountWithStaticEntries(twice_nat_id, table, count): """Get the twice nat id count with static entries""" config_db = ConfigDBConnector() config_db.connect() static_dict = config_db.get_table(table) twice_id_count = count if not static_dict: return twice_id_count for key, values in static_dict.items(): twice_id = 0 if "twice_nat_id" in values: twice_id = int(values["twice_nat_id"]) else: continue if twice_id == twice_nat_id: twice_id_count += 1 return twice_id_count
def test_ConfigDBFlush(): config_db = ConfigDBConnector() config_db.connect(wait_for_init=False) config_db.set_entry("TEST_PORT", "Ethernet111", {"alias": "etp1x"}) client = config_db.get_redis_client(config_db.CONFIG_DB) assert ConfigDBConnector.INIT_INDICATOR == "CONFIG_DB_INITIALIZED" assert config_db.INIT_INDICATOR == "CONFIG_DB_INITIALIZED" suc = client.set(config_db.INIT_INDICATOR, 1) assert suc # TODO: redis.get is not yet supported # indicator = client.get(config_db.INIT_INDICATOR) # assert indicator == '1' client.flushdb() allconfig = config_db.get_config() assert len(allconfig) == 0
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 test_ConfigDBScan(): config_db = ConfigDBPipeConnector() config_db.connect(wait_for_init=False) n = 1000 for i in range(0, n): s = str(i) config_db.mod_entry("TEST_TYPE" + s, "Ethernet" + s, {"alias" + s: "etp" + s}) allconfig = config_db.get_config() assert len(allconfig) == n config_db = ConfigDBConnector() config_db.connect(wait_for_init=False) allconfig = config_db.get_config() assert len(allconfig) == n for i in range(0, n): s = str(i) config_db.delete_table("TEST_TYPE" + s)
def interval(poll_interval): """ Set port_buffer_drop counter query interval This counter group causes high CPU usage when polled, hence the allowed interval is between 30s and 300s. This is a short term solution and should be changed once the performance is enhanced """ configdb = ConfigDBConnector() configdb.connect() port_info = {} if poll_interval: port_info['POLL_INTERVAL'] = poll_interval configdb.mod_entry("FLEX_COUNTER_TABLE", PORT_BUFFER_DROP, port_info)
def add(address, retransmit, timeout, key, auth_type, auth_port, pri, use_mgmt_vrf, source_interface): """Specify a RADIUS server""" if key: if len(key) > RADIUS_PASSKEY_MAX_LEN: click.echo('--key: Maximum of %d chars can be configured' % RADIUS_PASSKEY_MAX_LEN) return elif not is_secret(key): click.echo('--key: ' + VALID_CHARS_MSG) return config_db = ConfigDBConnector() config_db.connect() old_data = config_db.get_table('RADIUS_SERVER') if address in old_data: click.echo('server %s already exists' % address) return if len(old_data) == RADIUS_MAXSERVERS: click.echo('Maximum of %d can be configured' % RADIUS_MAXSERVERS) else: data = {'auth_port': str(auth_port), 'priority': pri} if auth_type is not None: data['auth_type'] = auth_type if retransmit is not None: data['retransmit'] = str(retransmit) if timeout is not None: data['timeout'] = str(timeout) if key is not None: data['passkey'] = key if use_mgmt_vrf: data['vrf'] = "mgmt" if source_interface: if (source_interface.startswith("Ethernet") or \ source_interface.startswith("PortChannel") or \ source_interface.startswith("Vlan") or \ source_interface.startswith("Loopback") or \ source_interface == "eth0"): data['src_intf'] = source_interface else: click.echo( 'Not supported interface name (valid interface name: Etherent<id>/PortChannel<id>/Vlan<id>/Loopback<id>/eth0)' ) config_db.set_entry('RADIUS_SERVER', address, data)
def remove_interfaces(ctx): """Remove all interface related NAT configuration""" config_db = ConfigDBConnector() config_db.connect() tables = [ 'INTERFACE', 'PORTCHANNEL_INTERFACE', 'VLAN_INTERFACE', 'LOOPBACK_INTERFACE' ] nat_config = {"nat_zone": "0"} for table_name in tables: table_dict = config_db.get_table(table_name) if table_dict: for table_key_name in table_dict: if isinstance(table_key_name, str) is False: continue config_db.set_entry(table_name, table_key_name, nat_config)
def remove_pools(ctx): """Remove all Pools for Dynamic configutation""" config_db = ConfigDBConnector() config_db.connect() entryFound = False pool_table_name = 'NAT_POOL' binding_table_name = 'NAT_BINDINGS' binding_dict = config_db.get_table(binding_table_name) pool_dict = config_db.get_table(pool_table_name) if pool_dict: for pool_key_name in pool_dict: entryFound = False for binding_name, binding_values in binding_dict.items(): if binding_values['nat_pool'] == pool_key_name: click.echo( "Pool {} is not removed, as it is mapped to Binding {}, remove the pool binding first !!" .format(pool_key_name, binding_name)) entryFound = True break if entryFound == False: config_db.set_entry(pool_table_name, pool_key_name, None)
def add(address, timeout, key, auth_type, port, pri, use_mgmt_vrf): """Specify a TACACS+ server""" if not clicommon.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 remove_binding(ctx, binding_name): """Remove Binding for Dynamic NAT-related configutation""" entryFound = False table = 'NAT_BINDINGS' key = binding_name if len(binding_name) > 32: ctx.fail( "Invalid binding name. Maximum allowed binding name is 32 characters !!" ) config_db = ConfigDBConnector() config_db.connect() data = config_db.get_entry(table, key) if not data: click.echo("Trying to delete binding, which is not present.") entryFound = True if entryFound == False: config_db.set_entry(table, key, None)
def writeConfigDB(self, jDiff): ''' Write the diff in Config DB. Parameters: jDiff (dict): config to push in config DB. Returns: void ''' self.sysLog(doPrint=True, msg='Writing in Config DB') data = dict() configdb = ConfigDBConnector() configdb.connect(False) deep_update(data, FormatConverter.to_deserialized(jDiff)) self.sysLog(msg="Write in DB: {}".format(data)) configdb.mod_config(FormatConverter.output_to_db(data)) return