_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q18500
Nipap._parse_vrf_query
train
def _parse_vrf_query(self, query_str): """ Parse a smart search query for VRFs This is a helper function to smart_search_vrf for easier unit testing of the parser. """
python
{ "resource": "" }
q18501
Nipap.add_pool
train
def add_pool(self, auth, attr): """ Create a pool according to `attr`. * `auth` [BaseAuth] AAA options. * `attr` [pool_attr] A dict containing the attributes the new pool should have. Returns a dict describing the pool which was added. This is the documentation of the internal backend function. It's exposed over XML-RPC, please also see the XML-RPC documentation for :py:func:`nipap.xmlrpc.NipapXMLRPC.add_pool` for full understanding. """ self._logger.debug("add_pool called; attrs: %s" % unicode(attr))
python
{ "resource": "" }
q18502
Nipap.list_pool
train
def list_pool(self, auth, spec=None): """ Return a list of pools. * `auth` [BaseAuth] AAA options. * `spec` [pool_spec] Specifies what pool(s) to list. Of omitted, all will be listed. Returns a list of dicts. This is the documentation of the internal backend function. It's exposed over XML-RPC, please also see the XML-RPC documentation for :py:func:`nipap.xmlrpc.NipapXMLRPC.list_pool` for full understanding. """ if spec is None: spec = {} self._logger.debug("list_pool called; spec: %s" % unicode(spec)) sql = """SELECT DISTINCT (po.id), po.id, po.name, po.description, po.default_type, po.ipv4_default_prefix_length, po.ipv6_default_prefix_length, po.member_prefixes_v4, po.member_prefixes_v6, po.used_prefixes_v4, po.used_prefixes_v6, po.free_prefixes_v4, po.free_prefixes_v6, po.total_prefixes_v4, po.total_prefixes_v6, po.total_addresses_v4, po.total_addresses_v6, po.used_addresses_v4, po.used_addresses_v6, po.free_addresses_v4,
python
{ "resource": "" }
q18503
Nipap._check_pool_attr
train
def _check_pool_attr(self, attr, req_attr=None): """ Check pool attributes. """ if req_attr is None: req_attr = [] # check attribute names self._check_attr(attr, req_attr, _pool_attrs) # validate IPv4 prefix length if attr.get('ipv4_default_prefix_length') is not None: try: attr['ipv4_default_prefix_length'] = \ int(attr['ipv4_default_prefix_length']) if (attr['ipv4_default_prefix_length'] > 32 or
python
{ "resource": "" }
q18504
Nipap._get_pool
train
def _get_pool(self, auth, spec): """ Get a pool. Shorthand function to reduce code in the functions below, since more or less all of them needs to perform the actions that are specified here. The major difference to :func:`list_pool` is that an exception
python
{ "resource": "" }
q18505
Nipap.edit_pool
train
def edit_pool(self, auth, spec, attr): """ Update pool given by `spec` with attributes `attr`. * `auth` [BaseAuth] AAA options. * `spec` [pool_spec] Specifies what pool to edit. * `attr` [pool_attr] Attributes to update and their new values. This is the documentation of the internal backend function. It's exposed over XML-RPC, please also see the XML-RPC documentation for :py:func:`nipap.xmlrpc.NipapXMLRPC.edit_pool` for full understanding. """ self._logger.debug("edit_pool called; spec: %s attr: %s" % (unicode(spec), unicode(attr))) if ('id' not in spec and 'name' not in spec) or ( 'id' in spec and 'name' in spec ): raise NipapMissingInputError('''pool spec must contain either 'id' or 'name' ''') self._check_pool_attr(attr) where, params1 = self._expand_pool_spec(spec) update, params2 = self._sql_expand_update(attr) params = dict(params2.items() + params1.items()) pools = self.list_pool(auth, spec) sql = "UPDATE ip_net_pool SET " + update sql += " FROM ip_net_pool AS po WHERE ip_net_pool.id = po.id AND " + where sql += " RETURNING po.id AS id" self._execute(sql, params) updated_pools =
python
{ "resource": "" }
q18506
Nipap.smart_search_pool
train
def smart_search_pool(self, auth, query_str, search_options=None, extra_query=None): """ Perform a smart search on pool list. * `auth` [BaseAuth] AAA options. * `query_str` [string] Search string * `search_options` [options_dict] Search options. See :func:`search_pool`. * `extra_query` [dict_to_sql] Extra search terms, will be AND:ed together with what is extracted from the query string. Return a dict with three elements: * :attr:`interpretation` - How the query string was interpreted. * :attr:`search_options` - Various search_options. * :attr:`result` - The search result. The :attr:`interpretation` is given as a list of dicts, each explaining how a part of the search key was interpreted (ie. what pool attribute the search operation was performed on). The :attr:`result` is a list of dicts containing the search result. The smart search function tries to convert the query from a text
python
{ "resource": "" }
q18507
Nipap._parse_pool_query
train
def _parse_pool_query(self, query_str): """ Parse a smart search query for pools This is a helper function to smart_search_pool for easier unit testing of the parser. """
python
{ "resource": "" }
q18508
Nipap._expand_prefix_spec
train
def _expand_prefix_spec(self, spec, prefix = ''): """ Expand prefix specification to SQL. """ # sanity checks if type(spec) is not dict: raise NipapInputError('invalid prefix specification') for key in spec.keys(): if key not in _prefix_spec: raise NipapExtraneousInputError("Key '" + key + "' not allowed in prefix spec.") where = "" params = {} # if we have id, no other input is needed if 'id' in spec: if spec != {'id': spec['id']}: raise NipapExtraneousInputError("If 'id' specified, no other keys are allowed.") family = None if 'family' in spec: family = spec['family'] del(spec['family']) # rename prefix columns spec2 = {} for k in spec: spec2[prefix + k] = spec[k] spec = spec2 # handle keys which refer to external keys if prefix + 'vrf_id' in spec: # "translate" vrf id None to id = 0 if spec[prefix + 'vrf_id'] is None: spec[prefix + 'vrf_id'] = 0 if prefix + 'vrf_name' in spec:
python
{ "resource": "" }
q18509
Nipap._expand_prefix_query
train
def _expand_prefix_query(self, query, table_name = None): """ Expand prefix query dict into a WHERE-clause. If you need to prefix each column reference with a table name, that can be supplied via the table_name argument. """ where = unicode() opt = list() # handle table name, can be None if table_name is None: col_prefix = "" else: col_prefix = table_name + "." if 'val1' not in query: raise NipapMissingInputError("'val1' must be specified") if 'val2' not in query: raise NipapMissingInputError("'val2' must be specified") if type(query['val1']) == dict and type(query['val2']) == dict: # Sub expression, recurse! This is used for boolean operators: AND OR # add parantheses sub_where1, opt1 = self._expand_prefix_query(query['val1'], table_name) sub_where2, opt2 = self._expand_prefix_query(query['val2'], table_name) try: where += unicode(" (%s %s %s) " % (sub_where1, _operation_map[query['operator']], sub_where2) ) except KeyError: raise NipapNoSuchOperatorError("No such operator %s" % unicode(query['operator'])) opt += opt1 opt += opt2 else: # TODO: raise exception if someone passes one dict and one "something else"? # val1 is key, val2 is value. if query['val1'] not in _prefix_spec: raise NipapInputError('Search variable \'%s\' unknown' % unicode(query['val1'])) # build where clause if query['operator'] not in _operation_map: raise NipapNoSuchOperatorError("No such operator %s" % query['operator']) if query['val1'] == 'vrf_id' and query['val2'] is None: query['val2'] = 0 # workaround for handling equal matches of NULL-values if query['operator'] == 'equals' and query['val2'] is None: query['operator'] = 'is' elif query['operator'] == 'not_equals' and query['val2'] is None: query['operator'] = 'is_not' if query['operator'] in ( 'contains',
python
{ "resource": "" }
q18510
Nipap._db_remove_prefix
train
def _db_remove_prefix(self, spec, recursive = False): """ Do the underlying database operations to delete a prefix """ if recursive: prefix = spec['prefix'] del spec['prefix'] where, params = self._expand_prefix_spec(spec) spec['prefix'] = prefix params['prefix'] = prefix
python
{ "resource": "" }
q18511
Nipap.remove_prefix
train
def remove_prefix(self, auth, spec, recursive = False): """ Remove prefix matching `spec`. * `auth` [BaseAuth] AAA options. * `spec` [prefix_spec] Specifies prefixe to remove. * `recursive` [bool] When set to True, also remove child prefixes. This is the documentation of the internal backend function. It's exposed over XML-RPC, please also see the XML-RPC documentation for :py:func:`nipap.xmlrpc.NipapXMLRPC.remove_prefix` for full understanding. """ self._logger.debug("remove_prefix called; spec: %s" % unicode(spec)) # sanity check - do we have all attributes? if 'id' in spec: # recursive requires a prefix, so translate id to prefix p = self.list_prefix(auth, spec)[0] del spec['id'] spec['prefix'] = p['prefix'] spec['vrf_id'] = p['vrf_id'] elif 'prefix' in spec: pass else: raise NipapMissingInputError('missing prefix or id of prefix') prefixes = self.list_prefix(auth, spec) if recursive: spec['type'] = 'host'
python
{ "resource": "" }
q18512
Nipap.smart_search_prefix
train
def smart_search_prefix(self, auth, query_str, search_options=None, extra_query=None): """ Perform a smart search on prefix list. * `auth` [BaseAuth] AAA options. * `query_str` [string] Search string * `search_options` [options_dict] Search options. See :func:`search_prefix`. * `extra_query` [dict_to_sql] Extra search terms, will be AND:ed together with what is extracted from the query string. Return a dict with three elements: * :attr:`interpretation` - How the query string was interpreted. * :attr:`search_options` - Various search_options. * :attr:`result` - The search result. The :attr:`interpretation` is given as a list of dicts, each explaining how a part of the search key was interpreted (ie. what prefix attribute the search operation was performed on). The :attr:`result` is a list of dicts containing the search result. The smart search function tries to convert the query from a text
python
{ "resource": "" }
q18513
Nipap._parse_prefix_query
train
def _parse_prefix_query(self, query_str): """ Parse a smart search query for prefixes This is a helper function to smart_search_prefix for easier unit testing of the parser. """
python
{ "resource": "" }
q18514
Nipap.list_asn
train
def list_asn(self, auth, asn=None): """ List AS numbers matching `spec`. * `auth` [BaseAuth] AAA options. * `spec` [asn_spec] An automous system number specification. If omitted, all ASNs are returned. Returns a list of dicts. This is the documentation of the internal backend function. It's exposed over XML-RPC, please also see the XML-RPC documentation for :py:func:`nipap.xmlrpc.NipapXMLRPC.list_asn` for full understanding. """ if asn is None: asn = {}
python
{ "resource": "" }
q18515
Nipap.add_asn
train
def add_asn(self, auth, attr): """ Add AS number to NIPAP. * `auth` [BaseAuth] AAA options. * `attr` [asn_attr] ASN attributes. Returns a dict describing the ASN which was added. This is the documentation of the internal backend function. It's exposed over XML-RPC, please also see the XML-RPC documentation for :py:func:`nipap.xmlrpc.NipapXMLRPC.add_asn` for full understanding. """ self._logger.debug("add_asn called; attr: %s" % unicode(attr))
python
{ "resource": "" }
q18516
Nipap.edit_asn
train
def edit_asn(self, auth, asn, attr): """ Edit AS number * `auth` [BaseAuth] AAA options. * `asn` [integer] AS number to edit. * `attr` [asn_attr] New AS attributes. This is the documentation of the internal backend function. It's exposed over XML-RPC, please also see the XML-RPC documentation for :py:func:`nipap.xmlrpc.NipapXMLRPC.edit_asn` for full understanding. """ self._logger.debug("edit_asn called; asn: %s attr: %s" % (unicode(asn), unicode(attr))) # sanity check - do we have all attributes? req_attr = [ ] allowed_attr = [ 'name', ] self._check_attr(attr, req_attr, allowed_attr) asns = self.list_asn(auth, asn) where, params1 = self._expand_asn_spec(asn) update, params2 = self._sql_expand_update(attr) params = dict(params2.items() + params1.items()) sql = "UPDATE ip_net_asn SET " + update + " WHERE " + where sql += " RETURNING *" self._execute(sql, params) updated_asns = [] for row in self._curs_pg:
python
{ "resource": "" }
q18517
Nipap.remove_asn
train
def remove_asn(self, auth, asn): """ Remove an AS number. * `auth` [BaseAuth] AAA options. * `spec` [asn] An ASN specification. Remove ASNs matching the `asn` argument. This is the documentation of the internal backend function. It's exposed over XML-RPC, please also see the XML-RPC documentation for :py:func:`nipap.xmlrpc.NipapXMLRPC.remove_asn` for full understanding. """ self._logger.debug("remove_asn called; asn: %s" % unicode(asn))
python
{ "resource": "" }
q18518
Nipap.smart_search_asn
train
def smart_search_asn(self, auth, query_str, search_options=None, extra_query=None): """ Perform a smart search operation among AS numbers * `auth` [BaseAuth] AAA options. * `query_str` [string] Search string * `search_options` [options_dict] Search options. See :func:`search_asn`. * `extra_query` [dict_to_sql] Extra search terms, will be AND:ed together with what is extracted from the query string. Return a dict with three elements: * :attr:`interpretation` - How the query string was interpreted. * :attr:`search_options` - Various search_options. * :attr:`result` - The search result. The :attr:`interpretation` is given as a list of dicts, each explaining how a part of the search key was interpreted (ie. what ASN attribute the search operation was performed on). The :attr:`result` is a list of dicts containing the search result. The smart search function tries to convert the query from a text string to a `query` dict which is passed to the :func:`search_asn` function. If multiple search keys are detected, they are combined with a logical AND. See the :func:`search_asn` function for an explanation of the `search_options` argument. This is the documentation of the internal
python
{ "resource": "" }
q18519
Nipap._parse_asn_query
train
def _parse_asn_query(self, query_str): """ Parse a smart search query for ASNs This is a helper function to smart_search_asn for easier unit testing of the parser. """ # find query parts query_str_parts = self._get_query_parts(query_str) # go through parts and add to query_parts list query_parts = list() for query_str_part in query_str_parts: is_int = True try: int(query_str_part['string']) except ValueError: is_int = False if is_int: self._logger.debug("Query part '" + query_str_part['string'] + "' interpreted as integer (ASN)") query_parts.append({ 'interpretation': { 'string': query_str_part['string'], 'interpretation': 'asn', 'attribute': 'asn', 'operator': 'equals', }, 'operator': 'equals', 'val1': 'asn', 'val2': query_str_part['string'] }) else: self._logger.debug("Query part '" + query_str_part['string'] + "' interpreted as text") query_parts.append({ 'interpretation': { 'string': query_str_part['string'], 'interpretation': 'text',
python
{ "resource": "" }
q18520
Nipap._expand_tag_query
train
def _expand_tag_query(self, query, table_name = None): """ Expand Tag query dict into a WHERE-clause. If you need to prefix each column reference with a table name, that can be supplied via the table_name argument. """ where = unicode() opt = list() # handle table name, can be None if table_name is None: col_prefix = "" else: col_prefix = table_name + "." if type(query['val1']) == dict and type(query['val2']) == dict: # Sub expression, recurse! This is used for boolean operators: AND OR # add parantheses sub_where1, opt1 = self._expand_tag_query(query['val1'], table_name) sub_where2, opt2 = self._expand_tag_query(query['val2'], table_name) try: where += unicode(" (%s %s %s) " % (sub_where1, _operation_map[query['operator']], sub_where2) ) except KeyError: raise NipapNoSuchOperatorError("No such operator %s" % unicode(query['operator'])) opt += opt1 opt += opt2 else: # TODO: raise exception if someone passes one dict and one "something else"? # val1 is variable, val2 is string. tag_attr = dict()
python
{ "resource": "" }
q18521
setup_connection
train
def setup_connection(): """ Set up the global pynipap connection object """ # get connection parameters, first from environment variables if they are # defined, otherwise from .nipaprc try: con_params = { 'username': os.getenv('NIPAP_USERNAME') or cfg.get('global', 'username'), 'password': os.getenv('NIPAP_PASSWORD') or cfg.get('global', 'password'), 'hostname': os.getenv('NIPAP_HOST') or cfg.get('global', 'hostname'), 'port' : os.getenv('NIPAP_PORT') or cfg.get('global', 'port') } except (configparser.NoOptionError, configparser.NoSectionError) as exc: print("ERROR:", str(exc), file=sys.stderr) print("HINT: Please define the username, password, hostname and port in your .nipaprc under the section 'global' or provide them through the environment variables NIPAP_HOST, NIPAP_PORT, NIPAP_USERNAME and NIPAP_PASSWORD.", file=sys.stderr) sys.exit(1) # if we haven't got a password (from
python
{ "resource": "" }
q18522
get_pool
train
def get_pool(arg = None, opts = None, abort = False): """ Returns pool to work with Returns a pynipap.Pool object representing the pool we are working with. """ # yep, global variables are evil global pool try: pool = Pool.list({ 'name': arg })[0] except IndexError:
python
{ "resource": "" }
q18523
get_vrf
train
def get_vrf(arg = None, default_var = 'default_vrf_rt', abort = False): """ Returns VRF to work in Returns a pynipap.VRF object representing the VRF we are working in. If there is a VRF set globally, return this. If not, fetch the VRF named 'arg'. If 'arg' is None, fetch the default_vrf attribute from the config file and return this VRF. """ # yep, global variables are evil global vrf # if there is a VRF set, return it if vrf is not None: return vrf if arg is None: # fetch default vrf try: vrf_rt = cfg.get('global', default_var) except configparser.NoOptionError: # default to all VRFs vrf_rt = 'all' else: vrf_rt = arg if vrf_rt.lower() == 'all': vrf = VRF() vrf.rt = 'all' else: if vrf_rt.lower() in ('-',
python
{ "resource": "" }
q18524
list_pool
train
def list_pool(arg, opts, shell_opts): """ List pools matching a search criteria """ search_string = '' if type(arg) == list or type(arg) == tuple: search_string = ' '.join(arg) v = get_vrf(opts.get('vrf_rt'), default_var='default_list_vrf_rt', abort=True) if v.rt == 'all': vrf_q = None else: vrf_q = { 'operator': 'equals', 'val1': 'vrf_rt', 'val2': v.rt } offset = 0 limit = 100 while True: res = Pool.smart_search(search_string, { 'offset': offset, 'max_result': limit }, vrf_q) if offset == 0: # first time in loop? if shell_opts.show_interpretation: print("Query interpretation:") _parse_interp_pool(res['interpretation']) if res['error']: print("Query failed: %s" % res['error_message']) return if len(res['result']) == 0: print("No matching pools found") return print("%-19s %-2s %-39s %-13s %-8s %s" % ( "Name", "#", "Description", "Default type", "4 / 6", "Implied VRF" ))
python
{ "resource": "" }
q18525
list_vrf
train
def list_vrf(arg, opts, shell_opts): """ List VRFs matching a search criteria """ search_string = '' if type(arg) == list or type(arg) == tuple: search_string = ' '.join(arg) offset = 0 limit = 100 while True: res = VRF.smart_search(search_string, { 'offset': offset, 'max_result': limit }) if offset == 0: if shell_opts.show_interpretation: print("Query interpretation:") _parse_interp_vrf(res['interpretation']) if res['error']: print("Query failed: %s" % res['error_message']) return if len(res['result']) == 0: print("No VRFs matching '%s' found." % search_string)
python
{ "resource": "" }
q18526
_prefix_from_opts
train
def _prefix_from_opts(opts): """ Return a prefix based on options passed from command line Used by add_prefix() and add_prefix_from_pool() to avoid duplicate parsing """ p = Prefix() p.prefix = opts.get('prefix') p.type = opts.get('type') p.description = opts.get('description') p.node = opts.get('node') p.country = opts.get('country') p.order_id = opts.get('order_id') p.customer_id = opts.get('customer_id') p.alarm_priority = opts.get('alarm_priority') p.comment =
python
{ "resource": "" }
q18527
add_vrf
train
def add_vrf(arg, opts, shell_opts): """ Add VRF to NIPAP """ v = VRF() v.rt = opts.get('rt') v.name = opts.get('name') v.description = opts.get('description') v.tags = list(csv.reader([opts.get('tags', '')], escapechar='\\'))[0] for avp in opts.get('extra-attribute', []): try: key, value = avp.split('=', 1) except ValueError: print("ERROR: Incorrect extra-attribute: %s. Accepted form: 'key=value'\n" % avp, file=sys.stderr) return
python
{ "resource": "" }
q18528
view_vrf
train
def view_vrf(arg, opts, shell_opts): """ View a single VRF """ if arg is None: print("ERROR: Please specify the RT of the VRF to view.", file=sys.stderr) sys.exit(1) # interpret as default VRF (ie, RT = None) if arg.lower() in ('-', 'none'): arg = None try: v = VRF.search({ 'val1': 'rt', 'operator': 'equals', 'val2': arg } )['result'][0] except (KeyError, IndexError): print("VRF with [RT: %s] not found." % str(arg), file=sys.stderr) sys.exit(1) print("-- VRF") print(" %-26s : %d" % ("ID", v.id)) print(" %-26s : %s" % ("RT", v.rt)) print(" %-26s : %s" % ("Name", v.name)) print(" %-26s : %s" % ("Description", v.description)) print("-- Extra Attributes") if v.avps is not None: for key in sorted(v.avps, key=lambda s: s.lower()): print(" %-26s : %s" % (key, v.avps[key])) print("-- Tags") for tag_name in sorted(v.tags, key=lambda s: s.lower()): print(" %s" % tag_name) # statistics if v.total_addresses_v4 == 0: used_percent_v4 = 0 else: used_percent_v4 = (float(v.used_addresses_v4)/v.total_addresses_v4)*100 if v.total_addresses_v6 == 0: used_percent_v6 = 0
python
{ "resource": "" }
q18529
modify_vrf
train
def modify_vrf(arg, opts, shell_opts): """ Modify a VRF with the options set in opts """ res = VRF.list({ 'rt': arg }) if len(res) < 1: print("VRF with [RT: %s] not found." % arg, file=sys.stderr) sys.exit(1) v = res[0] if 'rt' in opts: v.rt = opts['rt'] if 'name' in opts: v.name = opts['name'] if 'description' in opts: v.description = opts['description'] if 'tags' in opts: tags = list(csv.reader([opts.get('tags', '')], escapechar='\\'))[0] v.tags = {} for tag_name in tags: tag = Tag()
python
{ "resource": "" }
q18530
modify_pool
train
def modify_pool(arg, opts, shell_opts): """ Modify a pool with the options set in opts """ res = Pool.list({ 'name': arg }) if len(res) < 1: print("No pool with name '%s' found." % arg, file=sys.stderr) sys.exit(1) p = res[0] if 'name' in opts: p.name = opts['name'] if 'description' in opts: p.description = opts['description'] if 'default-type' in opts: p.default_type = opts['default-type'] if 'ipv4_default_prefix_length' in opts: p.ipv4_default_prefix_length = opts['ipv4_default_prefix_length'] if 'ipv6_default_prefix_length' in opts: p.ipv6_default_prefix_length = opts['ipv6_default_prefix_length'] if 'tags' in opts: tags = list(csv.reader([opts.get('tags', '')], escapechar='\\'))[0] p.tags = {} for tag_name in tags:
python
{ "resource": "" }
q18531
grow_pool
train
def grow_pool(arg, opts, shell_opts): """ Expand a pool with the ranges set in opts """ if not pool: print("No pool with name '%s' found." % arg, file=sys.stderr) sys.exit(1) if not 'add' in opts: print("Please supply a prefix to add to pool '%s'" % pool.name, file=sys.stderr) sys.exit(1) # Figure out VRF. # If pool already has a member prefix, implied_vrf will be set. Look for new # prefix to add in the same vrf as implied_vrf. # If pool has no members, then use get_vrf() to get vrf to search in for # prefix to add. if pool.vrf
python
{ "resource": "" }
q18532
shrink_pool
train
def shrink_pool(arg, opts, shell_opts): """ Shrink a pool by removing the ranges in opts from it """ if not pool: print("No pool with name '%s' found." % arg, file=sys.stderr) sys.exit(1) if 'remove' in opts: res = Prefix.list({'prefix': opts['remove'], 'pool_id': pool.id}) if len(res) == 0: print("Pool '%s' does not contain %s." % (pool.name, opts['remove']), file=sys.stderr) sys.exit(1) res[0].pool = None
python
{ "resource": "" }
q18533
prefix_attr_add
train
def prefix_attr_add(arg, opts, shell_opts): """ Add attributes to a prefix """ spec = { 'prefix': arg } v = get_vrf(opts.get('vrf_rt'), abort=True) spec['vrf_rt'] = v.rt res = Prefix.list(spec) if len(res) == 0: print("Prefix %s not found in %s." % (arg, vrf_format(v)), file=sys.stderr) return p = res[0] for avp in opts.get('extra-attribute', []): try: key, value = avp.split('=', 1) except ValueError: print("ERROR: Incorrect extra-attribute: %s. Accepted form: 'key=value'\n" % avp, file=sys.stderr) sys.exit(1)
python
{ "resource": "" }
q18534
vrf_attr_add
train
def vrf_attr_add(arg, opts, shell_opts): """ Add attributes to a VRF """ if arg is None: print("ERROR: Please specify the RT of the VRF to view.", file=sys.stderr) sys.exit(1) # interpret as default VRF (ie, RT = None) if arg.lower() in ('-', 'none'): arg = None try: v = VRF.search({ 'val1': 'rt', 'operator': 'equals', 'val2': arg } )['result'][0] except (KeyError, IndexError): print("VRF with [RT: %s] not found." % str(arg), file=sys.stderr) sys.exit(1) for avp in opts.get('extra-attribute', []): try: key, value = avp.split('=', 1) except ValueError:
python
{ "resource": "" }
q18535
pool_attr_add
train
def pool_attr_add(arg, opts, shell_opts): """ Add attributes to a pool """ res = Pool.list({ 'name': arg }) if len(res) < 1: print("No pool with name '%s' found." % arg, file=sys.stderr) sys.exit(1) p = res[0] for avp in opts.get('extra-attribute', []): try: key, value = avp.split('=', 1) except ValueError: print("ERROR: Incorrect extra-attribute: %s. Accepted form: 'key=value'\n" % avp, file=sys.stderr) sys.exit(1) if key in p.avps: print("Unable to add extra-attribute:
python
{ "resource": "" }
q18536
_complete_string
train
def _complete_string(key, haystack): """ Returns valid string completions Takes the string 'key' and compares it to each of the strings in 'haystack'. The ones which beginns with 'key' are returned as result. """ if len(key) == 0: return haystack
python
{ "resource": "" }
q18537
complete_tags
train
def complete_tags(arg): """ Complete NIPAP prefix type """ search_string = '^' if arg is not None: search_string += arg res = Tag.search({ 'operator': 'regex_match', 'val1': 'name',
python
{ "resource": "" }
q18538
complete_pool_members
train
def complete_pool_members(arg): """ Complete member prefixes of pool """ # pool should already be globally set res = [] for member in Prefix.list({
python
{ "resource": "" }
q18539
complete_node
train
def complete_node(arg): """ Complete node hostname This function is currently a bit special as it looks in the config file for a command to use to complete a node hostname from an external system. It is configured by setting the config attribute "complete_node_cmd" to a shell command. The string "%search_string%" in the command will be replaced by the current search string. """ # get complete command
python
{ "resource": "" }
q18540
complete_pool_name
train
def complete_pool_name(arg): """ Returns list of matching pool names """ search_string = '^' if arg is not None: search_string += arg res = Pool.search({ 'operator': 'regex_match', 'val1': 'name',
python
{ "resource": "" }
q18541
SmartParser._string_to_ast
train
def _string_to_ast(self, input_string): """ Parse a smart search string and return it in an AST like form """ # simple words # we need to use a regex to match on words because the regular # Word(alphanums) will only match on American ASCII alphanums and since # we try to be Unicode / internationally friendly we need to match much # much more. Trying to expand a word class to catch it all seems futile # so we match on everything *except* a few things, like our operators comp_word = Regex("[^*\s=><~!]+") word = Regex("[^*\s=><~!]+").setResultsName('word') # numbers comp_number = Word(nums) number = Word(nums).setResultsName('number') # IPv4 address ipv4_oct = Regex("((2(5[0-5]|[0-4][0-9])|[01]?[0-9][0-9]?))") comp_ipv4_address = Combine(ipv4_oct + ('.' + ipv4_oct*3)) ipv4_address = Combine(ipv4_oct + ('.' + ipv4_oct*3)).setResultsName('ipv4_address') # IPv6 address ipv6_address = Regex("((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?").setResultsName('ipv6_address') ipv6_prefix = Combine(ipv6_address + Regex("/(12[0-8]|1[01][0-9]|[0-9][0-9]?)")).setResultsName('ipv6_prefix') # VRF RTs of the form number:number vrf_rt = Combine((comp_ipv4_address | comp_number) + Literal(':') + comp_number).setResultsName('vrf_rt') # tags tags = Combine( Literal('#') + comp_word).setResultsName('tag')
python
{ "resource": "" }
q18542
Command._examine_key
train
def _examine_key(self, key_name, key_val, p, i, option_parsing): """ Examine the current matching key Extracts information, such as function to execute and command options, from the current key (passed to function as 'key_name' and 'key_val'). """ # if the element we reached has an executable registered, save it! if 'exec' in key_val: self.exe = key_val['exec'] # simple bool options, save value if 'type' in key_val and key_val['type'] == 'bool': self.exe_options[key_name] = True # Elements wich takes arguments need special attention if 'argument' in key_val: # is there an argument (the next element)? if len(self.inp_cmd) > i+1: self.key = { 'argument': key_val['argument'] } # there is - save it if key_val['type'] == 'option': # if argument is of type multiple, store result in a list if 'multiple' in key_val and key_val['multiple'] == True: if key_name not in self.exe_options: self.exe_options[key_name] = [] self.exe_options[key_name].append(self.inp_cmd[i+1]) else: self.exe_options[key_name] = self.inp_cmd[i+1] else: self.arg = self.inp_cmd[i+1] # Validate the argument if possible if 'validator' in key_val['argument']: self.key_complete = key_val['argument']['validator'](self.inp_cmd[i+1]) else: self.key_complete = True # if there are sub parameters, add them if 'children' in key_val: self.children = key_val['children'] # If we reached a command without parameters (which # should be the end of the command), unset the children # dict. elif key_val['type'] == 'command': self.children = None # if the command is finished (there is an element
python
{ "resource": "" }
q18543
Command.parse_cmd
train
def parse_cmd(self, tree, inp_cmd = None): """ Extract command and options from string. The tree argument should contain a specifically formatted dict which describes the available commands, options, arguments and callbacks to methods for completion of arguments. TODO: document dict format The inp_cmd argument should contain a list of strings containing the complete command to parse, such as sys.argv (without the first element which specified the command itself). """ # reset state from previous execution self.exe = None self.arg = None self.exe_options = {} self.children = tree['children'] self.key = tree['children'] option_parsing = False self._scoop_rest_arguments = False if inp_cmd is not None: self.inp_cmd = inp_cmd # iterate the list of inputted commands i = 0 while i < len(self.inp_cmd): p = self.inp_cmd[i] self.key = {} # Find which of the valid commands matches the current element of inp_cmd if self.children is not None: self.key_complete = False match = False for param, content in self.children.items(): # match string to command if param.find(p) == 0: self.key[param] = content match = True # If we have an exact match, make sure that # is the only element in self.key if p == param and len(self.inp_cmd) > i+1: self.key_complete
python
{ "resource": "" }
q18544
Command.complete
train
def complete(self): """ Return list of valid completions Returns a list of valid completions on the current level in the tree. If an element of type 'value' is found, its complete callback function is called (if set). """ comp = [] for k, v in self.key.items(): # if we have reached a value, try to fetch valid completions if v['type'] == 'value':
python
{ "resource": "" }
q18545
Command.next_values
train
def next_values(self): """ Return list of valid next values """ nval = [] for k, v in self.children.items(): # if we have reached a value, try to fetch valid
python
{ "resource": "" }
q18546
PoolController.remove
train
def remove(self, id): """ Remove pool. """ p = Pool.get(int(id)) p.remove()
python
{ "resource": "" }
q18547
PoolController.remove_prefix
train
def remove_prefix(self, id): """ Remove a prefix from pool 'id'. """ if 'prefix' not in request.params: abort(400, 'Missing prefix.') prefix = Prefix.get(int(request.params['prefix']))
python
{ "resource": "" }
q18548
add_ip_to_net
train
def add_ip_to_net(networks, host): """ Add hosts from ipplan to networks object. """
python
{ "resource": "" }
q18549
get_networks
train
def get_networks(base_file, ipaddr_file): """ Gather network and host information from ipplan export files. """ networks = [] base = open(base_file, 'r') csv_reader = csv.reader(base, delimiter='\t') buffer = "" for row in csv_reader: # Fixes quotation bug in ipplan exporter for base.txt if len(networks) > 0 and len(buffer) > 0: networks[-1]['comment'] += " ".join(buffer) buffer = "" if len(row) < 3: buffer = row else: network = { 'network': ipaddress.ip_network("{}/{}".format(row[0], row[2])), 'description': row[1], 'hosts': [], 'comment': "" } if len(row) > 3: network['additional'] = " ".join(row[3:]) networks.append(network) base.close() ipaddr = open(ipaddr_file, 'r') csv_reader = csv.reader(ipaddr, delimiter='\t')
python
{ "resource": "" }
q18550
add_prefix
train
def add_prefix(network): """ Put your network information in the prefix object. """ p = new_prefix() p.prefix = str(network['network']) p.type = "assignment"
python
{ "resource": "" }
q18551
add_host
train
def add_host(host): """ Put your host information in the prefix object. """ p = new_prefix() p.prefix = str(host['ipaddr']) p.type = "host" p.description = host['description'] p.node = host['fqdn'] p.avps = {} # Use remaining data from ipplan to populate comment field. if 'additional' in host: p.comment = host['additional'] # Use specific info to create extra attributes.
python
{ "resource": "" }
q18552
nipapd_version
train
def nipapd_version(): """ Get version of nipapd we're connected to. Maps to the function :py:func:`nipap.xmlrpc.NipapXMLRPC.version` in the XML-RPC API. Please see the documentation for the XML-RPC function for information regarding the return value. """ xmlrpc = XMLRPCConnection() try:
python
{ "resource": "" }
q18553
nipap_db_version
train
def nipap_db_version(): """ Get schema version of database we're connected to. Maps to the function :py:func:`nipap.backend.Nipap._get_db_version` in the backend. Please see the documentation for the backend function for information regarding the return value. """ xmlrpc = XMLRPCConnection() try:
python
{ "resource": "" }
q18554
_fault_to_exception
train
def _fault_to_exception(f): """ Converts XML-RPC Fault objects to Pynipap-exceptions. TODO: Is this one neccesary? Can be done inline... """ e =
python
{ "resource": "" }
q18555
Tag.from_dict
train
def from_dict(cls, tag=None): """ Create new Tag-object from dict. Suitable for creating objects from XML-RPC data. All available keys must exist. """
python
{ "resource": "" }
q18556
Tag.search
train
def search(cls, query, search_opts=None): """ Search tags. For more information, see the backend function :py:func:`nipap.backend.Nipap.search_tag`. """ if search_opts is None: search_opts = {} xmlrpc = XMLRPCConnection() try: search_result = xmlrpc.connection.search_tag( { 'query': query, 'search_options': search_opts,
python
{ "resource": "" }
q18557
VRF.list
train
def list(cls, vrf=None): """ List VRFs. Maps to the function :py:func:`nipap.backend.Nipap.list_vrf` in the backend. Please see the documentation for the backend function for information regarding input arguments and return values. """ if vrf is None: vrf = {} xmlrpc = XMLRPCConnection() try: vrf_list = xmlrpc.connection.list_vrf( {
python
{ "resource": "" }
q18558
VRF.from_dict
train
def from_dict(cls, parm, vrf = None): """ Create new VRF-object from dict. Suitable for creating objects from XML-RPC data. All available keys must exist. """ if vrf is None: vrf = VRF() vrf.id = parm['id'] vrf.rt = parm['rt'] vrf.name = parm['name'] vrf.description = parm['description'] vrf.tags = {} for tag_name in parm['tags']: tag = Tag.from_dict({'name': tag_name }) vrf.tags[tag_name] = tag vrf.avps = parm['avps'] vrf.num_prefixes_v4 = int(parm['num_prefixes_v4']) vrf.num_prefixes_v6 = int(parm['num_prefixes_v6'])
python
{ "resource": "" }
q18559
VRF.get
train
def get(cls, id): """ Get the VRF with id 'id'. """ # cached? if CACHE: if id in _cache['VRF']: log.debug('cache hit for VRF %d' % id)
python
{ "resource": "" }
q18560
VRF.search
train
def search(cls, query, search_opts=None): """ Search VRFs. Maps to the function :py:func:`nipap.backend.Nipap.search_vrf` in the backend. Please see the documentation for the backend function for information regarding input arguments and return values. """ if search_opts is None: search_opts = {} xmlrpc = XMLRPCConnection()
python
{ "resource": "" }
q18561
VRF.save
train
def save(self): """ Save changes made to object to NIPAP. If the object represents a new VRF unknown to NIPAP (attribute `id` is `None`) this function maps to the function :py:func:`nipap.backend.Nipap.add_vrf` in the backend, used to create a new VRF. Otherwise it maps to the function :py:func:`nipap.backend.Nipap.edit_vrf` in the backend, used to modify the VRF. Please see the documentation for the backend functions for information regarding input arguments and return values. """ xmlrpc = XMLRPCConnection() data = { 'rt': self.rt, 'name': self.name, 'description': self.description, 'tags': [], 'avps': self.avps
python
{ "resource": "" }
q18562
VRF.remove
train
def remove(self): """ Remove VRF. Maps to the function :py:func:`nipap.backend.Nipap.remove_vrf` in the backend. Please see the documentation for the backend function for information regarding input arguments and return values. """ xmlrpc = XMLRPCConnection() try: xmlrpc.connection.remove_vrf( {
python
{ "resource": "" }
q18563
Pool.save
train
def save(self): """ Save changes made to pool to NIPAP. If the object represents a new pool unknown to NIPAP (attribute `id` is `None`) this function maps to the function :py:func:`nipap.backend.Nipap.add_pool` in the backend, used to create a new pool. Otherwise it maps to the function :py:func:`nipap.backend.Nipap.edit_pool` in the backend, used to modify the pool. Please see the documentation for the backend functions for information regarding input arguments and return values. """ xmlrpc = XMLRPCConnection() data = { 'name': self.name, 'description': self.description, 'default_type': self.default_type, 'ipv4_default_prefix_length': self.ipv4_default_prefix_length, 'ipv6_default_prefix_length': self.ipv6_default_prefix_length, 'tags': [], 'avps': self.avps } for tag_name in self.tags: data['tags'].append(tag_name) if self.id is None: # New object, create try: pool = xmlrpc.connection.add_pool( { 'attr': data, 'auth': self._auth_opts.options }) except xmlrpclib.Fault as xml_fault: raise _fault_to_exception(xml_fault) else: # Old object, edit
python
{ "resource": "" }
q18564
Pool.get
train
def get(cls, id): """ Get the pool with id 'id'. """ # cached? if CACHE: if id in _cache['Pool']: log.debug('cache hit for pool %d' % id) return _cache['Pool'][id] log.debug('cache miss for pool %d' % id) try:
python
{ "resource": "" }
q18565
Pool.search
train
def search(cls, query, search_opts=None): """ Search pools. Maps to the function :py:func:`nipap.backend.Nipap.search_pool` in the backend. Please see the documentation for the backend function for information regarding input arguments and return values. """ if search_opts is None: search_opts = {} xmlrpc = XMLRPCConnection()
python
{ "resource": "" }
q18566
Pool.from_dict
train
def from_dict(cls, parm, pool = None): """ Create new Pool-object from dict. Suitable for creating objects from XML-RPC data. All available keys must exist. """ if pool is None: pool = Pool() pool.id = parm['id'] pool.name = parm['name'] pool.description = parm['description'] pool.default_type = parm['default_type'] pool.ipv4_default_prefix_length = parm['ipv4_default_prefix_length'] pool.ipv6_default_prefix_length = parm['ipv6_default_prefix_length'] for val in ('member_prefixes_v4', 'member_prefixes_v6', 'used_prefixes_v4', 'used_prefixes_v6', 'free_prefixes_v4', 'free_prefixes_v6', 'total_prefixes_v4', 'total_prefixes_v6', 'total_addresses_v4', 'total_addresses_v6', 'used_addresses_v4',
python
{ "resource": "" }
q18567
Pool.list
train
def list(self, spec=None): """ List pools. Maps to the function :py:func:`nipap.backend.Nipap.list_pool` in the backend. Please see the documentation for the backend function for information regarding input arguments and return values. """ if spec is None: spec = {} xmlrpc = XMLRPCConnection() try: pool_list = xmlrpc.connection.list_pool( {
python
{ "resource": "" }
q18568
Prefix.get
train
def get(cls, id): """ Get the prefix with id 'id'. """ # cached? if CACHE: if id in _cache['Prefix']: log.debug('cache hit for prefix %d' % id) return _cache['Prefix'][id] log.debug('cache miss for prefix %d' % id)
python
{ "resource": "" }
q18569
Prefix.find_free
train
def find_free(cls, vrf, args): """ Finds a free prefix. Maps to the function :py:func:`nipap.backend.Nipap.find_free_prefix` in the backend. Please see the documentation for the backend function for information regarding input arguments and return values. """ xmlrpc = XMLRPCConnection() q = {
python
{ "resource": "" }
q18570
Prefix.search
train
def search(cls, query, search_opts=None): """ Search for prefixes. Maps to the function :py:func:`nipap.backend.Nipap.search_prefix` in the backend. Please see the documentation for the backend function for information regarding input arguments and return values. """ if search_opts is None: search_opts = {} xmlrpc = XMLRPCConnection()
python
{ "resource": "" }
q18571
Prefix.smart_search
train
def smart_search(cls, query_string, search_options=None, extra_query = None): """ Perform a smart prefix search. Maps to the function :py:func:`nipap.backend.Nipap.smart_search_prefix` in the backend. Please see the documentation for the backend function for information regarding input arguments and return values. """ if search_options is None: search_options = {} xmlrpc = XMLRPCConnection() try: smart_result = xmlrpc.connection.smart_search_prefix( { 'query_string': query_string, 'search_options': search_options, 'auth': AuthOptions().options, 'extra_query': extra_query }) except xmlrpclib.Fault as xml_fault:
python
{ "resource": "" }
q18572
Prefix.list
train
def list(cls, spec=None): """ List prefixes. Maps to the function :py:func:`nipap.backend.Nipap.list_prefix` in the backend. Please see the documentation for the backend function for information regarding input arguments and return values. """ if spec is None: spec = {} xmlrpc = XMLRPCConnection() try: pref_list = xmlrpc.connection.list_prefix( {
python
{ "resource": "" }
q18573
Prefix.save
train
def save(self, args=None): """ Save prefix to NIPAP. If the object represents a new prefix unknown to NIPAP (attribute `id` is `None`) this function maps to the function :py:func:`nipap.backend.Nipap.add_prefix` in the backend, used to create a new prefix. Otherwise it maps to the function :py:func:`nipap.backend.Nipap.edit_prefix` in the backend, used to modify the VRF. Please see the documentation for the backend functions for information regarding input arguments and return values. """ if args is None: args = {} xmlrpc = XMLRPCConnection() data = { 'description': self.description, 'comment': self.comment, 'tags': [], 'node': self.node, 'type': self.type, 'country': self.country, 'order_id': self.order_id, 'customer_id': self.customer_id, 'external_key': self.external_key, 'alarm_priority': self.alarm_priority, 'monitor': self.monitor, 'vlan': self.vlan, 'avps': self.avps, 'expires': self.expires } if self.status is not None: data['status'] = self.status for tag_name in self.tags: data['tags'].append(tag_name) if self.vrf is not None: if not isinstance(self.vrf, VRF): raise NipapValueError("'vrf' attribute not instance of VRF class.") data['vrf_id'] = self.vrf.id # Prefix can be none if we are creating a new prefix # from a pool or other prefix! if self.prefix is not None: data['prefix'] = self.prefix if self.pool is None: data['pool_id'] = None else: if not isinstance(self.pool, Pool): raise NipapValueError("'pool' attribute not instance of Pool class.") data['pool_id'] = self.pool.id # New object, create from scratch if self.id is None: # format args x_args = {} if 'from-pool' in args: x_args['from-pool'] = { 'id': args['from-pool'].id } if 'family' in args: x_args['family'] = args['family']
python
{ "resource": "" }
q18574
Prefix.remove
train
def remove(self, recursive = False): """ Remove the prefix. Maps to the function :py:func:`nipap.backend.Nipap.remove_prefix` in the backend. Please see the documentation for the backend function for information regarding input arguments and return values. """ xmlrpc = XMLRPCConnection() try:
python
{ "resource": "" }
q18575
Prefix.from_dict
train
def from_dict(cls, pref, prefix = None): """ Create a Prefix object from a dict. Suitable for creating Prefix objects from XML-RPC input. """ if prefix is None: prefix = Prefix() prefix.id = pref['id'] if pref['vrf_id'] is not None: # VRF is not mandatory prefix.vrf = VRF.get(pref['vrf_id']) prefix.family = pref['family'] prefix.prefix = pref['prefix'] prefix.display_prefix = pref['display_prefix'] prefix.description = pref['description'] prefix.comment = pref['comment'] prefix.node = pref['node'] if pref['pool_id'] is not None: # Pool is not mandatory prefix.pool = Pool.get(pref['pool_id']) prefix.type = pref['type'] prefix.indent = pref['indent'] prefix.country = pref['country'] prefix.order_id = pref['order_id']
python
{ "resource": "" }
q18576
VrfController.edit
train
def edit(self, id): """ Edit a VRF """ c.action = 'edit' c.edit_vrf = VRF.get(int(id)) # Did we have any action passed to us? if 'action' in request.params: if request.params['action'] == 'edit': if request.params['rt'].strip() == '': c.edit_vrf.rt = None else: c.edit_vrf.rt = request.params['rt'].strip()
python
{ "resource": "" }
q18577
VrfController.remove
train
def remove(self, id): """ Removes a VRF. """ v = VRF.get(int(id)) v.remove()
python
{ "resource": "" }
q18578
setup_app
train
def setup_app(command, conf, vars): """Place any commands to setup nipapwww here""" # Don't reload the
python
{ "resource": "" }
q18579
PrefixController.edit
train
def edit(self, id): """ Edit a prefix. """ # find prefix c.prefix = Prefix.get(int(id)) # we got a HTTP POST - edit object if request.method == 'POST': c.prefix.prefix = request.params['prefix_prefix'] c.prefix.description = request.params['prefix_description'] if request.params['prefix_node'].strip() == '': c.prefix.node = None else: c.prefix.node = request.params['prefix_node'] if request.params['prefix_country'].strip() == '': c.prefix.country = None else: c.prefix.country = request.params['prefix_country'] if request.params['prefix_comment'].strip() == '': c.prefix.comment = None else: c.prefix.comment = request.params['prefix_comment'] if request.params['prefix_order_id'].strip() == '': c.prefix.order_id = None else: c.prefix.order_id = request.params['prefix_order_id'] if request.params['prefix_customer_id'].strip() == '':
python
{ "resource": "" }
q18580
ConfigExport.get_prefixes
train
def get_prefixes(self, query): """ Get prefix data from NIPAP """ try: res = Prefix.smart_search(query, {}) except socket.error: print >> sys.stderr, "Connection refused, please check hostname & port" sys.exit(1) except xmlrpclib.ProtocolError:
python
{ "resource": "" }
q18581
ConfigExport.write_conf
train
def write_conf(self): """ Write the config to file """ f = open(self.output_filename, 'w')
python
{ "resource": "" }
q18582
_mangle_prefix
train
def _mangle_prefix(res): """ Mangle prefix result """ # fugly cast from large numbers to string to deal with XML-RPC res['total_addresses'] = unicode(res['total_addresses']) res['used_addresses'] = unicode(res['used_addresses']) res['free_addresses'] = unicode(res['free_addresses']) # postgres has notion of infinite while datetime hasn't, if expires # is equal to the max datetime we assume it is infinity and instead
python
{ "resource": "" }
q18583
requires_auth
train
def requires_auth(f): """ Class decorator for XML-RPC functions that requires auth """ @wraps(f) def decorated(self, *args, **kwargs): """ """ # Fetch auth options from args auth_options = {} nipap_args = {} # validate function arguments if len(args) == 1: nipap_args = args[0] else: self.logger.debug("Malformed request: got %d parameters" % len(args)) raise Fault(1000, ("NIPAP API functions take exactly 1 argument (%d given)") % len(args)) if type(nipap_args) != dict: self.logger.debug("Function argument is not struct") raise Fault(1000, ("Function argument must be XML-RPC struct/Python dict (Python %s given)." % type(nipap_args).__name__ )) # fetch auth options try: auth_options = nipap_args['auth'] if type(auth_options) is not dict: raise ValueError() except (KeyError, ValueError): self.logger.debug("Missing/invalid authentication options in request.") raise Fault(1000, ("Missing/invalid authentication options in request.")) # fetch authoritative source try: auth_source = auth_options['authoritative_source'] except KeyError:
python
{ "resource": "" }
q18584
NipapXMLRPC.echo
train
def echo(self, args): """ An echo function An API test function which simply echoes what is is passed in the 'message' element in the args-dict.. Valid keys in the `args`-struct: * `auth` [struct] Authentication options passed to the :class:`AuthFactory`. * `message` [string] String to echo. * `sleep` [integer] Number of seconds
python
{ "resource": "" }
q18585
NipapXMLRPC.find_free_prefix
train
def find_free_prefix(self, args): """ Find a free prefix. Valid keys in the `args`-struct: * `auth` [struct] Authentication options passed to the :class:`AuthFactory`. * `args` [struct] Arguments for the find_free_prefix-function such as what prefix or pool to allocate from. """ try:
python
{ "resource": "" }
q18586
NewsFile._readfile
train
def _readfile(self, filename): """ Read content of specified NEWS file """
python
{ "resource": "" }
q18587
DchFile._parse
train
def _parse(self): """ Parse content of DCH file """ cur_ver = None cur_line = None for line in self.content: m = re.match('[^ ]+ \(([0-9]+\.[0-9]+\.[0-9]+)-[0-9]+\) [^ ]+; urgency=[^ ]+', line) if m: cur_ver = m.group(1) self.versions.append(cur_ver) self.entries[cur_ver] = [] cur_entry = self.entries[cur_ver] if self.latest_version is None or StrictVersion(cur_ver) > StrictVersion(self.latest_version):
python
{ "resource": "" }
q18588
JsonFormatter.format
train
def format(self, record: logging.LogRecord) -> str: """ Formats a record and serializes it as a JSON str. If record message isnt already a dict, initializes a new dict and uses `default_msg_fieldname` as a key as the record msg as the value. """ msg: Union[str, dict] = record.msg if not isinstance(record.msg, dict): msg = {self.default_msg_fieldname: msg} if record.exc_info: # type: ignore
python
{ "resource": "" }
q18589
BaseAsyncRotatingFileHandler.rotation_filename
train
def rotation_filename(self, default_name: str) -> str: """ Modify the filename of a log file when rotating. This is provided so that a custom filename can be provided. :param
python
{ "resource": "" }
q18590
BaseAsyncRotatingFileHandler.rotate
train
async def rotate(self, source: str, dest: str): """ When rotating, rotate the current log. The default implementation calls the 'rotator' attribute of the handler, if it's callable, passing the source and dest arguments to it. If the attribute isn't callable (the default is None), the source is simply renamed to the destination. :param source: The source filename. This is normally the base filename, e.g. 'test.log' :param dest: The destination filename. This is normally what the source
python
{ "resource": "" }
q18591
AsyncTimedRotatingFileHandler.compute_rollover
train
def compute_rollover(self, current_time: int) -> int: """ Work out the rollover time based on the specified time. If we are rolling over at midnight or weekly, then the interval is already known. need to figure out is WHEN the next interval is. In other words, if you are rolling over at midnight, then your base interval is 1 day, but you want to start that one day clock at midnight, not now. So, we have to fudge the `rollover_at` value in order to trigger the first rollover at the right time. After that, the regular interval will take care of the rest. Note that this code doesn't care about leap seconds. :) """ result = current_time + self.interval if ( self.when == RolloverInterval.MIDNIGHT or self.when in RolloverInterval.WEEK_DAYS ): if self.utc: t = time.gmtime(current_time) else: t = time.localtime(current_time) current_hour = t[3] current_minute = t[4] current_second = t[5] current_day = t[6] # r is the number of seconds left between now and the next rotation if self.at_time is None: rotate_ts = ONE_DAY_IN_SECONDS else: rotate_ts = ( self.at_time.hour * 60 + self.at_time.minute ) * 60 + self.at_time.second r = rotate_ts - ( (current_hour * 60 + current_minute) * 60 + current_second ) if r < 0: # Rotate time is before the current time (for example when # self.rotateAt is 13:45 and it now 14:15), rotation is # tomorrow. r += ONE_DAY_IN_SECONDS current_day = (current_day + 1) % 7 result = current_time + r # If we are rolling over on a certain day, add in the number of days until # the next rollover, but offset by 1 since we just calculated the time # until the next day starts. There are three cases: # Case 1) The day to rollover is today; in this case, do nothing # Case 2) The day to rollover is further in the interval (i.e., today is # day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to # next rollover is simply 6 - 2
python
{ "resource": "" }
q18592
AsyncTimedRotatingFileHandler.get_files_to_delete
train
async def get_files_to_delete(self) -> List[str]: """ Determine the files to delete when rolling over. """ dir_name, base_name = os.path.split(self.absolute_file_path) file_names = await self.loop.run_in_executor( None, lambda: os.listdir(dir_name) ) result = [] prefix = base_name + "." plen = len(prefix) for file_name in file_names: if file_name[:plen] == prefix:
python
{ "resource": "" }
q18593
AsyncStreamHandler.handle
train
async def handle(self, record: LogRecord) -> bool: # type: ignore """ Conditionally emit the specified logging record.
python
{ "resource": "" }
q18594
AsyncStreamHandler.emit
train
async def emit(self, record: LogRecord): # type: ignore """ Actually log the specified logging record to the stream. """ if self.writer is None: self.writer = await self._init_writer() try: msg
python
{ "resource": "" }
q18595
Logger.callHandlers
train
async def callHandlers(self, record): """ Pass a record to all relevant handlers. Loop through all handlers for this logger and its parents in the logger hierarchy. If no handler was found, raises an error. Stop searching up the hierarchy whenever a logger with the "propagate" attribute set to zero is found - that will be the last logger whose handlers are called. """ c = self found = 0 while c:
python
{ "resource": "" }
q18596
Logger.handle
train
async def handle(self, record): """ Call the handlers for the specified record. This method is used for unpickled records received from a socket, as well as those created locally.
python
{ "resource": "" }
q18597
Logger._make_log_task
train
def _make_log_task(self, level, msg, *args, **kwargs) -> Task: """ Creates an asyncio.Task for a msg if logging is enabled for level. Returns a dummy task otherwise. """ if not self.isEnabledFor(level): if self._dummy_task is None:
python
{ "resource": "" }
q18598
Logger.debug
train
def debug(self, msg, *args, **kwargs) -> Task: # type: ignore """ Log msg with severity 'DEBUG'. To pass exception information, use the keyword
python
{ "resource": "" }
q18599
Logger.info
train
def info(self, msg, *args, **kwargs) -> Task: # type: ignore """ Log msg with severity 'INFO'. To pass exception information, use the keyword
python
{ "resource": "" }