text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Add anycast gateway under interface ve.
<END_TASK>
<USER_TASK:>
Description:
def ip_anycast_gateway(self, **kwargs):
"""
Add anycast gateway under interface ve.
Args:
int_type: L3 interface type on which the anycast ip
needs to be configured.
name:L3 interface name on which the anycast ip
needs to be configured.
anycast_ip: Anycast ip which the L3 interface
needs to be associated.
enable (bool): If ip anycast gateway should be enabled
or disabled.Default:``True``.
get (bool) : Get config instead of editing config. (True, False)
rbridge_id (str): rbridge-id for device. Only required when type is
`ve`.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `int_type`, `name`, `anycast_ip` is not passed.
ValueError: if `int_type`, `name`, `anycast_ip` is invalid.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.ip_anycast_gateway(
... int_type='ve',
... name='89',
... anycast_ip='10.20.1.1/24',
... rbridge_id='1')
... output = dev.interface.ip_anycast_gateway(
... get=True,int_type='ve',
... name='89',
... anycast_ip='10.20.1.1/24',
... rbridge_id='1')
... output = dev.interface.ip_anycast_gateway(
... enable=False,int_type='ve',
... name='89',
... anycast_ip='10.20.1.1/24',
... rbridge_id='1')
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
int_type = kwargs.pop('int_type').lower()
name = kwargs.pop('name')
anycast_ip = kwargs.pop('anycast_ip', '')
enable = kwargs.pop('enable', True)
get = kwargs.pop('get', False)
rbridge_id = kwargs.pop('rbridge_id', '1')
callback = kwargs.pop('callback', self._callback)
valid_int_types = ['ve']
method_class = self._rbridge
if get and anycast_ip == '':
enable = None
if int_type not in valid_int_types:
raise ValueError('`int_type` must be one of: %s' %
repr(valid_int_types))
anycast_args = dict(name=name, ip_address=anycast_ip,
ipv6_address=anycast_ip)
method_name1 = 'interface_%s_ip_ip_anycast_'\
'address_ip_address' % int_type
method_name2 = 'interface_%s_ipv6_ipv6_'\
'anycast_address_ipv6_address' % int_type
method_name1 = 'rbridge_id_%s' % method_name1
method_name2 = 'rbridge_id_%s' % method_name2
anycast_args['rbridge_id'] = rbridge_id
if not pynos.utilities.valid_vlan_id(name):
raise InvalidVlanId("`name` must be between `1` and `8191`")
ip_anycast_gateway1 = getattr(method_class, method_name1)
ip_anycast_gateway2 = getattr(method_class, method_name2)
config1 = ip_anycast_gateway1(**anycast_args)
config2 = ip_anycast_gateway2(**anycast_args)
result = []
result.append(callback(config1, handler='get_config'))
result.append(callback(config2, handler='get_config'))
return result
elif get:
enable = None
ipaddress = ip_interface(unicode(anycast_ip))
if int_type not in valid_int_types:
raise ValueError('`int_type` must be one of: %s' %
repr(valid_int_types))
if anycast_ip != '':
ipaddress = ip_interface(unicode(anycast_ip))
if ipaddress.version == 4:
anycast_args = dict(name=name, ip_address=anycast_ip)
method_name = 'interface_%s_ip_ip_anycast_'\
'address_ip_address' % int_type
elif ipaddress.version == 6:
anycast_args = dict(name=name, ipv6_address=anycast_ip)
method_name = 'interface_%s_ipv6_ipv6_'\
'anycast_address_ipv6_address' % int_type
method_name = 'rbridge_id_%s' % method_name
anycast_args['rbridge_id'] = rbridge_id
if not pynos.utilities.valid_vlan_id(name):
raise InvalidVlanId("`name` must be between `1` and `8191`")
ip_anycast_gateway = getattr(method_class, method_name)
config = ip_anycast_gateway(**anycast_args)
if get:
return callback(config, handler='get_config')
if not enable:
if ipaddress.version == 4:
config.find('.//*ip-anycast-address').\
set('operation', 'delete')
elif ipaddress.version == 6:
config.find('.//*ipv6-anycast-address').\
set('operation', 'delete')
return callback(config) |
<SYSTEM_TASK:>
Enable Arp Suppression on a Vlan.
<END_TASK>
<USER_TASK:>
Description:
def arp_suppression(self, **kwargs):
"""
Enable Arp Suppression on a Vlan.
Args:
name:Vlan name on which the Arp suppression needs to be enabled.
enable (bool): If arp suppression should be enabled
or disabled.Default:``True``.
get (bool) : Get config instead of editing config. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `name` is not passed.
ValueError: if `name` is invalid.
output2 = dev.interface.arp_suppression(name='89')
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.arp_suppression(
... name='89')
... output = dev.interface.arp_suppression(
... get=True,name='89')
... output = dev.interface.arp_suppression(
... enable=False,name='89')
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
name = kwargs.pop('name')
enable = kwargs.pop('enable', True)
get = kwargs.pop('get', False)
callback = kwargs.pop('callback', self._callback)
method_class = self._interface
arp_args = dict(name=name)
if name:
if not pynos.utilities.valid_vlan_id(name):
raise InvalidVlanId("`name` must be between `1` and `8191`")
arp_suppression = getattr(method_class,
'interface_vlan_interface_vlan_suppress_'
'arp_suppress_arp_enable')
config = arp_suppression(**arp_args)
if get:
return callback(config, handler='get_config')
if not enable:
config.find('.//*suppress-arp').set('operation', 'delete')
return callback(config) |
<SYSTEM_TASK:>
Add "Duplicate MAC max count" under evpn instance.
<END_TASK>
<USER_TASK:>
Description:
def evpn_instance_mac_timer_max_count(self, **kwargs):
"""
Add "Duplicate MAC max count" under evpn instance.
Args:
evpn_instance_name: Instance name for evpn
max_count: Duplicate MAC max count.
enable (bool): If target community needs to be enabled
or disabled.Default:``True``.
get (bool) : Get config instead of editing config. (True, False)
rbridge_id (str): rbridge-id for device. Only required when type is
`ve`.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if 'evpn_instance_name' is not passed.
ValueError: if 'evpn_instance_name' is invalid.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output=dev.interface.evpn_instance_mac_timer_max_count(
... evpn_instance_name='100',
... max_count='10'
... rbridge_id='1')
... output=dev.interface.evpn_instance_mac_timer_max_count(
... get=True,
... evpn_instance_name='100',
... max_count='10'
... rbridge_id='1')
... output=dev.interface.evpn_instance_mac_timer_max_count(
... enable=False,
... evpn_instance_name='101',
... max_count='10'
... rbridge_id='1')
... output=dev.interface.evpn_instance_mac_timer_max_count(
... get=True,
... evpn_instance_name='101',
... rbridge_id='1')
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
evpn_instance_name = kwargs.pop('evpn_instance_name', '')
max_count = kwargs.pop('max_count', '5')
enable = kwargs.pop('enable', True)
get = kwargs.pop('get', False)
rbridge_id = kwargs.pop('rbridge_id', '1')
callback = kwargs.pop('callback', self._callback)
evpn_args = dict(instance_name=evpn_instance_name,
max_count=max_count)
if get:
enable = None
method_name = 'rbridge_id_evpn_instance_duplicate_'\
'mac_timer_max_count'
method_class = self._rbridge
evpn_args['rbridge_id'] = rbridge_id
evpn_instance_mac_timer_max_count = getattr(method_class, method_name)
config = evpn_instance_mac_timer_max_count(**evpn_args)
if get:
return callback(config, handler='get_config')
if not enable:
config.find('.//*duplicate-mac-timer').set('operation', 'delete')
return callback(config) |
<SYSTEM_TASK:>
Add RD auto under EVPN instance.
<END_TASK>
<USER_TASK:>
Description:
def evpn_instance_rd_auto(self, **kwargs):
"""
Add RD auto under EVPN instance.
Args:
rbridge_id: Rbrdige id .
instance_name: EVPN instance name.
Returns:
True if command completes successfully or False if not.
Raises:
None
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output=dev.interface.evpn_instance_rd_auto(
... evpn_instance_name='100',
... rbridge_id='1')
""" |
config = ET.Element("config")
rbridge_id = ET.SubElement(config, "rbridge-id",
xmlns="urn:brocade.com"
":mgmt:brocade-rbridge")
rbridge_id_key = ET.SubElement(rbridge_id, "rbridge-id")
rbridge_id_key.text = kwargs.pop('rbridge_id')
evpn_instance = ET.SubElement(rbridge_id, "evpn-instance",
xmlns="urn:brocade.com:mgmt:brocade-bgp")
instance_name_key = ET.SubElement(evpn_instance, "instance-name")
instance_name_key.text = kwargs.pop('instance_name')
route_distinguisher = ET.SubElement(evpn_instance,
"route-distinguisher")
ET.SubElement(route_distinguisher, "auto")
callback = kwargs.pop('callback', self._callback)
return callback(config) |
<SYSTEM_TASK:>
Set nsx-controller IP
<END_TASK>
<USER_TASK:>
Description:
def set_nsxcontroller_ip(self, **kwargs):
"""
Set nsx-controller IP
Args:
IP (str): IPV4 address.
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
None
""" |
name = kwargs.pop('name')
ip_addr = str((kwargs.pop('ip_addr', None)))
nsxipaddress = ip_interface(unicode(ip_addr))
if nsxipaddress.version != 4:
raise ValueError('NSX Controller ip must be IPV4')
ip_args = dict(name=name, address=ip_addr)
method_name = 'nsx_controller_connection_addr_address'
method_class = self._brocade_tunnels
nsxcontroller_attr = getattr(method_class, method_name)
config = nsxcontroller_attr(**ip_args)
output = self._callback(config)
return output |
<SYSTEM_TASK:>
Activate NSX Controller
<END_TASK>
<USER_TASK:>
Description:
def activate_nsxcontroller(self, **kwargs):
"""
Activate NSX Controller
Args:
name (str): nsxcontroller name
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
None
""" |
name = kwargs.pop('name')
name_args = dict(name=name)
method_name = 'nsx_controller_activate'
method_class = self._brocade_tunnels
nsxcontroller_attr = getattr(method_class, method_name)
config = nsxcontroller_attr(**name_args)
output = self._callback(config)
return output |
<SYSTEM_TASK:>
Set Nsx Controller pot on the switch
<END_TASK>
<USER_TASK:>
Description:
def set_nsxcontroller_port(self, **kwargs):
"""
Set Nsx Controller pot on the switch
Args:
port (int): 1 to 65535.
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
None
""" |
name = kwargs.pop('name')
port = str(kwargs.pop('port'))
port_args = dict(name=name, port=port)
method_name = 'nsx_controller_connection_addr_port'
method_class = self._brocade_tunnels
nsxcontroller_attr = getattr(method_class, method_name)
config = nsxcontroller_attr(**port_args)
output = self._callback(config)
return output |
<SYSTEM_TASK:>
Load tasks from entry points.
<END_TASK>
<USER_TASK:>
Description:
def load_entry_points(self):
"""Load tasks from entry points.""" |
if self.entry_point_group:
task_packages = {}
for item in pkg_resources.iter_entry_points(
group=self.entry_point_group):
# Celery 4.2 requires autodiscover to be called with
# related_name for Python 2.7.
try:
pkg, related_name = item.module_name.rsplit('.', 1)
except ValueError:
warnings.warn(
'The celery task module "{}" was not loaded. '
'Defining modules in bare Python modules is no longer '
'supported due to Celery v4.2 constraints. Please '
'move the module into a Python package.'.format(
item.module_name
),
RuntimeWarning
)
continue
if related_name not in task_packages:
task_packages[related_name] = []
task_packages[related_name].append(pkg)
if task_packages:
for related_name, packages in task_packages.items():
self.celery.autodiscover_tasks(
packages, related_name=related_name, force=True
) |
<SYSTEM_TASK:>
Return a list of current active Celery queues.
<END_TASK>
<USER_TASK:>
Description:
def get_queues(self):
"""Return a list of current active Celery queues.""" |
res = self.celery.control.inspect().active_queues() or dict()
return [result.get('name') for host in res.values() for result in host] |
<SYSTEM_TASK:>
Suspend Celery queues and wait for running tasks to complete.
<END_TASK>
<USER_TASK:>
Description:
def suspend_queues(self, active_queues, sleep_time=10.0):
"""Suspend Celery queues and wait for running tasks to complete.""" |
for queue in active_queues:
self.disable_queue(queue)
while self.get_active_tasks():
time.sleep(sleep_time) |
<SYSTEM_TASK:>
Initialises the Negotiate extension for the given application.
<END_TASK>
<USER_TASK:>
Description:
def init_app(self, app):
"""
Initialises the Negotiate extension for the given application.
""" |
if not hasattr(app, 'extensions'):
app.extensions = {}
service_name = app.config.get('GSSAPI_SERVICE_NAME', 'HTTP')
hostname = app.config.get('GSSAPI_HOSTNAME', socket.getfqdn())
principal = '{}@{}'.format(service_name, hostname)
name = gssapi.Name(principal, gssapi.NameType.hostbased_service)
app.extensions['gssapi'] = {
'creds': gssapi.Credentials(name=name, usage='accept'),
} |
<SYSTEM_TASK:>
Attempts to authenticate the user if a token was provided.
<END_TASK>
<USER_TASK:>
Description:
def authenticate(self):
"""Attempts to authenticate the user if a token was provided.""" |
if request.headers.get('Authorization', '').startswith('Negotiate '):
in_token = base64.b64decode(request.headers['Authorization'][10:])
try:
creds = current_app.extensions['gssapi']['creds']
except KeyError:
raise RuntimeError('flask-gssapi not configured for this app')
ctx = gssapi.SecurityContext(creds=creds, usage='accept')
out_token = ctx.step(in_token)
if ctx.complete:
username = ctx._inquire(initiator_name=True).initiator_name
return str(username), out_token
return None, None |
<SYSTEM_TASK:>
Parse option name.
<END_TASK>
<USER_TASK:>
Description:
def parse(self, name, description):
"""
Parse option name.
:param name: option's name
:param description: option's description
Parsing acceptable names:
* -f: shortname
* --force: longname
* -f, --force: shortname and longname
* -o <output>: shortname and a required value
* -o, --output [output]: shortname, longname and optional value
Parsing default value from description:
* source directory, default: src
* source directory, default: [src]
* source directory, default: <src>
""" |
name = name.strip()
if '<' in name:
self.required = True
self.boolean = False
name = name[:name.index('<')].strip()
elif '[' in name:
self.required = False
self.boolean = False
name = name[:name.index('[')].strip()
else:
self.required = False
self.boolean = True
regex = re.compile(r'(-\w)?(?:\,\s*)?(--[\w\-]+)?')
m = regex.findall(name)
if not m:
raise ValueError('Invalid Option: %s', name)
shortname, longname = m[0]
if not shortname and not longname:
raise ValueError('Invalid Option: %s', name)
self.shortname = shortname
self.longname = longname
# parse store key
if longname and longname.startswith('--no-'):
self.key = longname[5:]
elif longname:
self.key = longname[2:]
else:
self.key = shortname
if self.boolean:
# boolean don't need to parse from description
if longname and longname.startswith('--no-'):
self.default = True
else:
self.default = False
return self
if not description:
self.default = None
return self
# parse default value from description
regex = re.compile(r'\sdefault:(.*)$')
m = regex.findall(description)
if not m:
self.default = None
return self
# if it has a default value, it is not required
self.required = False
value = m[0].strip()
if value.startswith('<') and value.endswith('>'):
value = value[1:-1]
elif value.startswith('[') and value.endswith(']'):
value = value[1:-1]
self.default = value.strip()
return self |
<SYSTEM_TASK:>
Transform the option value to python data.
<END_TASK>
<USER_TASK:>
Description:
def to_python(self, value=None):
"""
Transform the option value to python data.
""" |
if value is None:
return self.default
if self.resolve:
return self.resolve(value)
return value |
<SYSTEM_TASK:>
Get parsed result.
<END_TASK>
<USER_TASK:>
Description:
def get(self, key):
"""
Get parsed result.
After :func:`parse` the argv, we can get the parsed results::
# command.option('-f', 'description of -f')
command.get('-f')
command.get('verbose')
# we can also get ``verbose``: command.verbose
""" |
value = self._results.get(key)
if value is not None:
return value
# get from option default value
option = list(filter(lambda o: o.key == key, self._option_list))
if not option:
raise ValueError('No such option: %s' % key)
option = option[0]
return option.default |
<SYSTEM_TASK:>
Add or get option.
<END_TASK>
<USER_TASK:>
Description:
def option(self, name, description=None, action=None, resolve=None):
"""
Add or get option.
Here are some examples::
command.option('-v, --verbose', 'show more log')
command.option('--tag <tag>', 'tag of the package')
command.option('-s, --source <source>', 'the source repo')
:param name: arguments of the option
:param description: description of the option
:param action: a function to be invoked
:param resolve: a function to resolve the data
""" |
if isinstance(name, Option):
option = name
else:
name = name.strip()
option = Option(
name=name, description=description,
action=action, resolve=resolve,
)
self._option_list.append(option)
return self |
<SYSTEM_TASK:>
Parse options with the argv
<END_TASK>
<USER_TASK:>
Description:
def parse_options(self, arg):
"""
Parse options with the argv
:param arg: one arg from argv
""" |
if not arg.startswith('-'):
return False
value = None
if '=' in arg:
arg, value = arg.split('=')
for option in self._option_list:
if arg not in (option.shortname, option.longname):
continue
action = option.action
if action:
action()
if option.key == option.shortname:
self._results[option.key] = True
return True
if option.boolean and option.default:
self._results[option.key] = False
return True
if option.boolean:
self._results[option.key] = True
return True
# has tag, it should has value
if not value:
if self._argv:
value = self._argv[0]
self._argv = self._argv[1:]
if not value:
raise RuntimeError('Missing value for: %s' % option.name)
self._results[option.key] = option.to_python(value)
return True
return False |
<SYSTEM_TASK:>
Parse argv of terminal
<END_TASK>
<USER_TASK:>
Description:
def parse(self, argv=None):
"""
Parse argv of terminal
:param argv: default is sys.argv
""" |
if not argv:
argv = sys.argv
elif isinstance(argv, str):
argv = argv.split()
self._argv = argv[1:]
if not self._argv:
self.validate_options()
if self._command_func:
self._command_func(**self._results)
return True
return False
cmd = self._argv[0]
if not cmd.startswith('-'):
# parse subcommands
for command in self._command_list:
if isinstance(command, Command) and command._name == cmd:
command._parent = self
return command.parse(self._argv)
_positional_index = 0
while self._argv:
arg = self._argv[0]
self._argv = self._argv[1:]
if not self.parse_options(arg):
self._args_results.append(arg)
if len(self._positional_list) > _positional_index:
# positional arguments
key = self._positional_list[_positional_index]
self._results[key] = arg
_positional_index += 1
# validate
self.validate_options()
if self._parent and isinstance(self._parent, Command):
self._parent._args_results = self._args_results
if self._command_func:
self._command_func(**self._results)
return True
return False |
<SYSTEM_TASK:>
Print the program version.
<END_TASK>
<USER_TASK:>
Description:
def print_version(self):
"""
Print the program version.
""" |
if not self._version:
return self
if not self._title:
print(' %s %s' % (self._name, self._version))
return self
print(' %s (%s %s)' % (self._title, self._name, self._version))
return self |
<SYSTEM_TASK:>
Print the help menu.
<END_TASK>
<USER_TASK:>
Description:
def print_help(self):
"""
Print the help menu.
""" |
print('\n %s %s' % (self._title or self._name, self._version or ''))
if self._usage:
print('\n %s' % self._usage)
else:
cmd = self._name
if hasattr(self, '_parent') and isinstance(self._parent, Command):
cmd = '%s %s' % (self._parent._name, cmd)
if self._command_list:
usage = 'Usage: %s <command> [option]' % cmd
else:
usage = 'Usage: %s [option]' % cmd
pos = ' '.join(['<%s>' % name for name in self._positional_list])
print('\n %s %s' % (usage, pos))
arglen = max(len(o.name) for o in self._option_list)
arglen += 2
self.print_title('\n Options:\n')
for o in self._option_list:
print(' %s %s' % (_pad(o.name, arglen), o.description or ''))
print('')
if self._command_list:
self.print_title(' Commands:\n')
for cmd in self._command_list:
if isinstance(cmd, Command):
name = _pad(cmd._name, arglen)
desc = cmd._description or ''
print(' %s %s' % (_pad(name, arglen), desc))
print('')
if self._help_footer:
print(self._help_footer)
print('')
return self |
<SYSTEM_TASK:>
Configures device's Router ID.
<END_TASK>
<USER_TASK:>
Description:
def router_id(self, **kwargs):
"""Configures device's Router ID.
Args:
router_id (str): Router ID for the device.
rbridge_id (str): The rbridge ID of the device on which BGP will be
configured in a VCS fabric.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `router_id` is not specified.
Examples:
>>> import pynos.device
>>> conn = ('10.24.39.211', '22')
>>> auth = ('admin', 'password')
>>> with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.system.router_id(router_id='10.24.39.211',
... rbridge_id='225')
... dev.system.router_id() # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
router_id = kwargs.pop('router_id')
rbridge_id = kwargs.pop('rbridge_id', '1')
callback = kwargs.pop('callback', self._callback)
rid_args = dict(rbridge_id=rbridge_id, router_id=router_id)
config = self._rbridge.rbridge_id_ip_rtm_config_router_id(**rid_args)
return callback(config) |
<SYSTEM_TASK:>
Configures device's rbridge ID. Setting this property will need
<END_TASK>
<USER_TASK:>
Description:
def rbridge_id(self, **kwargs):
"""Configures device's rbridge ID. Setting this property will need
a switch reboot
Args:
rbridge_id (str): The rbridge ID of the device on which BGP will be
configured in a VCS fabric.
get (bool): Get config instead of editing config. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `rbridge_id` is not specified.
Examples:
>>> import pynos.device
>>> conn = ('10.24.39.211', '22')
>>> auth = ('admin', 'password')
>>> with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.system.rbridge_id(rbridge_id='225')
... output = dev.system.rbridge_id(rbridge_id='225', get=True)
... dev.system.rbridge_id() # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
is_get_config = kwargs.pop('get', False)
if not is_get_config:
rbridge_id = kwargs.pop('rbridge_id')
else:
rbridge_id = ''
callback = kwargs.pop('callback', self._callback)
rid_args = dict(rbridge_id=rbridge_id)
rid = getattr(self._rbridge,
'rbridge_id_rbridge_id')
config = rid(**rid_args)
if is_get_config:
return callback(config, handler='get_config')
return callback(config) |
<SYSTEM_TASK:>
Add the HW map only if it doesn't exist for a given key, and no address collisions
<END_TASK>
<USER_TASK:>
Description:
def add(self, new_hw_map):
"""
Add the HW map only if it doesn't exist for a given key, and no address collisions
""" |
new_route = new_hw_map.route
if new_route in self.raw_maps:
raise KeyError("HW Map already exists: {0:s}".format(new_hw_map.route))
common_addresses = set(self).intersection(new_hw_map)
if common_addresses:
raise ValueError("An address in {0:s} already exists in the manager".format(new_route))
# all ok, add it all
self.raw_maps[new_route] = new_hw_map
self.update(new_hw_map) |
<SYSTEM_TASK:>
Remove the route entirely.
<END_TASK>
<USER_TASK:>
Description:
def subtract(self, route):
"""
Remove the route entirely.
""" |
for address in self.raw_maps.pop(route, NullHardwareMap()).iterkeys():
self.pop(address, NullHardwareNode()) |
<SYSTEM_TASK:>
Watches for filesystem changes and compiles SCSS to CSS
<END_TASK>
<USER_TASK:>
Description:
def watch(source_path, dest_path):
"""Watches for filesystem changes and compiles SCSS to CSS
This is an async function.
:param str source_path: The source directory to watch. All .scss files are
monitored.
:param str dest_path: The destination directory where the resulting CSS
files should go. The filename will be identical to
the original, except the extension will be `.css`.
""" |
# Setup Watchdog
handler = FileSystemEvents(source_path, dest_path)
# Always run initial compile
handler.compile_scss()
observer = Observer(timeout=5000)
observer.schedule(handler, path=source_path, recursive=True)
observer.start() |
<SYSTEM_TASK:>
Add VLAN Interface. VLAN interfaces are required for VLANs even when
<END_TASK>
<USER_TASK:>
Description:
def add_vlan_int(self, vlan_id):
"""
Add VLAN Interface. VLAN interfaces are required for VLANs even when
not wanting to use the interface for any L3 features.
Args:
vlan_id: ID for the VLAN interface being created. Value of 2-4096.
Returns:
True if command completes successfully or False if not.
Raises:
None
""" |
config = ET.Element('config')
vlinterface = ET.SubElement(config, 'interface-vlan',
xmlns=("urn:brocade.com:mgmt:"
"brocade-interface"))
interface = ET.SubElement(vlinterface, 'interface')
vlan = ET.SubElement(interface, 'vlan')
name = ET.SubElement(vlan, 'name')
name.text = vlan_id
try:
self._callback(config)
return True
# TODO add logging and narrow exception window.
except Exception as error:
logging.error(error)
return False |
<SYSTEM_TASK:>
Change an interface's operation to L3.
<END_TASK>
<USER_TASK:>
Description:
def disable_switchport(self, inter_type, inter):
"""
Change an interface's operation to L3.
Args:
inter_type: The type of interface you want to configure. Ex.
tengigabitethernet, gigabitethernet, fortygigabitethernet.
inter: The ID for the interface you want to configure. Ex. 1/0/1
Returns:
True if command completes successfully or False if not.
Raises:
None
""" |
config = ET.Element('config')
interface = ET.SubElement(config, 'interface',
xmlns=("urn:brocade.com:mgmt:"
"brocade-interface"))
int_type = ET.SubElement(interface, inter_type)
name = ET.SubElement(int_type, 'name')
name.text = inter
ET.SubElement(int_type, 'switchport-basic', operation='delete')
try:
self._callback(config)
return True
# TODO add logging and narrow exception window.
except Exception as error:
logging.error(error)
return False |
<SYSTEM_TASK:>
Add a L2 Interface to a specific VLAN.
<END_TASK>
<USER_TASK:>
Description:
def access_vlan(self, inter_type, inter, vlan_id):
"""
Add a L2 Interface to a specific VLAN.
Args:
inter_type: The type of interface you want to configure. Ex.
tengigabitethernet, gigabitethernet, fortygigabitethernet.
inter: The ID for the interface you want to configure. Ex. 1/0/1
vlan_id: ID for the VLAN interface being modified. Value of 2-4096.
Returns:
True if command completes successfully or False if not.
Raises:
None
""" |
config = ET.Element('config')
interface = ET.SubElement(config, 'interface',
xmlns=("urn:brocade.com:mgmt:"
"brocade-interface"))
int_type = ET.SubElement(interface, inter_type)
name = ET.SubElement(int_type, 'name')
name.text = inter
switchport = ET.SubElement(int_type, 'switchport')
access = ET.SubElement(switchport, 'access')
accessvlan = ET.SubElement(access, 'accessvlan')
accessvlan.text = vlan_id
try:
self._callback(config)
return True
# TODO add logging and narrow exception window.
except Exception as error:
logging.error(error)
return False |
<SYSTEM_TASK:>
Set IP address of a L3 interface.
<END_TASK>
<USER_TASK:>
Description:
def set_ip(self, inter_type, inter, ip_addr):
"""
Set IP address of a L3 interface.
Args:
inter_type: The type of interface you want to configure. Ex.
tengigabitethernet, gigabitethernet, fortygigabitethernet.
inter: The ID for the interface you want to configure. Ex. 1/0/1
ip_addr: IP Address in <prefix>/<bits> format. Ex: 10.10.10.1/24
Returns:
True if command completes successfully or False if not.
Raises:
None
""" |
config = ET.Element('config')
interface = ET.SubElement(config, 'interface',
xmlns=("urn:brocade.com:mgmt:"
"brocade-interface"))
intert = ET.SubElement(interface, inter_type)
name = ET.SubElement(intert, 'name')
name.text = inter
ipel = ET.SubElement(intert, 'ip')
ip_config = ET.SubElement(
ipel, 'ip-config',
xmlns="urn:brocade.com:mgmt:brocade-ip-config"
)
address = ET.SubElement(ip_config, 'address')
ipaddr = ET.SubElement(address, 'address')
ipaddr.text = ip_addr
try:
self._callback(config)
return True
# TODO add logging and narrow exception window.
except Exception as error:
logging.error(error)
return False |
<SYSTEM_TASK:>
Remove a port channel interface.
<END_TASK>
<USER_TASK:>
Description:
def remove_port_channel(self, **kwargs):
"""
Remove a port channel interface.
Args:
port_int (str): port-channel number (1, 2, 3, etc).
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `port_int` is not passed.
ValueError: if `port_int` is invalid.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.channel_group(name='225/0/20',
... int_type='tengigabitethernet',
... port_int='1', channel_type='standard', mode='active')
... output = dev.interface.remove_port_channel(
... port_int='1')
""" |
port_int = kwargs.pop('port_int')
callback = kwargs.pop('callback', self._callback)
if re.search('^[0-9]{1,4}$', port_int) is None:
raise ValueError('%s must be in the format of x for port channel '
'interfaces.' % repr(port_int))
port_channel = getattr(self._interface, 'interface_port_channel_name')
port_channel_args = dict(name=port_int)
config = port_channel(**port_channel_args)
delete_channel = config.find('.//*port-channel')
delete_channel.set('operation', 'delete')
return callback(config) |
<SYSTEM_TASK:>
Set IP Address on an Interface.
<END_TASK>
<USER_TASK:>
Description:
def ip_address(self, **kwargs):
"""
Set IP Address on an Interface.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet etc).
name (str): Name of interface id.
(For interface: 1/0/5, 1/0/10 etc).
ip_addr (str): IPv4/IPv6 Virtual IP Address..
Ex: 10.10.10.1/24 or 2001:db8::/48
delete (bool): True is the IP address is added and False if its to
be deleted (True, False). Default value will be False if not
specified.
rbridge_id (str): rbridge-id for device. Only required when type is
`ve`.
get (bool): Get config instead of editing config. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `int_type`, `name`, or `ip_addr` is not passed.
ValueError: if `int_type`, `name`, or `ip_addr` are invalid.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... int_type = 'tengigabitethernet'
... name = '225/0/4'
... ip_addr = '20.10.10.1/24'
... output = dev.interface.disable_switchport(inter_type=
... int_type, inter=name)
... output = dev.interface.ip_address(int_type=int_type,
... name=name, ip_addr=ip_addr)
... output = dev.interface.ip_address(int_type=int_type,
... name=name, ip_addr=ip_addr, delete=True)
... output = dev.interface.add_vlan_int('86')
... output = dev.interface.ip_address(int_type='ve',
... name='86', ip_addr=ip_addr, rbridge_id='225')
... output = dev.interface.ip_address(int_type='ve',
... name='86', ip_addr=ip_addr, delete=True,
... rbridge_id='225')
... output = dev.interface.ip_address(int_type='loopback',
... name='225', ip_addr='10.225.225.225/32',
... rbridge_id='225')
... output = dev.interface.ip_address(int_type='loopback',
... name='225', ip_addr='10.225.225.225/32', delete=True,
... rbridge_id='225')
... ip_addr = 'fc00:1:3:1ad3:0:0:23:a/64'
... output = dev.interface.ip_address(int_type=int_type,
... name=name, ip_addr=ip_addr)
... output = dev.interface.ip_address(int_type=int_type,
... name=name, ip_addr=ip_addr, delete=True)
... output = dev.interface.ip_address(int_type='ve',
... name='86', ip_addr=ip_addr, rbridge_id='225')
... output = dev.interface.ip_address(int_type='ve',
... name='86', ip_addr=ip_addr, delete=True,
... rbridge_id='225')
""" |
int_type = str(kwargs.pop('int_type').lower())
name = str(kwargs.pop('name'))
ip_addr = str(kwargs.pop('ip_addr'))
delete = kwargs.pop('delete', False)
rbridge_id = kwargs.pop('rbridge_id', '1')
callback = kwargs.pop('callback', self._callback)
valid_int_types = ['gigabitethernet', 'tengigabitethernet', 've',
'fortygigabitethernet', 'hundredgigabitethernet',
'loopback']
if int_type not in valid_int_types:
raise ValueError('int_type must be one of: %s' %
repr(valid_int_types))
ipaddress = ip_interface(unicode(ip_addr))
ip_args = dict(name=name, address=ip_addr)
method_name = None
method_class = self._interface
if ipaddress.version == 4:
method_name = 'interface_%s_ip_ip_config_address_' \
'address' % int_type
elif ipaddress.version == 6:
method_name = 'interface_%s_ipv6_ipv6_config_address_ipv6_' \
'address_address' % int_type
if int_type == 've':
method_name = "rbridge_id_%s" % method_name
method_class = self._rbridge
ip_args['rbridge_id'] = rbridge_id
if not pynos.utilities.valid_vlan_id(name):
raise InvalidVlanId("`name` must be between `1` and `8191`")
elif int_type == 'loopback':
method_name = 'rbridge_id_interface_loopback_ip_ip_config_' \
'address_address'
if ipaddress.version == 6:
method_name = 'rbridge_id_interface_loopback_ipv6_ipv6_' \
'config_address_ipv6_address_address'
method_class = self._rbridge
ip_args['rbridge_id'] = rbridge_id
ip_args['id'] = name
elif not pynos.utilities.valid_interface(int_type, name):
raise ValueError('`name` must be in the format of x/y/z for '
'physical interfaces.')
ip_address_attr = getattr(method_class, method_name)
config = ip_address_attr(**ip_args)
if delete:
config.find('.//*address').set('operation', 'delete')
try:
if kwargs.pop('get', False):
return callback(config, handler='get_config')
else:
return callback(config)
# TODO Setting IP on port channel is not done yet.
except AttributeError:
return None |
<SYSTEM_TASK:>
Get IP Addresses already set on an Interface.
<END_TASK>
<USER_TASK:>
Description:
def get_ip_addresses(self, **kwargs):
"""
Get IP Addresses already set on an Interface.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet etc).
name (str): Name of interface id.
(For interface: 1/0/5, 1/0/10 etc).
version (int): 4 or 6 to represent IPv4 or IPv6 address
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
List of 0 or more IPs configure on the specified interface.
Raises:
KeyError: if `int_type` or `name` is not passed.
ValueError: if `int_type` or `name` are invalid.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... int_type = 'tengigabitethernet'
... name = '225/0/4'
... ip_addr = '20.10.10.1/24'
... version = 4
... output = dev.interface.disable_switchport(inter_type=
... int_type, inter=name)
... output = dev.interface.ip_address(int_type=int_type,
... name=name, ip_addr=ip_addr)
... result = dev.interface.get_ip_addresses(
... int_type=int_type, name=name, version=version)
... assert len(result) >= 1
... output = dev.interface.ip_address(int_type=int_type,
... name=name, ip_addr=ip_addr, delete=True)
... ip_addr = 'fc00:1:3:1ad3:0:0:23:a/64'
... version = 6
... output = dev.interface.ip_address(int_type=int_type,
... name=name, ip_addr=ip_addr)
... result = dev.interface.get_ip_addresses(
... int_type=int_type, name=name, version=version)
... assert len(result) >= 1
... output = dev.interface.ip_address(int_type=int_type,
... name=name, ip_addr=ip_addr, delete=True)
""" |
int_type = str(kwargs.pop('int_type').lower())
name = str(kwargs.pop('name'))
version = int(kwargs.pop('version'))
callback = kwargs.pop('callback', self._callback)
valid_int_types = ['gigabitethernet', 'tengigabitethernet',
'fortygigabitethernet', 'hundredgigabitethernet']
if int_type not in valid_int_types:
raise ValueError('int_type must be one of: %s' %
repr(valid_int_types))
method_name = None
method_class = self._interface
if version == 4:
method_name = 'interface_%s_ip_ip_config_address_' \
'address' % int_type
elif version == 6:
method_name = 'interface_%s_ipv6_ipv6_config_address_ipv6_' \
'address_address' % int_type
if not pynos.utilities.valid_interface(int_type, name):
raise ValueError('`name` must be in the format of x/y/z for '
'physical interfaces.')
ip_args = dict(name=name, address='')
ip_address_attr = getattr(method_class, method_name)
config = ip_address_attr(**ip_args)
output = callback(config, handler='get_config')
result = []
if version == 4:
for item in output.data.findall(
'.//{*}address/{*}address'):
result.append(item.text)
elif version == 6:
for item in output.data.findall(
'.//{*}address/{*}ipv6-address/{'
'*}address'):
result.append(item.text)
return result |
<SYSTEM_TASK:>
Set interface description.
<END_TASK>
<USER_TASK:>
Description:
def description(self, **kwargs):
"""Set interface description.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc)
name (str): Name of interface. (1/0/5, 1/0/10, etc)
desc (str): The description of the interface.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `int_type`, `name`, or `desc` is not specified.
ValueError: if `name`, `int_type`, or `desc` is not a valid
value.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.description(
... int_type='tengigabitethernet',
... name='225/0/38',
... desc='test')
... dev.interface.description()
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
int_type = str(kwargs.pop('int_type').lower())
name = str(kwargs.pop('name'))
desc = str(kwargs.pop('desc'))
callback = kwargs.pop('callback', self._callback)
int_types = [
'gigabitethernet',
'tengigabitethernet',
'fortygigabitethernet',
'hundredgigabitethernet',
'port_channel',
'vlan'
]
if int_type not in int_types:
raise ValueError("`int_type` must be one of: %s" % repr(int_types))
desc_args = dict(name=name, description=desc)
if int_type == "vlan":
if not pynos.utilities.valid_vlan_id(name):
raise InvalidVlanId("`name` must be between `1` and `8191`")
config = self._interface.interface_vlan_interface_vlan_description(
**desc_args
)
else:
if not pynos.utilities.valid_interface(int_type, name):
raise ValueError('`name` must be in the format of x/y/z for '
'physical interfaces or x for port channel.')
config = getattr(
self._interface,
'interface_%s_description' % int_type
)(**desc_args)
return callback(config) |
<SYSTEM_TASK:>
Add a secondary PVLAN to a primary PVLAN.
<END_TASK>
<USER_TASK:>
Description:
def vlan_pvlan_association_add(self, **kwargs):
"""Add a secondary PVLAN to a primary PVLAN.
Args:
name (str): VLAN number (1-4094).
sec_vlan (str): The secondary PVLAN.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `name` or `sec_vlan` is not specified.
ValueError: if `name` or `sec_vlan` is invalid.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> int_type = 'tengigabitethernet'
>>> name = '20'
>>> sec_vlan = '30'
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.private_vlan_type(name=name,
... pvlan_type='primary')
... output = dev.interface.private_vlan_type(name=sec_vlan,
... pvlan_type='isolated')
... output = dev.interface.vlan_pvlan_association_add(
... name=name, sec_vlan=sec_vlan)
... dev.interface.vlan_pvlan_association_add()
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
name = kwargs.pop('name')
sec_vlan = kwargs.pop('sec_vlan')
callback = kwargs.pop('callback', self._callback)
if not pynos.utilities.valid_vlan_id(name):
raise InvalidVlanId("Incorrect name value.")
if not pynos.utilities.valid_vlan_id(sec_vlan):
raise InvalidVlanId("`sec_vlan` must be between `1` and `8191`.")
pvlan_args = dict(name=name, sec_assoc_add=sec_vlan)
pvlan_assoc = getattr(self._interface,
'interface_vlan_interface_vlan_'
'private_vlan_association_sec_assoc_add')
config = pvlan_assoc(**pvlan_args)
return callback(config) |
<SYSTEM_TASK:>
Set interface PVLAN association.
<END_TASK>
<USER_TASK:>
Description:
def pvlan_host_association(self, **kwargs):
"""Set interface PVLAN association.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc)
name (str): Name of interface. (1/0/5, 1/0/10, etc)
pri_vlan (str): The primary PVLAN.
sec_vlan (str): The secondary PVLAN.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `int_type`, `name`, `pri_vlan`, or `sec_vlan` is not
specified.
ValueError: if `int_type`, `name`, `pri_vlan`, or `sec_vlan`
is invalid.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> int_type = 'tengigabitethernet'
>>> name = '225/0/38'
>>> pri_vlan = '75'
>>> sec_vlan = '100'
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.private_vlan_type(name=pri_vlan,
... pvlan_type='primary')
... output = dev.interface.private_vlan_type(name=sec_vlan,
... pvlan_type='isolated')
... output = dev.interface.vlan_pvlan_association_add(
... name=pri_vlan, sec_vlan=sec_vlan)
... output = dev.interface.enable_switchport(int_type,
... name)
... output = dev.interface.private_vlan_mode(
... int_type=int_type, name=name, mode='host')
... output = dev.interface.pvlan_host_association(
... int_type=int_type, name=name, pri_vlan=pri_vlan,
... sec_vlan=sec_vlan)
... dev.interface.pvlan_host_association()
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
int_type = kwargs.pop('int_type').lower()
name = kwargs.pop('name')
pri_vlan = kwargs.pop('pri_vlan')
sec_vlan = kwargs.pop('sec_vlan')
callback = kwargs.pop('callback', self._callback)
int_types = ['gigabitethernet', 'tengigabitethernet',
'fortygigabitethernet', 'hundredgigabitethernet',
'port_channel']
if int_type not in int_types:
raise ValueError("Incorrect int_type value.")
if not pynos.utilities.valid_interface(int_type, name):
raise ValueError('`name` must be in the format of x/y/z for '
'physical interfaces or x for port channel.')
if not pynos.utilities.valid_vlan_id(pri_vlan):
raise InvalidVlanId("`sec_vlan` must be between `1` and `4095`.")
if not pynos.utilities.valid_vlan_id(sec_vlan):
raise InvalidVlanId("`sec_vlan` must be between `1` and `4095`.")
pvlan_args = dict(name=name, host_pri_pvlan=pri_vlan)
associate_pvlan = getattr(self._interface,
'interface_%s_switchport_private_vlan_'
'host_association_host_pri_pvlan' %
int_type)
config = associate_pvlan(**pvlan_args)
sec_assoc = config.find('.//*host-association')
sec_assoc = ET.SubElement(sec_assoc, 'host-sec-pvlan')
sec_assoc.text = sec_vlan
return callback(config) |
<SYSTEM_TASK:>
Set tagging of native VLAN on trunk.
<END_TASK>
<USER_TASK:>
Description:
def tag_native_vlan(self, **kwargs):
"""Set tagging of native VLAN on trunk.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc)
name (str): Name of interface. (1/0/5, 1/0/10, etc)
mode (str): Trunk port mode (trunk, trunk-no-default-native).
enabled (bool): Is tagging of the VLAN enabled on trunks?
(True, False)
callback (function): A function executed upon completion oj the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `int_type`, `name`, or `state` is not specified.
ValueError: if `int_type`, `name`, or `state` is not valid.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.trunk_mode(
... int_type='tengigabitethernet',
... name='225/0/38', mode='trunk')
... output = dev.interface.tag_native_vlan(name='225/0/38',
... int_type='tengigabitethernet')
... output = dev.interface.tag_native_vlan(
... int_type='tengigabitethernet',
... name='225/0/38', enabled=False)
... dev.interface.tag_native_vlan()
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
int_type = kwargs.pop('int_type').lower()
name = kwargs.pop('name')
enabled = kwargs.pop('enabled', True)
callback = kwargs.pop('callback', self._callback)
int_types = ['gigabitethernet', 'tengigabitethernet',
'fortygigabitethernet', 'hundredgigabitethernet',
'port_channel']
if int_type not in int_types:
raise ValueError("Incorrect int_type value.")
if not pynos.utilities.valid_interface(int_type, name):
raise ValueError('`name` must be in the format of x/y/z for '
'physical interfaces or x for port channel.')
if not isinstance(enabled, bool):
raise ValueError("Invalid state.")
tag_args = dict(name=name)
tag_native_vlan = getattr(self._interface, 'interface_%s_switchport_'
'trunk_tag_native_vlan' % int_type)
config = tag_native_vlan(**tag_args)
if not enabled:
untag = config.find('.//*native-vlan')
untag.set('operation', 'delete')
try:
return callback(config)
# TODO: Catch existing 'no switchport tag native-vlan'
except AttributeError:
return None |
<SYSTEM_TASK:>
Switchport private VLAN mapping.
<END_TASK>
<USER_TASK:>
Description:
def switchport_pvlan_mapping(self, **kwargs):
"""Switchport private VLAN mapping.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc)
name (str): Name of interface. (1/0/5, 1/0/10, etc)
pri_vlan (str): The primary PVLAN.
sec_vlan (str): The secondary PVLAN.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `int_type`, `name`, or `mode` is not specified.
ValueError: if `int_type`, `name`, or `mode` is invalid.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> int_type = 'tengigabitethernet'
>>> name = '225/0/37'
>>> pri_vlan = '3000'
>>> sec_vlan = ['3001', '3002']
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.private_vlan_type(name=pri_vlan,
... pvlan_type='primary')
... output = dev.interface.enable_switchport(int_type,
... name)
... output = dev.interface.private_vlan_mode(
... int_type=int_type, name=name, mode='trunk_promiscuous')
... for spvlan in sec_vlan:
... output = dev.interface.private_vlan_type(
... name=spvlan, pvlan_type='isolated')
... output = dev.interface.vlan_pvlan_association_add(
... name=pri_vlan, sec_vlan=spvlan)
... output = dev.interface.switchport_pvlan_mapping(
... int_type=int_type, name=name, pri_vlan=pri_vlan,
... sec_vlan=spvlan)
... dev.interface.switchport_pvlan_mapping()
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
int_type = kwargs.pop('int_type').lower()
name = kwargs.pop('name')
pri_vlan = kwargs.pop('pri_vlan')
sec_vlan = kwargs.pop('sec_vlan')
callback = kwargs.pop('callback', self._callback)
int_types = ['gigabitethernet', 'tengigabitethernet',
'fortygigabitethernet', 'hundredgigabitethernet',
'port_channel']
if int_type not in int_types:
raise ValueError("`int_type` must be one of: %s" % repr(int_types))
if not pynos.utilities.valid_interface(int_type, name):
raise ValueError("`name` must be in the format of x/y/x for "
"physical interfaces or x for port channel.")
if not pynos.utilities.valid_vlan_id(pri_vlan, extended=True):
raise InvalidVlanId("`pri_vlan` must be between `1` and `4096`")
if not pynos.utilities.valid_vlan_id(sec_vlan, extended=True):
raise InvalidVlanId("`sec_vlan` must be between `1` and `4096`")
pvlan_args = dict(name=name,
promis_pri_pvlan=pri_vlan,
promis_sec_pvlan_range=sec_vlan)
pvlan_mapping = getattr(self._interface,
'interface_gigabitethernet_switchport_'
'private_vlan_mapping_promis_sec_pvlan_range')
config = pvlan_mapping(**pvlan_args)
return callback(config) |
<SYSTEM_TASK:>
Set interface mtu.
<END_TASK>
<USER_TASK:>
Description:
def mtu(self, **kwargs):
"""Set interface mtu.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc)
name (str): Name of interface. (1/0/5, 1/0/10, etc)
mtu (str): Value between 1522 and 9216
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `int_type`, `name`, or `mtu` is not specified.
ValueError: if `int_type`, `name`, or `mtu` is invalid.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.mtu(mtu='1666',
... int_type='tengigabitethernet', name='225/0/38')
... dev.interface.mtu() # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
int_type = kwargs.pop('int_type').lower()
name = kwargs.pop('name')
mtu = kwargs.pop('mtu')
callback = kwargs.pop('callback', self._callback)
int_types = [
'gigabitethernet',
'tengigabitethernet',
'fortygigabitethernet',
'hundredgigabitethernet',
'port_channel'
]
if int_type not in int_types:
raise ValueError("Incorrect int_type value.")
minimum_mtu = 1522
maximum_mtu = 9216
if int(mtu) < minimum_mtu or int(mtu) > maximum_mtu:
raise ValueError("Incorrect mtu value 1522-9216")
mtu_args = dict(name=name, mtu=mtu)
if not pynos.utilities.valid_interface(int_type, name):
raise ValueError('`name` must be in the format of x/y/z for '
'physical interfaces or x for port channel.')
config = getattr(
self._interface,
'interface_%s_mtu' % int_type
)(**mtu_args)
return callback(config) |
<SYSTEM_TASK:>
Set fabric ISL state.
<END_TASK>
<USER_TASK:>
Description:
def fabric_isl(self, **kwargs):
"""Set fabric ISL state.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc)
name (str): Name of interface. (1/0/5, 1/0/10, etc)
enabled (bool): Is fabric ISL state enabled? (True, False)
get (bool): Get config instead of editing config. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `int_type`, `name`, or `state` is not specified.
ValueError: if `int_type`, `name`, or `state` is not a valid value.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.fabric_isl(
... int_type='tengigabitethernet',
... name='225/0/40',
... enabled=False)
... dev.interface.fabric_isl()
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
int_type = str(kwargs.pop('int_type').lower())
name = str(kwargs.pop('name'))
enabled = kwargs.pop('enabled', True)
callback = kwargs.pop('callback', self._callback)
int_types = [
'tengigabitethernet',
'fortygigabitethernet',
'hundredgigabitethernet'
]
if int_type not in int_types:
raise ValueError("`int_type` must be one of: %s" %
repr(int_types))
if not isinstance(enabled, bool):
raise ValueError('`enabled` must be `True` or `False`.')
fabric_isl_args = dict(name=name)
if not pynos.utilities.valid_interface(int_type, name):
raise ValueError("`name` must match `^[0-9]{1,3}/[0-9]{1,3}/[0-9]"
"{1,3}$`")
config = getattr(
self._interface,
'interface_%s_fabric_fabric_isl_fabric_isl_enable' % int_type
)(**fabric_isl_args)
if not enabled:
fabric_isl = config.find('.//*fabric-isl')
fabric_isl.set('operation', 'delete')
if kwargs.pop('get', False):
return callback(config, handler='get_config')
else:
return callback(config) |
<SYSTEM_TASK:>
Disable IPv6 Router Advertisements
<END_TASK>
<USER_TASK:>
Description:
def v6_nd_suppress_ra(self, **kwargs):
"""Disable IPv6 Router Advertisements
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc)
name (str): Name of interface. (1/0/5, 1/0/10, etc)
rbridge_id (str): rbridge-id for device. Only required when type is
`ve`.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `int_type`, `name`, or `rbridge_id` is not specified.
ValueError: if `int_type`, `name`, or `rbridge_id` is not a valid
value.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.add_vlan_int('10')
... output = dev.interface.v6_nd_suppress_ra(name='10',
... int_type='ve', rbridge_id='225')
... dev.interface.v6_nd_suppress_ra()
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
int_type = str(kwargs.pop('int_type').lower())
name = str(kwargs.pop('name'))
callback = kwargs.pop('callback', self._callback)
int_types = [
'gigabitethernet',
'tengigabitethernet',
'fortygigabitethernet',
'hundredgigabitethernet',
've'
]
if int_type not in int_types:
raise ValueError("`int_type` must be one of: %s" % repr(int_types))
if int_type == "ve":
if not pynos.utilities.valid_vlan_id(name):
raise ValueError("`name` must be between `1` and `8191`")
rbridge_id = kwargs.pop('rbridge_id', "1")
nd_suppress_args = dict(name=name, rbridge_id=rbridge_id)
nd_suppress = getattr(self._rbridge,
'rbridge_id_interface_ve_ipv6_'
'ipv6_nd_ra_ipv6_intf_cmds_'
'nd_suppress_ra_suppress_ra_all')
config = nd_suppress(**nd_suppress_args)
else:
if not pynos.utilities.valid_interface(int_type, name):
raise ValueError("`name` must match "
"`^[0-9]{1,3}/[0-9]{1,3}/[0-9]{1,3}$`")
nd_suppress_args = dict(name=name)
nd_suppress = getattr(self._interface,
'interface_%s_ipv6_ipv6_nd_ra_'
'ipv6_intf_cmds_nd_suppress_ra_'
'suppress_ra_all' % int_type)
config = nd_suppress(**nd_suppress_args)
return callback(config) |
<SYSTEM_TASK:>
Set VRRP priority.
<END_TASK>
<USER_TASK:>
Description:
def vrrp_priority(self, **kwargs):
"""Set VRRP priority.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc).
name (str): Name of interface. (1/0/5, 1/0/10, etc).
vrid (str): VRRPv3 ID.
priority (str): VRRP Priority.
ip_version (str): Version of IP (4, 6).
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `int_type`, `name`, `vrid`, `priority`, or
`ip_version` is not passed.
ValueError: if `int_type`, `name`, `vrid`, `priority`, or
`ip_version` is invalid.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.anycast_mac(rbridge_id='225',
... mac='aabb.ccdd.eeff', delete=True)
... output = dev.services.vrrp(ip_version='6',
... enabled=True, rbridge_id='225')
... output = dev.services.vrrp(enabled=True,
... rbridge_id='225')
... output = dev.interface.set_ip('tengigabitethernet',
... '225/0/18', '10.1.1.2/24')
... output = dev.interface.ip_address(name='225/0/18',
... int_type='tengigabitethernet',
... ip_addr='2001:4818:f000:1ab:cafe:beef:1000:2/64')
... dev.interface.vrrp_vip(int_type='tengigabitethernet',
... name='225/0/18', vrid='1', vip='10.1.1.1/24')
... dev.interface.vrrp_vip(int_type='tengigabitethernet',
... name='225/0/18', vrid='1',
... vip='fe80::cafe:beef:1000:1/64')
... dev.interface.vrrp_vip(int_type='tengigabitethernet',
... name='225/0/18', vrid='1',
... vip='2001:4818:f000:1ab:cafe:beef:1000:1/64')
... dev.interface.vrrp_priority(
... int_type='tengigabitethernet',
... name='225/0/18', vrid='1', ip_version='4',
... priority='66')
... dev.interface.vrrp_priority(
... int_type='tengigabitethernet',
... name='225/0/18', vrid='1', ip_version='6',
... priority='77')
... output = dev.interface.add_vlan_int('88')
... output = dev.interface.ip_address(int_type='ve',
... name='88', ip_addr='172.16.10.1/24', rbridge_id='225')
... output = dev.interface.ip_address(int_type='ve',
... name='88', rbridge_id='225',
... ip_addr='2003:4818:f000:1ab:cafe:beef:1000:2/64')
... dev.interface.vrrp_vip(int_type='ve', name='88',
... vrid='1', vip='172.16.10.2/24', rbridge_id='225')
... dev.interface.vrrp_vip(int_type='ve', name='88',
... rbridge_id='225', vrid='1',
... vip='fe80::dafe:beef:1000:1/64')
... dev.interface.vrrp_vip(int_type='ve', rbridge_id='225',
... name='88', vrid='1',
... vip='2003:4818:f000:1ab:cafe:beef:1000:1/64')
... dev.interface.vrrp_priority(int_type='ve', name='88',
... rbridge_id='225', vrid='1', ip_version='4',
... priority='66')
... dev.interface.vrrp_priority(int_type='ve', name='88',
... rbridge_id='225', vrid='1', ip_version='6',
... priority='77')
... output = dev.services.vrrp(ip_version='6',
... enabled=False, rbridge_id='225')
... output = dev.services.vrrp(enabled=False,
... rbridge_id='225')
""" |
int_type = kwargs.pop('int_type').lower()
name = kwargs.pop('name')
vrid = kwargs.pop('vrid')
priority = kwargs.pop('priority')
ip_version = int(kwargs.pop('ip_version'))
rbridge_id = kwargs.pop('rbridge_id', '1')
callback = kwargs.pop('callback', self._callback)
valid_int_types = ['gigabitethernet', 'tengigabitethernet',
'fortygigabitethernet', 'hundredgigabitethernet',
'port_channel', 've']
vrrp_args = dict(name=name, vrid=vrid, priority=priority)
vrrp_priority = None
method_name = None
method_class = self._interface
if int_type not in valid_int_types:
raise ValueError('`int_type` must be one of: %s' %
repr(valid_int_types))
if ip_version == 4:
vrrp_args['version'] = '3'
method_name = 'interface_%s_vrrp_priority' % int_type
elif ip_version == 6:
method_name = 'interface_%s_ipv6_vrrpv3_group_priority' % int_type
if int_type == 've':
method_name = "rbridge_id_%s" % method_name
if ip_version == 6:
method_name = method_name.replace('group_', '')
method_class = self._rbridge
vrrp_args['rbridge_id'] = rbridge_id
if not pynos.utilities.valid_vlan_id(name):
raise InvalidVlanId("`name` must be between `1` and `8191`")
elif not pynos.utilities.valid_interface(int_type, name):
raise ValueError('`name` must be in the format of x/y/z for '
'physical interfaces or x for port channel.')
vrrp_priority = getattr(method_class, method_name)
config = vrrp_priority(**vrrp_args)
return callback(config) |
<SYSTEM_TASK:>
Set minimum number of links in a port channel.
<END_TASK>
<USER_TASK:>
Description:
def port_channel_minimum_links(self, **kwargs):
"""Set minimum number of links in a port channel.
Args:
name (str): Port-channel number. (1, 5, etc)
minimum_links (str): Minimum number of links in channel group.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `name` or `minimum_links` is not specified.
ValueError: if `name` is not a valid value.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.port_channel_minimum_links(
... name='1', minimum_links='2')
... dev.interface.port_channel_minimum_links()
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
name = str(kwargs.pop('name'))
minimum_links = str(kwargs.pop('minimum_links'))
callback = kwargs.pop('callback', self._callback)
min_links_args = dict(name=name, minimum_links=minimum_links)
if not pynos.utilities.valid_interface('port_channel', name):
raise ValueError("`name` must match `^[0-9]{1,3}${1,3}$`")
config = getattr(
self._interface,
'interface_port_channel_minimum_links'
)(**min_links_args)
return callback(config) |
<SYSTEM_TASK:>
set channel group mode.
<END_TASK>
<USER_TASK:>
Description:
def channel_group(self, **kwargs):
"""set channel group mode.
args:
int_type (str): type of interface. (gigabitethernet,
tengigabitethernet, etc)
name (str): name of interface. (1/0/5, 1/0/10, etc)
port_int (str): port-channel number (1, 2, 3, etc).
channel_type (str): tiype of port-channel (standard, brocade)
mode (str): mode of channel group (active, on, passive).
delete (bool): Removes channel group configuration from this
interface if `delete` is ``True``.
callback (function): a function executed upon completion of the
method. the only parameter passed to `callback` will be the
``elementtree`` `config`.
returns:
return value of `callback`.
raises:
keyerror: if `int_type`, `name`, or `description` is not specified.
valueerror: if `name` or `int_type` are not valid values.
examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.channel_group(name='225/0/20',
... int_type='tengigabitethernet',
... port_int='1', channel_type='standard', mode='active')
... dev.interface.channel_group()
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
int_type = kwargs.pop('int_type').lower()
name = kwargs.pop('name')
channel_type = kwargs.pop('channel_type')
port_int = kwargs.pop('port_int')
mode = kwargs.pop('mode')
delete = kwargs.pop('delete', False)
callback = kwargs.pop('callback', self._callback)
int_types = [
'gigabitethernet',
'tengigabitethernet',
'fortygigabitethernet',
'hundredgigabitethernet'
]
if int_type not in int_types:
raise ValueError("`int_type` must be one of: %s" % repr(int_types))
valid_modes = ['active', 'on', 'passive']
if mode not in valid_modes:
raise ValueError("`mode` must be one of: %s" % repr(valid_modes))
valid_types = ['brocade', 'standard']
if channel_type not in valid_types:
raise ValueError("`channel_type` must be one of: %s" %
repr(valid_types))
if not pynos.utilities.valid_interface('port_channel', port_int):
raise ValueError("incorrect port_int value.")
channel_group_args = dict(name=name, mode=mode)
if not pynos.utilities.valid_interface(int_type, name):
raise ValueError("incorrect name value.")
config = getattr(
self._interface,
'interface_%s_channel_group_mode' % int_type
)(**channel_group_args)
channel_group = config.find('.//*channel-group')
if delete is True:
channel_group.set('operation', 'delete')
else:
ET.SubElement(channel_group, 'port-int').text = port_int
ET.SubElement(channel_group, 'type').text = channel_type
return callback(config) |
<SYSTEM_TASK:>
Ignore VLAG Split.
<END_TASK>
<USER_TASK:>
Description:
def port_channel_vlag_ignore_split(self, **kwargs):
"""Ignore VLAG Split.
Args:
name (str): Port-channel number. (1, 5, etc)
enabled (bool): Is ignore split enabled? (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `name` or `enable` is not specified.
ValueError: if `name` is not a valid value.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.port_channel_vlag_ignore_split(
... name='1', enabled=True)
... dev.interface.port_channel_vlag_ignore_split()
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
name = str(kwargs.pop('name'))
enabled = bool(kwargs.pop('enabled', True))
callback = kwargs.pop('callback', self._callback)
vlag_ignore_args = dict(name=name)
if not pynos.utilities.valid_interface('port_channel', name):
raise ValueError("`name` must match x")
config = getattr(
self._interface,
'interface_port_channel_vlag_ignore_split'
)(**vlag_ignore_args)
if not enabled:
ignore_split = config.find('.//*ignore-split')
ignore_split.set('operation', 'delete')
return callback(config) |
<SYSTEM_TASK:>
Configure VLAN Transport Service.
<END_TASK>
<USER_TASK:>
Description:
def transport_service(self, **kwargs):
"""Configure VLAN Transport Service.
Args:
vlan (str): The VLAN ID.
service_id (str): The transport-service ID.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `vlan` or `service_id` is not specified.
ValueError: if `vlan` is invalid.
Examples:
>>> # Skip due to current work in devel
>>> # TODO: Reenable
>>> def test_transport_service():
... import pynos.device
... switches = ['10.24.39.212', '10.24.39.202']
... auth = ('admin', 'password')
... vlan = '6666'
... service_id = '1'
... for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.add_vlan_int(vlan)
... output = dev.interface.spanning_tree_state(
... int_type='vlan', name=vlan, enabled=False)
... output = dev.interface.transport_service(vlan=vlan,
... service_id=service_id)
... dev.interface.transport_service()
... # doctest: +IGNORE_EXCEPTION_DETAIL
>>> test_transport_service() # doctest: +SKIP
""" |
vlan = kwargs.pop('vlan')
service_id = kwargs.pop('service_id')
callback = kwargs.pop('callback', self._callback)
if not pynos.utilities.valid_vlan_id(vlan, extended=True):
raise InvalidVlanId("vlan must be between `1` and `8191`")
service_args = dict(name=vlan, transport_service=service_id)
transport_service = getattr(self._interface,
'interface_vlan_interface_vlan_'
'transport_service')
config = transport_service(**service_args)
return callback(config) |
<SYSTEM_TASK:>
Set lacp timeout.
<END_TASK>
<USER_TASK:>
Description:
def lacp_timeout(self, **kwargs):
"""Set lacp timeout.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc)
timeout (str): Timeout length. (short, long)
name (str): Name of interface. (1/0/5, 1/0/10, etc)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `int_type`, `name`, or `timeout` is not specified.
ValueError: if `int_type`, `name`, or `timeout is not valid.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> int_type = 'tengigabitethernet'
>>> name = '225/0/39'
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.channel_group(name=name,
... int_type=int_type, port_int='1',
... channel_type='standard', mode='active')
... output = dev.interface.lacp_timeout(name=name,
... int_type=int_type, timeout='long')
... dev.interface.lacp_timeout()
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
int_type = kwargs.pop('int_type').lower()
name = kwargs.pop('name')
timeout = kwargs.pop('timeout')
callback = kwargs.pop('callback', self._callback)
int_types = [
'gigabitethernet',
'tengigabitethernet',
'fortygigabitethernet',
'hundredgigabitethernet'
]
if int_type not in int_types:
raise ValueError("Incorrect int_type value.")
valid_timeouts = ['long', 'short']
if timeout not in valid_timeouts:
raise ValueError("Incorrect timeout value")
timeout_args = dict(name=name, timeout=timeout)
if not pynos.utilities.valid_interface(int_type, name):
raise ValueError("Incorrect name value.")
config = getattr(
self._interface,
'interface_%s_lacp_timeout' % int_type
)(**timeout_args)
return callback(config) |
<SYSTEM_TASK:>
Set interface switchport status.
<END_TASK>
<USER_TASK:>
Description:
def switchport(self, **kwargs):
"""Set interface switchport status.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc)
name (str): Name of interface. (1/0/5, 1/0/10, etc)
enabled (bool): Is the interface enabled? (True, False)
get (bool): Get config instead of editing config. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `int_type` or `name` is not specified.
ValueError: if `name` or `int_type` is not a valid
value.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.switchport(name='225/0/19',
... int_type='tengigabitethernet')
... output = dev.interface.switchport(name='225/0/19',
... int_type='tengigabitethernet', enabled=False)
... dev.interface.switchport()
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
int_type = kwargs.pop('int_type').lower()
name = kwargs.pop('name')
enabled = kwargs.pop('enabled', True)
callback = kwargs.pop('callback', self._callback)
int_types = ['gigabitethernet', 'tengigabitethernet',
'fortygigabitethernet', 'hundredgigabitethernet',
'port_channel', 'vlan']
if int_type not in int_types:
raise ValueError("`int_type` must be one of: %s" % repr(int_types))
if not pynos.utilities.valid_interface(int_type, name):
raise ValueError('`name` must be in the format of x/y/z for '
'physical interfaces or x for port channel.')
switchport_args = dict(name=name)
switchport = getattr(self._interface,
'interface_%s_switchport_basic_basic' % int_type)
config = switchport(**switchport_args)
if not enabled:
config.find('.//*switchport-basic').set('operation', 'delete')
if kwargs.pop('get', False):
return callback(config, handler='get_config')
else:
return callback(config) |
<SYSTEM_TASK:>
Set access VLAN on a port.
<END_TASK>
<USER_TASK:>
Description:
def acc_vlan(self, **kwargs):
"""Set access VLAN on a port.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc)
name (str): Name of interface. (1/0/5, 1/0/10, etc)
vlan (str): VLAN ID to set as the access VLAN.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `int_type`, `name`, or `vlan` is not specified.
ValueError: if `int_type`, `name`, or `vlan` is not valid.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> int_type = 'tengigabitethernet'
>>> name = '225/0/30'
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.add_vlan_int('736')
... output = dev.interface.enable_switchport(int_type,
... name)
... output = dev.interface.acc_vlan(int_type=int_type,
... name=name, vlan='736')
... dev.interface.acc_vlan()
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
int_type = kwargs.pop('int_type')
name = kwargs.pop('name')
vlan = kwargs.pop('vlan')
callback = kwargs.pop('callback', self._callback)
int_types = ['gigabitethernet', 'tengigabitethernet',
'fortygigabitethernet', 'hundredgigabitethernet',
'port_channel']
if int_type not in int_types:
raise ValueError("`int_type` must be one of: %s" % repr(int_types))
if not pynos.utilities.valid_vlan_id(vlan):
raise InvalidVlanId("`name` must be between `1` and `4096`")
if not pynos.utilities.valid_interface(int_type, name):
raise ValueError('`name` must be in the format of x/y/z for '
'physical interfaces or x for port channel.')
vlan_args = dict(name=name, accessvlan=vlan)
access_vlan = getattr(self._interface,
'interface_%s_switchport_access_accessvlan' %
int_type)
config = access_vlan(**vlan_args)
return callback(config) |
<SYSTEM_TASK:>
Creates a new Netconf request based on the last received
<END_TASK>
<USER_TASK:>
Description:
def get_interface_detail_request(last_interface_name,
last_interface_type):
""" Creates a new Netconf request based on the last received
interface name and type when the hasMore flag is true
""" |
request_interface = ET.Element(
'get-interface-detail',
xmlns="urn:brocade.com:mgmt:brocade-interface-ext"
)
if last_interface_name != '':
last_received_int = ET.SubElement(request_interface,
"last-rcvd-interface")
last_int_type_el = ET.SubElement(last_received_int,
"interface-type")
last_int_type_el.text = last_interface_type
last_int_name_el = ET.SubElement(last_received_int,
"interface-name")
last_int_name_el.text = last_interface_name
return request_interface |
<SYSTEM_TASK:>
Creates a new Netconf request based on the last received
<END_TASK>
<USER_TASK:>
Description:
def get_vlan_brief_request(last_vlan_id):
""" Creates a new Netconf request based on the last received
vlan id when the hasMore flag is true
""" |
request_interface = ET.Element(
'get-vlan-brief',
xmlns="urn:brocade.com:mgmt:brocade-interface-ext"
)
if last_vlan_id != '':
last_received_int_el = ET.SubElement(request_interface,
"last-rcvd-vlan-id")
last_received_int_el.text = last_vlan_id
return request_interface |
<SYSTEM_TASK:>
Creates a new Netconf request based on the last received
<END_TASK>
<USER_TASK:>
Description:
def get_port_chann_detail_request(last_aggregator_id):
""" Creates a new Netconf request based on the last received
aggregator id when the hasMore flag is true
""" |
port_channel_ns = 'urn:brocade.com:mgmt:brocade-lag'
request_port_channel = ET.Element('get-port-channel-detail',
xmlns=port_channel_ns)
if last_aggregator_id != '':
last_received_port_chann_el = ET.SubElement(request_port_channel,
"last-aggregator-id")
last_received_port_chann_el.text = last_aggregator_id
return request_port_channel |
<SYSTEM_TASK:>
Set vrrpe short path forwarding to default.
<END_TASK>
<USER_TASK:>
Description:
def vrrpe_spf_basic(self, **kwargs):
"""Set vrrpe short path forwarding to default.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc).
name (str): Name of interface. (1/0/5, 1/0/10, etc).
enable (bool): If vrrpe short path fowarding should be enabled
or disabled.Default:``True``.
get (bool) : Get config instead of editing config. (True, False)
vrid (str): vrrpe router ID.
rbridge_id (str): rbridge-id for device. Only required when type is
`ve`.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `int_type`, `name`, `vrid` is not passed.
ValueError: if `int_type`, `name`, `vrid` is invalid.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.services.vrrpe(ip_version='6',
... enable=True, rbridge_id='225')
... output = dev.interface.vrrpe_vip(int_type='ve',
... name='89', vrid='1',
... vip='2002:4818:f000:1ab:cafe:beef:1000:1/64',
... output = dev.interface.vrrpe_vip(int_type='ve',
... name='89',
... vrid='1', vip='2002:4818:f000:1ab:cafe:beef:1000:1/64',
... rbridge_id='225')
... output = dev.services.vrrpe(enable=False,
... rbridge_id='225')
... output = dev.interface.vrrpe_spf_basic(int_type='ve',
... name='89', vrid='1', rbridge_id='1')
""" |
int_type = kwargs.pop('int_type').lower()
name = kwargs.pop('name')
vrid = kwargs.pop('vrid')
enable = kwargs.pop('enable', True)
get = kwargs.pop('get', False)
rbridge_id = kwargs.pop('rbridge_id', '1')
callback = kwargs.pop('callback', self._callback)
valid_int_types = ['gigabitethernet', 'tengigabitethernet',
'fortygigabitethernet', 'hundredgigabitethernet',
'port_channel', 've']
vrrpe_args = dict(name=name, vrid=vrid)
method_class = self._interface
if get:
enable = None
if int_type not in valid_int_types:
raise ValueError('`int_type` must be one of: %s' %
repr(valid_int_types))
method_name = 'interface_%s_vrrpe_short_path_forwarding_basic' % \
int_type
if int_type == 've':
method_name = 'rbridge_id_%s' % method_name
method_class = self._rbridge
vrrpe_args['rbridge_id'] = rbridge_id
if not pynos.utilities.valid_vlan_id(name):
raise InvalidVlanId("`name` must be between `1` and `8191`")
elif not pynos.utilities.valid_interface(int_type, name):
raise ValueError('`name` must be in the format of x/y/z for '
'physical interfaces or x for port channel.')
vrrpe_spf_basic = getattr(method_class, method_name)
config = vrrpe_spf_basic(**vrrpe_args)
if get:
return callback(config, handler='get_config')
if not enable:
config.find('.//*short-path-forwarding').set('operation', 'delete')
return callback(config) |
<SYSTEM_TASK:>
Set vrrpe VIP.
<END_TASK>
<USER_TASK:>
Description:
def vrrpe_vip(self, **kwargs):
"""Set vrrpe VIP.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, ve, etc).
name (str): Name of interface. (1/0/5, 1/0/10, VE name etc).
vrid (str): vrrpev3 ID.
get (bool): Get config instead of editing config. (True, False)
delete (bool): True, the VIP address is added and False if its to
be deleted (True, False). Default value will be False if not
specified.
vip (str): IPv4/IPv6 Virtual IP Address.
rbridge_id (str): rbridge-id for device. Only required when type is
`ve`.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Raises:
KeyError: if `int_type`, `name`, `vrid`, or `vip` is not passed.
ValueError: if `int_type`, `name`, `vrid`, or `vip` is invalid.
Returns:
Return value of `callback`.
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output =dev.interface.vrrpe_vip(int_type='ve',
... name='89', rbridge_id = '1',
... vrid='11', vip='10.0.1.10')
... output = dev.interface.vrrpe_vip(get=True,
... int_type='ve', name='89', rbridge_id = '1')
... output =dev.interface.vrrpe_vip(delete=True,
... int_type='ve', name='89', rbridge_id = '1',vrid='1',
... vip='10.0.0.10')
""" |
int_type = kwargs.pop('int_type').lower()
name = kwargs.pop('name',)
vip = kwargs.pop('vip', '')
get = kwargs.pop('get', False)
delete = kwargs.pop('delete', False)
callback = kwargs.pop('callback', self._callback)
valid_int_types = ['gigabitethernet', 'tengigabitethernet',
'fortygigabitethernet', 'hundredgigabitethernet',
'port_channel', 've']
if vip != '':
ipaddress = ip_interface(unicode(vip))
version = ipaddress.version
else:
version = 4
if int_type not in valid_int_types:
raise ValueError('`int_type` must be one of: %s' %
repr(valid_int_types))
if delete:
vrid = kwargs.pop('vrid')
rbridge_id = kwargs.pop('rbridge_id', '1')
vrrpe_args = dict(rbridge_id=rbridge_id, name=name,
vrid=vrid, virtual_ipaddr=vip)
elif get:
rbridge_id = kwargs.pop('rbridge_id', '1')
vrrpe_args = dict(name=name, vrid='', virtual_ipaddr='')
else:
vrid = kwargs.pop('vrid')
ipaddress = ip_interface(unicode(vip))
if int_type == 've':
rbridge_id = kwargs.pop('rbridge_id', '1')
vrrpe_args = dict(name=name, vrid=vrid,
virtual_ipaddr=str(ipaddress.ip))
method_name = None
method_class = self._interface
if version == 4:
vrrpe_args['version'] = '3'
method_name = 'interface_%s_vrrpe_virtual_ip_virtual_' \
'ipaddr' % int_type
elif version == 6:
method_name = 'interface_%s_ipv6_vrrpv3e_group_virtual_ip_' \
'virtual_ipaddr' % int_type
if int_type == 've':
method_name = 'rbridge_id_%s' % method_name
if version == 6:
method_name = method_name.replace('group_', '')
method_class = self._rbridge
vrrpe_args['rbridge_id'] = rbridge_id
if not pynos.utilities.valid_vlan_id(name):
raise InvalidVlanId("`name` must be between `1` and `8191`")
elif not pynos.utilities.valid_interface(int_type, name):
raise ValueError('`name` must be in the format of x/y/z for '
'physical interfaces or x for port channel.')
vrrpe_vip = getattr(method_class, method_name)
config = vrrpe_vip(**vrrpe_args)
result = []
if delete:
config.find('.//*virtual-ip').set('operation', 'delete')
if get:
output = callback(config, handler='get_config')
for item in output.data.findall('.//{*}vrrpe'):
vrid = item.find('.//{*}vrid').text
if item.find('.//{*}virtual-ipaddr') is not None:
vip = item.find('.//{*}virtual-ipaddr').text
else:
vip = ''
tmp = {"vrid": vrid,
"vip": vip}
result.append(tmp)
else:
result = callback(config)
return result |
<SYSTEM_TASK:>
Creates a new Netconf request based on the rbridge_id specifed
<END_TASK>
<USER_TASK:>
Description:
def _get_intf_rb_id(rbridge_id):
""" Creates a new Netconf request based on the rbridge_id specifed
""" |
intf_rb_id = ET.Element(
'get-ip-interface',
xmlns="urn:brocade.com:mgmt:brocade-interface-ext"
)
if rbridge_id is not None:
rbridge_el = ET.SubElement(intf_rb_id, "rbridge-id")
rbridge_el.text = rbridge_id
return intf_rb_id |
<SYSTEM_TASK:>
Enable conversational mac learning on vdx switches
<END_TASK>
<USER_TASK:>
Description:
def conversational_mac(self, **kwargs):
"""Enable conversational mac learning on vdx switches
Args:
get (bool): Get config instead of editing config. (True, False)
delete (bool): True, delete the mac-learning. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
None
Examples:
>>> import pynos.device
>>> conn = ('10.24.39.211', '22')
>>> auth = ('admin', 'password')
>>> with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.conversational_mac()
... output = dev.interface.conversational_mac(get=True)
... output = dev.interface.conversational_mac(delete=True)
""" |
callback = kwargs.pop('callback', self._callback)
mac_learning = getattr(self._mac_address_table,
'mac_address_table_learning_mode')
config = mac_learning(learning_mode='conversational')
if kwargs.pop('get', False):
output = callback(config, handler='get_config')
item = output.data.find('.//{*}learning-mode')
if item is not None:
return True
if kwargs.pop('delete', False):
config.find('.//*learning-mode').set('operation', 'delete')
return callback(config) |
<SYSTEM_TASK:>
Configure Name of Overlay Gateway on vdx switches
<END_TASK>
<USER_TASK:>
Description:
def overlay_gateway_name(self, **kwargs):
"""Configure Name of Overlay Gateway on vdx switches
Args:
gw_name: Name of Overlay Gateway
get (bool): Get config instead of editing config. (True, False)
delete (bool): True, delete the overlay gateway config.
(True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `gw_name` is not passed.
ValueError: if `gw_name` is invalid.
Examples:
>>> import pynos.device
>>> conn = ('10.24.39.211', '22')
>>> auth = ('admin', 'password')
>>> with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.overlay_gateway_name(gw_name='Leaf')
... output = dev.interface.overlay_gateway_name(get=True)
... output = dev.interface.overlay_gateway_name(gw_name='Leaf',
... delete=True)
""" |
callback = kwargs.pop('callback', self._callback)
get_config = kwargs.pop('get', False)
if not get_config:
gw_name = kwargs.pop('gw_name')
overlay_gw = getattr(self._tunnels, 'overlay_gateway_name')
config = overlay_gw(name=gw_name)
if get_config:
overlay_gw = getattr(self._tunnels, 'overlay_gateway_name')
config = overlay_gw(name='')
output = callback(config, handler='get_config')
if output.data.find('.//{*}name') is not None:
gwname = output.data.find('.//{*}name').text
return gwname
else:
return None
if kwargs.pop('delete', False):
config.find('.//overlay-gateway').set('operation', 'delete')
return callback(config) |
<SYSTEM_TASK:>
Activates the Overlay Gateway Instance on VDX switches
<END_TASK>
<USER_TASK:>
Description:
def overlay_gateway_activate(self, **kwargs):
"""Activates the Overlay Gateway Instance on VDX switches
Args:
gw_name: Name of Overlay Gateway
get (bool): Get config instead of editing config. (True, False)
delete (bool): True, delete the activate config. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `gw_name` is not passed.
ValueError: if `gw_name` is invalid.
Examples:
>>> import pynos.device
>>> conn = ('10.24.39.211', '22')
>>> auth = ('admin', 'password')
>>> with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.overlay_gateway_activate(
... gw_name='Leaf')
... output = dev.interface.overlay_gateway_activate(
... get=True)
... output = dev.interface.overlay_gateway_activate(
... gw_name='Leaf', delete=True)
""" |
callback = kwargs.pop('callback', self._callback)
get_config = kwargs.pop('get', False)
if not get_config:
gw_name = kwargs.pop('gw_name')
overlay_gw = getattr(self._tunnels, 'overlay_gateway_activate')
config = overlay_gw(name=gw_name)
if get_config:
overlay_gw = getattr(self._tunnels, 'overlay_gateway_activate')
config = overlay_gw(name='')
output = callback(config, handler='get_config')
if output.data.find('.//{*}name') is not None:
if output.data.find('.//{*}activate') is not None:
return True
else:
return None
else:
return None
if kwargs.pop('delete', False):
config.find('.//activate').set('operation', 'delete')
return callback(config) |
<SYSTEM_TASK:>
Configure Overlay Gateway Type on vdx switches
<END_TASK>
<USER_TASK:>
Description:
def overlay_gateway_type(self, **kwargs):
"""Configure Overlay Gateway Type on vdx switches
Args:
gw_name: Name of Overlay Gateway
gw_type: Type of Overlay Gateway(hardware-vtep/
layer2-extension/nsx)
get (bool): Get config instead of editing config. (True, False)
delete (bool): True, delete the overlay gateway type.
(True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `gw_name`, 'gw_type' is not passed.
ValueError: if `gw_name`, 'gw_type' is invalid.
Examples:
>>> import pynos.device
>>> conn = ('10.24.39.211', '22')
>>> auth = ('admin', 'password')
>>> with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.overlay_gateway_type(gw_name='Leaf',
... gw_type='layer2-extension')
... output = dev.interface.overlay_gateway_name(get=True)
""" |
callback = kwargs.pop('callback', self._callback)
get_config = kwargs.pop('get', False)
if not get_config:
gw_name = kwargs.pop('gw_name')
gw_type = kwargs.pop('gw_type')
gw_args = dict(name=gw_name, gw_type=gw_type)
overlay_gw = getattr(self._tunnels, 'overlay_gateway_gw_type')
config = overlay_gw(**gw_args)
if get_config:
overlay_gw = getattr(self._tunnels, 'overlay_gateway_gw_type')
config = overlay_gw(name='', gw_type='')
output = callback(config, handler='get_config')
if output.data.find('.//{*}name') is not None:
gwtype = output.data.find('.//{*}gw-type').text
return gwtype
else:
return None
return callback(config) |
<SYSTEM_TASK:>
Configure Overlay Gateway ip interface loopback
<END_TASK>
<USER_TASK:>
Description:
def overlay_gateway_loopback_id(self, **kwargs):
"""Configure Overlay Gateway ip interface loopback
Args:
gw_name: Name of Overlay Gateway <WORD:1-32>
loopback_id: Loopback interface Id <NUMBER: 1-255>
get (bool): Get config instead of editing config. (True, False)
delete (bool): True, delete the overlay gateway loop back id.
(True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `gw_name`, 'loopback_id' is not passed.
ValueError: if `gw_name`, 'loopback_id' is invalid.
Examples:
>>> import pynos.device
>>> conn = ('10.24.39.211', '22')
>>> auth = ('admin', 'password')
>>> with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.overlay_gateway_loopback_id(
... gw_name='Leaf', loopback_id='10')
... output = dev.interface.overlay_gateway_loopback_id(
... get=True)
... output = dev.interface.overlay_gateway_loopback_id(
... gw_name='Leaf', loopback_id='10', delete=True)
""" |
callback = kwargs.pop('callback', self._callback)
get_config = kwargs.pop('get', False)
if not get_config:
gw_name = kwargs.pop('gw_name')
loopback_id = kwargs.pop('loopback_id')
gw_args = dict(name=gw_name, loopback_id=loopback_id)
overlay_gw = getattr(self._tunnels, 'overlay_gateway_ip_'
'interface_loopback_loopback_id')
config = overlay_gw(**gw_args)
if get_config:
overlay_gw = getattr(self._tunnels, 'overlay_gateway_ip_'
'interface_loopback_loopback_id')
config = overlay_gw(name='', loopback_id='')
output = callback(config, handler='get_config')
if output.data.find('.//{*}name') is not None:
if output.data.find('.//{*}loopback-id') is not None:
ip_intf = output.data.find('.//{*}loopback-id').text
return ip_intf
else:
return None
else:
return None
if kwargs.pop('delete', False):
config.find('.//loopback-id').set('operation', 'delete')
return callback(config) |
<SYSTEM_TASK:>
Configure Overlay Gateway attach rbridge id
<END_TASK>
<USER_TASK:>
Description:
def overlay_gateway_attach_rbridge_id(self, **kwargs):
"""Configure Overlay Gateway attach rbridge id
Args:
gw_name: Name of Overlay Gateway <WORD:1-32>
rbridge_id: Single or range of rbridge id to be added/removed
get (bool): Get config instead of editing config. (True, False)
delete (bool): True, delete the attached rbridge list
(True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `gw_name`, 'rbridge_id' is not passed.
ValueError: if `gw_name`, 'rbridge_id' is invalid.
Examples:
>>> import pynos.device
>>> conn = ('10.24.39.211', '22')
>>> auth = ('admin', 'password')
>>> with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.overlay_gateway_attach_rbridge_id(
... gw_name='Leaf', rbridge_id='10')
... output = dev.interface.overlay_gateway_attach_rbridge_id(
... get=True)
... output = dev.interface.overlay_gateway_attach_rbridge_id(
... gw_name='Leaf', rbridge_id='1-2', delete=True)
""" |
callback = kwargs.pop('callback', self._callback)
get_config = kwargs.pop('get', False)
delete = kwargs.pop('delete', False)
if not get_config:
gw_name = kwargs.pop('gw_name')
rbridge_id = kwargs.pop('rbridge_id')
if delete is True:
gw_args = dict(name=gw_name, rb_remove=rbridge_id)
overlay_gw = getattr(self._tunnels, 'overlay_gateway_'
'attach_rbridge_id_rb_remove')
config = overlay_gw(**gw_args)
else:
gw_args = dict(name=gw_name, rb_add=rbridge_id)
overlay_gw = getattr(self._tunnels, 'overlay_gateway_'
'attach_rbridge_id_rb_add')
config = overlay_gw(**gw_args)
if get_config:
overlay_gw = getattr(self._tunnels, 'overlay_gateway_'
'attach_rbridge_id_rb_add')
config = overlay_gw(name='', rb_add='')
output = callback(config, handler='get_config')
if output.data.find('.//{*}name') is not None:
if output.data.find('.//{*}attach') is not None:
output.data.find('.//{*}name').text
rb_id = output.data.find('.//{*}rb-add').text
return rb_id
else:
return None
else:
return None
return callback(config) |
<SYSTEM_TASK:>
Configure ipv6 link local address on interfaces on vdx switches
<END_TASK>
<USER_TASK:>
Description:
def ipv6_link_local(self, **kwargs):
"""Configure ipv6 link local address on interfaces on vdx switches
Args:
int_type: Interface type on which the ipv6 link local needs to be
configured.
name: 'Ve' or 'loopback' interface name.
rbridge_id (str): rbridge-id for device.
get (bool): Get config instead of editing config. (True, False)
delete (bool): True, delete the mac-learning. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `int_type`, `name` is not passed.
ValueError: if `int_type`, `name` is invalid.
Examples:
>>> import pynos.device
>>> conn = ('10.24.39.211', '22')
>>> auth = ('admin', 'password')
>>> with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.interface.ipv6_link_local(name='500',
... int_type='ve',rbridge_id='1')
... output = dev.interface.ipv6_link_local(get=True,name='500',
... int_type='ve',rbridge_id='1')
... output = dev.interface.ipv6_link_local(delete=True,
... name='500', int_type='ve', rbridge_id='1')
""" |
int_type = kwargs.pop('int_type').lower()
ve_name = kwargs.pop('name')
rbridge_id = kwargs.pop('rbridge_id', '1')
callback = kwargs.pop('callback', self._callback)
valid_int_types = ['loopback', 've']
if int_type not in valid_int_types:
raise ValueError('`int_type` must be one of: %s' %
repr(valid_int_types))
link_args = dict(name=ve_name, rbridge_id=rbridge_id,
int_type=int_type)
method_name = 'rbridge_id_interface_%s_ipv6_ipv6_config_address_' \
'use_link_local_only' % int_type
method_class = self._rbridge
v6_link_local = getattr(method_class, method_name)
config = v6_link_local(**link_args)
if kwargs.pop('get', False):
output = callback(config, handler='get_config')
item = output.data.find('.//{*}use-link-local-only')
if item is not None:
return True
if kwargs.pop('delete', False):
config.find('.//*use-link-local-only').set('operation', 'delete')
return callback(config) |
<SYSTEM_TASK:>
Configures maintenance mode on the device
<END_TASK>
<USER_TASK:>
Description:
def maintenance_mode(self, **kwargs):
"""Configures maintenance mode on the device
Args:
rbridge_id (str): The rbridge ID of the device on which
Maintenance mode
will be configured in a VCS fabric.
get (bool): Get config instead of editing config. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `rbridge_id` is not specified.
Examples:
>>> import pynos.device
>>> conn = ('10.24.39.202', '22')
>>> auth = ('admin', 'password')
>>> with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.system.maintenance_mode(rbridge_id='226')
... output = dev.system.maintenance_mode(rbridge_id='226',
... get=True)
... assert output == True
... output = dev.system.maintenance_mode(rbridge_id='226',
... delete=True)
... output = dev.system.maintenance_mode(rbridge_id='226',
... get=True)
... assert output == False
""" |
is_get_config = kwargs.pop('get', False)
delete = kwargs.pop('delete', False)
rbridge_id = kwargs.pop('rbridge_id')
callback = kwargs.pop('callback', self._callback)
rid_args = dict(rbridge_id=rbridge_id)
rid = getattr(self._rbridge,
'rbridge_id_system_mode_maintenance')
config = rid(**rid_args)
if is_get_config:
maint_mode = callback(config, handler='get_config')
mode = maint_mode.data_xml
root = ET.fromstring(mode)
namespace = 'urn:brocade.com:mgmt:brocade-rbridge'
for rbridge_id_node in root.findall('{%s}rbridge-id' % namespace):
system_mode = rbridge_id_node.find(
'{%s}system-mode' % namespace)
if system_mode is not None:
return True
else:
return False
if delete:
config.find('.//*maintenance').set('operation', 'delete')
return callback(config) |
<SYSTEM_TASK:>
Callback for NETCONF calls.
<END_TASK>
<USER_TASK:>
Description:
def _callback_main(self, call, handler='edit_config', target='running',
source='startup'):
"""
Callback for NETCONF calls.
Args:
call: An Element Tree element containing the XML of the NETCONF
call you intend to make to the device.
handler: Type of ncclient call to make.
get_config: NETCONF standard get config.
get: ncclient dispatch. For custom RPCs.
edit_config: NETCONF standard edit.
delete_config: NETCONF standard delete.
copy_config: NETCONF standard copy.
target: Target configuration location for action. Only used for
edit_config, delete_config, and copy_config.
source: Source of configuration information for copying
configuration. Only used for copy_config.
Returns:
None
Raises:
None
""" |
try:
if handler == 'get_config':
call = ET.tostring(call.getchildren()[0])
return self._mgr.get(filter=('subtree', call))
call = ET.tostring(call)
if handler == 'get':
call_element = xml_.to_ele(call)
return ET.fromstring(str(self._mgr.dispatch(call_element)))
if handler == 'edit_config':
self._mgr.edit_config(target=target, config=call)
if handler == 'delete_config':
self._mgr.delete_config(target=target)
if handler == 'copy_config':
self._mgr.copy_config(target=target, source=source)
except (ncclient.transport.TransportError,
ncclient.transport.SessionCloseError,
ncclient.transport.SSHError,
ncclient.transport.AuthenticationError,
ncclient.transport.SSHUnknownHostError) as error:
logging.error(error)
raise DeviceCommError |
<SYSTEM_TASK:>
Reconnect session with device.
<END_TASK>
<USER_TASK:>
Description:
def reconnect(self):
"""
Reconnect session with device.
Args:
None
Returns:
bool: True if reconnect succeeds, False if not.
Raises:
None
""" |
if self._auth_method is "userpass":
self._mgr = manager.connect(host=self._conn[0],
port=self._conn[1],
username=self._auth[0],
password=self._auth[1],
hostkey_verify=self._hostkey_verify)
elif self._auth_method is "key":
self._mgr = manager.connect(host=self._conn[0],
port=self._conn[1],
username=self._auth[0],
key_filename=self._auth_key,
hostkey_verify=self._hostkey_verify)
else:
raise ValueError("auth_method incorrect value.")
self._mgr.timeout = 600
return True |
<SYSTEM_TASK:>
Find the interface through which a MAC can be reached.
<END_TASK>
<USER_TASK:>
Description:
def find_interface_by_mac(self, **kwargs):
"""Find the interface through which a MAC can be reached.
Args:
mac_address (str): A MAC address in 'xx:xx:xx:xx:xx:xx' format.
Returns:
list[dict]: a list of mac table data.
Raises:
KeyError: if `mac_address` is not specified.
Examples:
>>> from pprint import pprint
>>> import pynos.device
>>> conn = ('10.24.39.211', '22')
>>> auth = ('admin', 'password')
>>> with pynos.device.Device(conn=conn, auth=auth) as dev:
... x = dev.find_interface_by_mac(
... mac_address='10:23:45:67:89:ab')
... pprint(x) # doctest: +ELLIPSIS
[{'interface'...'mac_address'...'state'...'type'...'vlan'...}]
""" |
mac = kwargs.pop('mac_address')
results = [x for x in self.mac_table if x['mac_address'] == mac]
return results |
<SYSTEM_TASK:>
Solve a puzzle constrained by board dimensions and pieces.
<END_TASK>
<USER_TASK:>
Description:
def solve(ctx, length, height, silent, profile, **pieces):
""" Solve a puzzle constrained by board dimensions and pieces. """ |
# Check that at least one piece is provided.
if not sum(pieces.values()):
context = click.get_current_context()
raise BadParameter('No piece provided.', ctx=context, param_hint=[
'--{}'.format(label) for label in PIECE_LABELS])
# Setup the optionnal profiler.
profiler = BProfile('solver-profile.png', enabled=profile)
solver = SolverContext(length, height, **pieces)
logger.info(repr(solver))
logger.info('Searching positions...')
with profiler:
start = time.time()
for result in solver.solve():
if not silent:
click.echo(u'{}'.format(result))
processing_time = time.time() - start
logger.info('{} results found in {:.2f} seconds.'.format(
solver.result_counter, processing_time))
if profile:
logger.info('Execution profile saved at {}'.format(
profiler.output_path)) |
<SYSTEM_TASK:>
Run a benchmarking suite and measure time taken by the solver.
<END_TASK>
<USER_TASK:>
Description:
def benchmark():
""" Run a benchmarking suite and measure time taken by the solver.
Each scenario is run in an isolated process, and results are appended to
CSV file.
""" |
# Use all cores but one on multi-core CPUs.
pool_size = multiprocessing.cpu_count() - 1
if pool_size < 1:
pool_size = 1
# Start a pool of workers. Only allow 1 task per child, to force flushing
# of solver's internal caches.
pool = multiprocessing.Pool(processes=pool_size, maxtasksperchild=1)
results = pool.imap_unordered(run_scenario, Benchmark.scenarii)
pool.close()
pool.join()
# Update CSV database with the new results.
benchmark = Benchmark()
benchmark.load_csv()
benchmark.add(results)
benchmark.save_csv() |
<SYSTEM_TASK:>
Reuse standard integer validator but add checks on sign and zero.
<END_TASK>
<USER_TASK:>
Description:
def convert(self, value, param, ctx):
""" Reuse standard integer validator but add checks on sign and zero.
""" |
value = super(PositiveInt, self).convert(value, param, ctx)
if value < 0:
self.fail('%s is not positive' % value, param, ctx)
if not self.allow_zero and not value:
self.fail('%s is not greater than 0' % value, param, ctx)
return value |
<SYSTEM_TASK:>
Enable or Disable VRRP.
<END_TASK>
<USER_TASK:>
Description:
def vrrp(self, **kwargs):
"""Enable or Disable VRRP.
Args:
ip_version (str): The IP version ('4' or '6') for which VRRP should
be enabled/disabled. Default: `4`.
enabled (bool): If VRRP should be enabled or disabled. Default:
``True``.
rbridge_id (str): The rbridge ID of the device on which VRRP will
be enabled/disabled. Default: `1`.
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
None
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.211', '10.24.39.203']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.bgp.local_asn(rbridge_id='225')
... output = dev.bgp.local_asn(rbridge_id='225',
... enabled=False)
... output = dev.bgp.local_asn(rbridge_id='225',
... ip_version='6')
... output = dev.bgp.local_asn(rbridge_id='225',
... enabled=False, ip_version='6')
... dev.services.vrrp() # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError
""" |
ip_version = kwargs.pop('ip_version', '4')
enabled = kwargs.pop('enabled', True)
rbridge_id = kwargs.pop('rbridge_id', '1')
callback = kwargs.pop('callback', self._callback)
vrrp_args = dict(rbridge_id=rbridge_id)
vrrp_method = 'rbridge_id_protocol_hide_vrrp_holder_vrrp'
if ip_version == '6':
vrrp_method = 'rbridge_id_ipv6_proto_vrrpv3_vrrp'
vrrp = getattr(self._rbridge, vrrp_method)
config = vrrp(**vrrp_args)
if not enabled:
config.find('.//*vrrp').set('operation', 'delete')
return callback(config) |
<SYSTEM_TASK:>
Run one scenario and returns execution time and number of solutions.
<END_TASK>
<USER_TASK:>
Description:
def run_scenario(params):
""" Run one scenario and returns execution time and number of solutions.
Also returns initial parameters in the response to keep the results
associated with the initial context.
""" |
solver = SolverContext(**params)
start = time.time()
count = sum(1 for _ in solver.solve())
execution_time = time.time() - start
params.update({
'solutions': count,
'execution_time': execution_time})
return params |
<SYSTEM_TASK:>
Load old benchmark results from CSV.
<END_TASK>
<USER_TASK:>
Description:
def load_csv(self):
""" Load old benchmark results from CSV. """ |
if path.exists(self.csv_filepath):
self.results = self.results.append(
pandas.read_csv(self.csv_filepath)) |
<SYSTEM_TASK:>
Dump all results to CSV.
<END_TASK>
<USER_TASK:>
Description:
def save_csv(self):
""" Dump all results to CSV. """ |
# Sort results so we can start to see patterns right in the raw CSV.
self.results.sort_values(by=self.column_ids, inplace=True)
# Gotcha: integers seems to be promoted to float64 because of
# reindexation. See: https://pandas.pydata.org/pandas-docs/stable
# /gotchas.html#na-type-promotions
self.results.reindex(columns=self.column_ids).to_csv(
self.csv_filepath, index=False) |
<SYSTEM_TASK:>
Graph n-queens problem for the current version and context.
<END_TASK>
<USER_TASK:>
Description:
def nqueen_graph(self):
""" Graph n-queens problem for the current version and context. """ |
# Filters out boards with pieces other than queens.
nqueens = self.results
for piece_label in set(PIECE_LABELS).difference(['queen']):
nqueens = nqueens[nqueens[piece_label].map(pandas.isnull)]
# Filters out non-square boards whose dimension are not aligned to the
# number of queens.
nqueens = nqueens[nqueens['length'] == nqueens['queen']]
nqueens = nqueens[nqueens['height'] == nqueens['queen']]
# Filters out results not obtained from this system.
for label, value in self.context.items():
if not value:
nqueens = nqueens[nqueens[label].map(pandas.isnull)]
else:
nqueens = nqueens[nqueens[label] == value]
plot = seaborn.factorplot(
x='queen',
y='execution_time',
data=nqueens.sort(columns='queen'),
estimator=median,
kind='bar',
palette='BuGn_d',
aspect=1.5)
plot.set_xlabels('Number of queens')
plot.set_ylabels('Solving time in seconds (log scale)')
plot.fig.get_axes()[0].set_yscale('log')
plot.savefig('nqueens-performances.png') |
<SYSTEM_TASK:>
Experimental neighbor method.
<END_TASK>
<USER_TASK:>
Description:
def neighbor(self, **kwargs):
"""Experimental neighbor method.
Args:
ip_addr (str): IP Address of BGP neighbor.
remote_as (str): Remote ASN of BGP neighbor.
rbridge_id (str): The rbridge ID of the device on which BGP will be
configured in a VCS fabric.
afis (list): A list of AFIs to configure. Do not include IPv4 or
IPv6 unicast as these are inferred from the `ip_addr`
parameter.
delete (bool): Deletes the neighbor if `delete` is ``True``.
get (bool): Get config instead of editing config. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
KeyError: if `remote_as` or `ip_addr` is not specified.
Examples:
>>> import pynos.device
>>> conn = ('10.24.39.203', '22')
>>> auth = ('admin', 'password')
>>> with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.bgp.local_asn(local_as='65535',
... rbridge_id='225')
... output = dev.bgp.neighbor(ip_addr='10.10.10.10',
... remote_as='65535', rbridge_id='225')
... output = dev.bgp.neighbor(remote_as='65535',
... rbridge_id='225',
... ip_addr='2001:4818:f000:1ab:cafe:beef:1000:1')
... output = dev.bgp.neighbor(ip_addr='10.10.10.10',
... delete=True, rbridge_id='225', remote_as='65535')
... output = dev.bgp.neighbor(remote_as='65535',
... rbridge_id='225', delete=True,
... ip_addr='2001:4818:f000:1ab:cafe:beef:1000:1')
""" |
ip_addr = ip_interface(unicode(kwargs.pop('ip_addr')))
rbridge_id = kwargs.pop('rbridge_id', '1')
delete = kwargs.pop('delete', False)
callback = kwargs.pop('callback', self._callback)
remote_as = kwargs.pop('remote_as', None)
get_config = kwargs.pop('get', False)
if not get_config and remote_as is None:
raise ValueError('When configuring a neighbor, you must specify '
'its remote-as.')
neighbor_args = dict(router_bgp_neighbor_address=str(ip_addr.ip),
remote_as=remote_as,
rbridge_id=rbridge_id)
if ip_addr.version == 6:
neighbor_args['router_bgp_neighbor_ipv6_address'] = str(ip_addr.ip)
neighbor, ip_addr_path = self._unicast_xml(ip_addr.version)
config = neighbor(**neighbor_args)
if ip_addr.version == 6 and not delete:
config = self._build_ipv6(ip_addr, config, rbridge_id)
if delete and config.find(ip_addr_path) is not None:
if ip_addr.version == 4:
config.find(ip_addr_path).set('operation', 'delete')
config.find('.//*router-bgp-neighbor-address').set('operation',
'delete')
elif ip_addr.version == 6:
config.find(ip_addr_path).set('operation', 'delete')
config.find('.//*router-bgp-neighbor-ipv6-address').set(
'operation', 'delete')
if get_config:
return callback(config, handler='get_config')
return callback(config) |
<SYSTEM_TASK:>
Activate EVPN AFI for a peer.
<END_TASK>
<USER_TASK:>
Description:
def evpn_afi_peer_activate(self, **kwargs):
"""
Activate EVPN AFI for a peer.
Args:
ip_addr (str): IP Address of BGP neighbor.
rbridge_id (str): The rbridge ID of the device on which BGP will be
configured in a VCS fabric.
delete (bool): Deletes the neighbor if `delete` is ``True``.
Deactivate
get (bool): Get config instead of editing config. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
None
Examples:
>>> import pynos.device
>>> conn = ('10.24.39.203', '22')
>>> auth = ('admin', 'password')
>>> with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.bgp.local_asn(local_as='65535',
... rbridge_id='225')
... output = dev.bgp.evpn_afi(rbridge_id='225')
... output = dev.bgp.neighbor(ip_addr='10.10.10.11',
... remote_as='65535', rbridge_id='225')
... output = dev.bgp.evpn_afi_peer_activate(rbridge_id='225',
... peer_ip='10.10.10.11')
... output = dev.bgp.evpn_afi_peer_activate(rbridge_id='225',
... peer_ip='10.10.10.11', get=True)
... output = dev.bgp.evpn_afi_peer_activate(rbridge_id='225',
... peer_ip='10.10.10.11', delete=True)
... output = dev.bgp.evpn_afi(rbridge_id='225',
... delete=True)
... output = dev.bgp.remove_bgp(rbridge_id='225')
""" |
peer_ip = kwargs.pop('peer_ip')
callback = kwargs.pop('callback', self._callback)
evpn_activate = getattr(self._rbridge,
'rbridge_id_router_router_bgp_address_family_'
'l2vpn_evpn_neighbor_evpn_neighbor_ipv4_'
'activate')
args = dict(evpn_neighbor_ipv4_address=peer_ip, ip_addr=peer_ip,
rbridge_id=kwargs.pop('rbridge_id'),
afi='evpn')
evpn_activate = evpn_activate(**args)
if kwargs.pop('delete', False):
evpn_activate.find('.//*activate').set('operation', 'delete')
if kwargs.pop('get', False):
return callback(evpn_activate, handler='get_config')
return callback(evpn_activate) |
<SYSTEM_TASK:>
Configure next hop unchanged for an EVPN neighbor.
<END_TASK>
<USER_TASK:>
Description:
def evpn_next_hop_unchanged(self, **kwargs):
"""Configure next hop unchanged for an EVPN neighbor.
You probably don't want this method. You probably want to configure
an EVPN neighbor using `BGP.neighbor`. That will configure next-hop
unchanged automatically.
Args:
ip_addr (str): IP Address of BGP neighbor.
rbridge_id (str): The rbridge ID of the device on which BGP will be
configured in a VCS fabric.
delete (bool): Deletes the neighbor if `delete` is ``True``.
get (bool): Get config instead of editing config. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
None
Examples:
>>> import pynos.device
>>> conn = ('10.24.39.203', '22')
>>> auth = ('admin', 'password')
>>> with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.bgp.local_asn(local_as='65535',
... rbridge_id='225')
... output = dev.bgp.neighbor(ip_addr='10.10.10.10',
... remote_as='65535', rbridge_id='225')
... output = dev.bgp.evpn_next_hop_unchanged(rbridge_id='225',
... ip_addr='10.10.10.10')
... output = dev.bgp.evpn_next_hop_unchanged(rbridge_id='225',
... ip_addr='10.10.10.10', get=True)
... output = dev.bgp.evpn_next_hop_unchanged(rbridge_id='225',
... ip_addr='10.10.10.10', delete=True)
""" |
callback = kwargs.pop('callback', self._callback)
args = dict(rbridge_id=kwargs.pop('rbridge_id', '1'),
evpn_neighbor_ipv4_address=kwargs.pop('ip_addr'))
next_hop_unchanged = getattr(self._rbridge,
'rbridge_id_router_router_bgp_address_'
'family_l2vpn_evpn_neighbor_evpn_'
'neighbor_ipv4_next_hop_unchanged')
config = next_hop_unchanged(**args)
if kwargs.pop('delete', False):
config.find('.//*next-hop-unchanged').set('operation', 'delete')
if kwargs.pop('get', False):
return callback(config, handler='get_config')
return callback(config) |
<SYSTEM_TASK:>
BFD enable for each specified peer.
<END_TASK>
<USER_TASK:>
Description:
def enable_peer_bfd(self, **kwargs):
"""BFD enable for each specified peer.
Args:
rbridge_id (str): Rbridge to configure. (1, 225, etc)
peer_ip (str): Peer IPv4 address for BFD setting.
delete (bool): True if BFD configuration should be deleted.
Default value will be False if not specified.
get (bool): Get config instead of editing config. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
XML to be passed to the switch.
Raises:
None
Examples:
>>> import pynos.device
>>> switches = ['10.24.39.230']
>>> auth = ('admin', 'password')
>>> for switch in switches:
... conn = (switch, '22')
... with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.bgp.neighbor(ip_addr='10.10.10.20',
... remote_as='65535', rbridge_id='230')
... output = dev.bgp.enable_peer_bfd(peer_ip='10.10.10.20',
... rbridge_id='230')
... output = dev.bgp.enable_peer_bfd(peer_ip='10.10.10.20',
... rbridge_id='230',get=True)
... output = dev.bgp.enable_peer_bfd(peer_ip='10.10.10.20',
... rbridge_id='230', delete=True)
... output = dev.bgp.neighbor(ip_addr='10.10.10.20',
... delete=True, rbridge_id='230', remote_as='65535')
""" |
method_name = 'rbridge_id_router_router_bgp_router_bgp_attributes_' \
'neighbor_neighbor_ips_neighbor_addr_bfd_bfd_enable'
bfd_enable = getattr(self._rbridge, method_name)
kwargs['router_bgp_neighbor_address'] = kwargs.pop('peer_ip')
callback = kwargs.pop('callback', self._callback)
config = bfd_enable(**kwargs)
if kwargs.pop('delete', False):
tag = 'bfd-enable'
config.find('.//*%s' % tag).set('operation', 'delete')
if kwargs.pop('get', False):
return callback(config, handler='get_config')
else:
return callback(config) |
<SYSTEM_TASK:>
Get and merge the `bfd` config from global BGP.
<END_TASK>
<USER_TASK:>
Description:
def _peer_get_bfd(self, tx, rx, multiplier):
"""Get and merge the `bfd` config from global BGP.
You should not use this method.
You probably want `BGP.bfd`.
Args:
tx: XML document with the XML to get the transmit interval.
rx: XML document with the XML to get the receive interval.
multiplier: XML document with the XML to get the interval
multiplier.
Returns:
Merged XML document.
Raises:
None
""" |
tx = self._callback(tx, handler='get_config')
rx = self._callback(rx, handler='get_config')
multiplier = self._callback(multiplier, handler='get_config')
tx = pynos.utilities.return_xml(str(tx))
rx = pynos.utilities.return_xml(str(rx))
multiplier = pynos.utilities.return_xml(str(multiplier))
config = pynos.utilities.merge_xml(tx, rx)
return pynos.utilities.merge_xml(config, multiplier) |
<SYSTEM_TASK:>
Set BGP max paths property on VRF address family.
<END_TASK>
<USER_TASK:>
Description:
def vrf_max_paths(self, **kwargs):
"""Set BGP max paths property on VRF address family.
Args:
vrf (str): The VRF for this BGP process.
rbridge_id (str): The rbridge ID of the device on which BGP will be
configured in a VCS fabric.
paths (str): Number of paths for BGP ECMP (default: 8).
afi (str): Address family to configure. (ipv4, ipv6)
get (bool): Get config instead of editing config. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
``AttributeError``: When `afi` is not one of ['ipv4', 'ipv6']
Examples:
>>> import pynos.device
>>> conn = ('10.24.39.211', '22')
>>> auth = ('admin', 'password')
>>> with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.bgp.vrf_max_paths(paths='8',
... rbridge_id='225')
... output = dev.bgp.vrf_max_paths(
... rbridge_id='225', get=True)
... output = dev.bgp.vrf_max_paths(paths='8',
... rbridge_id='225', delete=True)
... output = dev.bgp.vrf_max_paths(paths='8', afi='ipv6',
... rbridge_id='225')
... output = dev.bgp.vrf_max_paths(afi='ipv6',
... rbridge_id='225', get=True)
... output = dev.bgp.vrf_max_paths(paths='8', afi='ipv6',
... rbridge_id='225', delete=True)
... output = dev.bgp.vrf_max_paths(paths='8', afi='ipv5',
... rbridge_id='225') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
AttributeError
""" |
afi = kwargs.pop('afi', 'ipv4')
vrf = kwargs.pop('vrf', 'default')
get_config = kwargs.pop('get', False)
callback = kwargs.pop('callback', self._callback)
if afi not in ['ipv4', 'ipv6']:
raise AttributeError('Invalid AFI.')
if "ipv4" in afi:
if not get_config:
args = dict(af_vrf_name=vrf,
rbridge_id=kwargs.pop('rbridge_id', '1'),
load_sharing_value=kwargs.pop('paths', '8'))
else:
args = dict(af_vrf_name=vrf,
rbridge_id=kwargs.pop('rbridge_id', '1'),
load_sharing_value='')
max_paths = getattr(self._rbridge,
'rbridge_id_router_router_bgp_address_family_'
'ipv4_ipv4_unicast_af_vrf_maximum_paths_'
'load_sharing_value')
elif "ipv6" in afi:
if not get_config:
args = dict(af_ipv6_vrf_name=vrf,
rbridge_id=kwargs.pop('rbridge_id', '1'),
load_sharing_value=kwargs.pop('paths', '8'))
else:
args = dict(af_ipv6_vrf_name=vrf,
rbridge_id=kwargs.pop('rbridge_id', '1'),
load_sharing_value='')
max_paths = getattr(self._rbridge,
'rbridge_id_router_router_bgp_address_family_'
'ipv6_ipv6_unicast_af_ipv6_vrf_maximum_paths_'
'load_sharing_value')
config = max_paths(**args)
if get_config:
output = callback(config, handler='get_config')
if output.data.find('.//{*}load-sharing-value') is not None:
max_path = output.data.find('.//{*}load-sharing-value').text
result = {"vrf": vrf,
"max_path": max_path}
return result
else:
return None
if kwargs.pop('delete', False):
config.find('.//*load-sharing-value').set('operation', 'delete')
return callback(config) |
<SYSTEM_TASK:>
Set BGP max paths property on default VRF address family.
<END_TASK>
<USER_TASK:>
Description:
def default_vrf_max_paths(self, **kwargs):
"""Set BGP max paths property on default VRF address family.
Args:
rbridge_id (str): The rbridge ID of the device on which BGP will be
configured in a VCS fabric.
paths (str): Number of paths for BGP ECMP (default: 8).
afi (str): Address family to configure. (ipv4, ipv6)
get (bool): Get config instead of editing config. (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns:
Return value of `callback`.
Raises:
``AttributeError``: When `afi` is not one of ['ipv4', 'ipv6']
Examples:
>>> import pynos.device
>>> conn = ('10.24.39.211', '22')
>>> auth = ('admin', 'password')
>>> with pynos.device.Device(conn=conn, auth=auth) as dev:
... output = dev.bgp.default_vrf_max_paths(paths='8',
... rbridge_id='225')
... output = dev.bgp.default_vrf_max_paths(
... rbridge_id='225', get=True)
... output = dev.bgp.default_vrf_max_paths(paths='8',
... rbridge_id='225', delete=True)
... output = dev.bgp.default_vrf_max_paths(paths='8',
... afi='ipv6', rbridge_id='225')
... output = dev.bgp.default_vrf_max_paths(
... afi='ipv6', rbridge_id='225', get=True)
... output = dev.bgp.default_vrf_max_paths(paths='8',
... afi='ipv6', rbridge_id='225', delete=True)
... output = dev.bgp.default_vrf_max_paths(paths='8',
... afi='ipv5', rbridge_id='225')
Traceback (most recent call last):
AttributeError
""" |
afi = kwargs.pop('afi', 'ipv4')
callback = kwargs.pop('callback', self._callback)
get_config = kwargs.pop('get', False)
if afi not in ['ipv4', 'ipv6']:
raise AttributeError('Invalid AFI.')
if not get_config:
args = dict(rbridge_id=kwargs.pop('rbridge_id', '1'),
load_sharing_value=kwargs.pop('paths', '8'))
else:
args = dict(rbridge_id=kwargs.pop('rbridge_id', '1'),
load_sharing_value='')
max_paths = getattr(self._rbridge,
'rbridge_id_router_router_bgp_address_family_'
'{0}_{0}_unicast_default_vrf_af_common_cmds_'
'holder_maximum_paths_load_'
'sharing_value'.format(afi))
config = max_paths(**args)
if get_config:
output = callback(config, handler='get_config')
if output.data.find('.//{*}load-sharing-value') is not None:
max_path = output.data.find('.//{*}load-sharing-value').text
result = {"max_path": max_path}
return result
else:
return None
if kwargs.pop('delete', False):
config.find('.//*load-sharing-value').set('operation', 'delete')
return callback(config) |
<SYSTEM_TASK:>
Decorator to define a command.
<END_TASK>
<USER_TASK:>
Description:
def command(*args, **kwargs):
"""Decorator to define a command.
The arguments to this decorator are those of the
`ArgumentParser <https://docs.python.org/3/library/argparse.html\
#argumentparser-objects>`_
object constructor.
""" |
def decorator(f):
if 'description' not in kwargs:
kwargs['description'] = f.__doc__
if 'parents' in kwargs:
if not hasattr(f, '_argnames'): # pragma: no cover
f._argnames = []
for p in kwargs['parents']:
f._argnames += p._argnames if hasattr(p, '_argnames') else []
kwargs['parents'] = [p.parser for p in kwargs['parents']]
f.parser = argparse.ArgumentParser(*args, **kwargs)
f.climax = True
for arg in getattr(f, '_arguments', []):
f.parser.add_argument(*arg[0], **arg[1])
@wraps(f)
def wrapper(args=None):
kwargs = f.parser.parse_args(args)
return f(**vars(kwargs))
wrapper.func = f
return wrapper
return decorator |
<SYSTEM_TASK:>
Decorator to define a subcommand.
<END_TASK>
<USER_TASK:>
Description:
def _subcommand(group, *args, **kwargs):
"""Decorator to define a subcommand.
This decorator is used for the group's @command decorator.
""" |
def decorator(f):
if 'help' not in kwargs:
kwargs['help'] = f.__doc__
_parser_class = group._subparsers._parser_class
if 'parser' in kwargs:
# use a copy of the given parser
group._subparsers._parser_class = _CopiedArgumentParser
if 'parents' in kwargs:
if not hasattr(f, '_argnames'): # pragma: no cover
f._argnames = []
for p in kwargs['parents']:
f._argnames += p._argnames if hasattr(p, '_argnames') else []
kwargs['parents'] = [p.parser for p in kwargs['parents']]
if args == ():
f.parser = group._subparsers.add_parser(f.__name__, **kwargs)
else:
f.parser = group._subparsers.add_parser(*args, **kwargs)
f.parser.set_defaults(**{'_func_' + group.__name__: f})
f.climax = 'parser' not in kwargs
group._subparsers._parser_class = _parser_class
for arg in getattr(f, '_arguments', []):
f.parser.add_argument(*arg[0], **arg[1])
return f
return decorator |
<SYSTEM_TASK:>
Decorator to define a subgroup.
<END_TASK>
<USER_TASK:>
Description:
def _subgroup(group, *args, **kwargs):
"""Decorator to define a subgroup.
This decorator is used for the group's @group decorator.
""" |
def decorator(f):
f.required = kwargs.pop('required', True)
if 'parents' in kwargs:
if not hasattr(f, '_argnames'): # pragma: no cover
f._argnames = []
for p in kwargs['parents']:
f._argnames += p._argnames if hasattr(p, '_argnames') else []
kwargs['parents'] = [p.parser for p in kwargs['parents']]
if 'help' not in kwargs:
kwargs['help'] = f.__doc__
if args == ():
f.parser = group._subparsers.add_parser(f.__name__, **kwargs)
else:
f.parser = group._subparsers.add_parser(*args, **kwargs)
f.parser.set_defaults(**{'_func_' + group.__name__: f})
f.climax = True
for arg in getattr(f, '_arguments', []):
f.parser.add_argument(*arg[0], **arg[1])
f._subparsers = f.parser.add_subparsers()
f.command = partial(_subcommand, f)
f.group = partial(_subgroup, f)
return f
return decorator |
<SYSTEM_TASK:>
Decorator to define a command group.
<END_TASK>
<USER_TASK:>
Description:
def group(*args, **kwargs):
"""Decorator to define a command group.
The arguments to this decorator are those of the
`ArgumentParser <https://docs.python.org/3/library/argparse.html\
#argumentparser-objects>`_
object constructor.
""" |
def decorator(f):
f.required = kwargs.pop('required', True)
if 'parents' in kwargs:
if not hasattr(f, '_argnames'): # pragma: no cover
f._argnames = []
for p in kwargs['parents']:
f._argnames += p._argnames if hasattr(p, '_argnames') else []
kwargs['parents'] = [p.parser for p in kwargs['parents']]
f.parser = argparse.ArgumentParser(*args, **kwargs)
f.climax = True
for arg in getattr(f, '_arguments', []):
f.parser.add_argument(*arg[0], **arg[1])
f._subparsers = f.parser.add_subparsers()
f.command = partial(_subcommand, f)
f.group = partial(_subgroup, f)
@wraps(f)
def wrapper(args=None):
parsed_args = vars(f.parser.parse_args(args))
# in Python 3.3+, sub-commands are optional by default
# so required parsers need to be validated by hand here
func = f
while '_func_' + func.__name__ in parsed_args:
func = parsed_args.get('_func_' + func.__name__)
if getattr(func, 'required', False):
f.parser.error('too few arguments')
# call the group function
filtered_args = {arg: parsed_args[arg]
for arg in parsed_args.keys()
if arg in getattr(f, '_argnames', [])}
parsed_args = {arg: parsed_args[arg] for arg in parsed_args.keys()
if arg not in filtered_args}
ctx = f(**filtered_args)
# call the sub-command function (or chain)
func = f
while '_func_' + func.__name__ in parsed_args:
func = parsed_args.pop('_func_' + func.__name__)
if getattr(func, 'climax', False):
filtered_args = {arg: parsed_args[arg]
for arg in parsed_args.keys()
if arg in getattr(func, '_argnames', [])}
parsed_args = {arg: parsed_args[arg]
for arg in parsed_args.keys()
if arg not in filtered_args}
else:
# we don't have our metadata for this subparser, so we
# send all remaining args to it
filtered_args = parsed_args
parsed_args = {}
filtered_args.update(ctx or {})
ctx = func(**filtered_args)
return ctx
return wrapper
return decorator |
<SYSTEM_TASK:>
Duplicate argument names processing logic from argparse.
<END_TASK>
<USER_TASK:>
Description:
def _get_dest(*args, **kwargs): # pragma: no cover
"""
Duplicate argument names processing logic from argparse.
argparse stores the variable in the namespace using the provided dest name,
the first long option string, or the first short option string
""" |
prefix_chars = kwargs.get('prefix_chars', '-')
# determine short and long option strings
option_strings = []
long_option_strings = []
for option_string in args:
# strings starting with two prefix characters are long options
option_strings.append(option_string)
if option_string[0] in prefix_chars:
if len(option_string) > 1:
if option_string[1] in prefix_chars:
long_option_strings.append(option_string)
# infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
dest = kwargs.get('dest', None)
if dest is None:
if long_option_strings:
dest_option_string = long_option_strings[0]
else:
dest_option_string = option_strings[0]
dest = dest_option_string.lstrip(prefix_chars)
if not dest:
msg = _('dest= is required for options like %r')
raise ValueError(msg % option_string)
dest = dest.replace('-', '_')
# return the updated dest name
return dest |
<SYSTEM_TASK:>
Decorator to define an argparse option or argument.
<END_TASK>
<USER_TASK:>
Description:
def argument(*args, **kwargs):
"""Decorator to define an argparse option or argument.
The arguments to this decorator are the same as the
`ArgumentParser.add_argument <https://docs.python.org/3/library/\
argparse.html#the-add-argument-method>`_
method.
""" |
def decorator(f):
if not hasattr(f, '_arguments'):
f._arguments = []
if not hasattr(f, '_argnames'):
f._argnames = []
f._arguments.append((args, kwargs))
f._argnames.append(_get_dest(*args, **kwargs))
return f
return decorator |
<SYSTEM_TASK:>
Download firmware to device
<END_TASK>
<USER_TASK:>
Description:
def download(self, protocol, host, user, password,
file_name, rbridge='all'):
"""
Download firmware to device
""" |
urn = "{urn:brocade.com:mgmt:brocade-firmware}"
request_fwdl = self.get_firmware_download_request(protocol, host,
user, password,
file_name, rbridge)
response = self._callback(request_fwdl, 'get')
fwdl_result = None
for item in response.findall('%scluster-output' % urn):
fwdl_result = item.find('%sfwdl-msg' % urn).text
if not fwdl_result:
fwdl_result = response.find('%sfwdl-cmd-msg' % urn).text
return fwdl_result |
<SYSTEM_TASK:>
Add vCenter on the switch
<END_TASK>
<USER_TASK:>
Description:
def add_vcenter(self, **kwargs):
"""
Add vCenter on the switch
Args:
id(str) : Name of an established vCenter
url (bool) : vCenter URL
username (str): Username of the vCenter
password (str): Password of the vCenter
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
None
""" |
config = ET.Element("config")
vcenter = ET.SubElement(config, "vcenter",
xmlns="urn:brocade.com:mgmt:brocade-vswitch")
id = ET.SubElement(vcenter, "id")
id.text = kwargs.pop('id')
credentials = ET.SubElement(vcenter, "credentials")
url = ET.SubElement(credentials, "url")
url.text = kwargs.pop('url')
username = ET.SubElement(credentials, "username")
username.text = kwargs.pop('username')
password = ET.SubElement(credentials, "password")
password.text = kwargs.pop('password')
try:
self._callback(config)
return True
except Exception as error:
logging.error(error)
return False |
<SYSTEM_TASK:>
Activate vCenter on the switch
<END_TASK>
<USER_TASK:>
Description:
def activate_vcenter(self, **kwargs):
"""
Activate vCenter on the switch
Args:
name: (str) : Name of an established vCenter
activate (bool) : Activates the vCenter if activate=True
else deactivates it
callback (function): A function executed upon completion of the
method.
Returns:
Return value of `callback`.
Raises:
None
""" |
name = kwargs.pop('name')
activate = kwargs.pop('activate', True)
vcenter_args = dict(id=name)
method_class = self._brocade_vswitch
if activate:
method_name = 'vcenter_activate'
vcenter_attr = getattr(method_class, method_name)
config = vcenter_attr(**vcenter_args)
output = self._callback(config)
print output
return output
else:
pass |
<SYSTEM_TASK:>
Get vCenter hosts on the switch
<END_TASK>
<USER_TASK:>
Description:
def get_vcenter(self, **kwargs):
"""
Get vCenter hosts on the switch
Args:
callback (function): A function executed upon completion of the
method.
Returns:
Returns a list of vcenters
Raises:
None
""" |
config = ET.Element("config")
urn = "urn:brocade.com:mgmt:brocade-vswitch"
ET.SubElement(config, "vcenter", xmlns=urn)
output = self._callback(config, handler='get_config')
result = []
element = ET.fromstring(str(output))
for vcenter in element.iter('{%s}vcenter'%urn):
vc = {}
vc['name'] = vcenter.find('{%s}id' % urn).text
vc['url'] = (vcenter.find('{%s}credentials' % urn)).find('{%s}url' % urn).text
isactive = vcenter.find('{%s}activate' %urn)
if isactive is None:
vc['isactive'] = False
else:
vc['isactive'] = True
result.append(vc)
return result |
<SYSTEM_TASK:>
Perform authentication on the incoming request.
<END_TASK>
<USER_TASK:>
Description:
def perform_authentication(self):
"""
Perform authentication on the incoming request.
""" |
if not self.authenticators:
return
request.user = None
request.auth = None
for authenticator in self.authenticators:
auth_tuple = authenticator.authenticate()
if auth_tuple:
request.user = auth_tuple[0]
request.auth = auth_tuple[1]
break |
<SYSTEM_TASK:>
Convert the virtualbox config file values for clone_mode into the integers the API requires
<END_TASK>
<USER_TASK:>
Description:
def map_clonemode(vm_info):
"""
Convert the virtualbox config file values for clone_mode into the integers the API requires
""" |
mode_map = {
'state': 0,
'child': 1,
'all': 2
}
if not vm_info:
return DEFAULT_CLONE_MODE
if 'clonemode' not in vm_info:
return DEFAULT_CLONE_MODE
if vm_info['clonemode'] in mode_map:
return mode_map[vm_info['clonemode']]
else:
raise SaltCloudSystemExit(
"Illegal clonemode for virtualbox profile. Legal values are: {}".format(','.join(mode_map.keys()))
) |
<SYSTEM_TASK:>
Stop a running machine.
<END_TASK>
<USER_TASK:>
Description:
def stop(name, call=None):
"""
Stop a running machine.
@param name: Machine to stop
@type name: str
@param call: Must be "action"
@type call: str
""" |
if call != 'action':
raise SaltCloudSystemExit(
'The instance action must be called with -a or --action.'
)
log.info("Stopping machine: %s", name)
vb_stop_vm(name)
machine = vb_get_machine(name)
del machine["name"]
return treat_machine_dict(machine) |
<SYSTEM_TASK:>
Show the details of an image
<END_TASK>
<USER_TASK:>
Description:
def show_image(kwargs, call=None):
"""
Show the details of an image
""" |
if call != 'function':
raise SaltCloudSystemExit(
'The show_image action must be called with -f or --function.'
)
name = kwargs['image']
log.info("Showing image %s", name)
machine = vb_get_machine(name)
ret = {
machine["name"]: treat_machine_dict(machine)
}
del machine["name"]
return ret |
<SYSTEM_TASK:>
Reshard a kinesis stream. Each call to this function will wait until the stream is ACTIVE,
<END_TASK>
<USER_TASK:>
Description:
def reshard(stream_name, desired_size, force=False,
region=None, key=None, keyid=None, profile=None):
"""
Reshard a kinesis stream. Each call to this function will wait until the stream is ACTIVE,
then make a single split or merge operation. This function decides where to split or merge
with the assumption that the ultimate goal is a balanced partition space.
For safety, user must past in force=True; otherwise, the function will dry run.
CLI example::
salt myminion boto_kinesis.reshard my_stream N True region=us-east-1
:return: True if a split or merge was found/performed, False if nothing is needed
""" |
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
stream_response = get_stream_when_active(stream_name, region, key, keyid, profile)
if 'error' in stream_response:
return stream_response
stream_details = stream_response['result']["StreamDescription"]
min_hash_key, max_hash_key, stream_details = get_info_for_reshard(stream_details)
log.debug("found %s open shards, min_hash_key %s max_hash_key %s",
len(stream_details["OpenShards"]), min_hash_key, max_hash_key)
# find the first open shard that doesn't match the desired pattern. When we find it,
# either split or merge (depending on if it's too big or too small), and then return.
for shard_num, shard in enumerate(stream_details["OpenShards"]):
shard_id = shard["ShardId"]
if "EndingSequenceNumber" in shard["SequenceNumberRange"]:
# something went wrong, there's a closed shard in our open shard list
log.debug("this should never happen! closed shard %s", shard_id)
continue
starting_hash_key = shard["HashKeyRange"]["StartingHashKey"]
ending_hash_key = shard["HashKeyRange"]["EndingHashKey"]
# this weird math matches what AWS does when you create a kinesis stream
# with an initial number of shards.
expected_starting_hash_key = (
max_hash_key - min_hash_key) / desired_size * shard_num + shard_num
expected_ending_hash_key = (
max_hash_key - min_hash_key) / desired_size * (shard_num + 1) + shard_num
# fix an off-by-one at the end
if expected_ending_hash_key > max_hash_key:
expected_ending_hash_key = max_hash_key
log.debug(
"Shard %s (%s) should start at %s: %s",
shard_num, shard_id, expected_starting_hash_key,
starting_hash_key == expected_starting_hash_key
)
log.debug(
"Shard %s (%s) should end at %s: %s",
shard_num, shard_id, expected_ending_hash_key,
ending_hash_key == expected_ending_hash_key
)
if starting_hash_key != expected_starting_hash_key:
r['error'] = "starting hash keys mismatch, don't know what to do!"
return r
if ending_hash_key == expected_ending_hash_key:
continue
if ending_hash_key > expected_ending_hash_key + 1:
# split at expected_ending_hash_key
if force:
log.debug("%s should end at %s, actual %s, splitting",
shard_id, expected_ending_hash_key, ending_hash_key)
r = _execute_with_retries(conn,
"split_shard",
StreamName=stream_name,
ShardToSplit=shard_id,
NewStartingHashKey=str(expected_ending_hash_key + 1)) # future lint: disable=blacklisted-function
else:
log.debug("%s should end at %s, actual %s would split",
shard_id, expected_ending_hash_key, ending_hash_key)
if 'error' not in r:
r['result'] = True
return r
else:
# merge
next_shard_id = _get_next_open_shard(stream_details, shard_id)
if not next_shard_id:
r['error'] = "failed to find next shard after {0}".format(shard_id)
return r
if force:
log.debug("%s should continue past %s, merging with %s",
shard_id, ending_hash_key, next_shard_id)
r = _execute_with_retries(conn,
"merge_shards",
StreamName=stream_name,
ShardToMerge=shard_id,
AdjacentShardToMerge=next_shard_id)
else:
log.debug("%s should continue past %s, would merge with %s",
shard_id, ending_hash_key, next_shard_id)
if 'error' not in r:
r['result'] = True
return r
log.debug("No split or merge action necessary")
r['result'] = False
return r |
<SYSTEM_TASK:>
Render the roster file
<END_TASK>
<USER_TASK:>
Description:
def _render(roster_file, **kwargs):
"""
Render the roster file
""" |
renderers = salt.loader.render(__opts__, {})
domain = __opts__.get('roster_domain', '')
try:
result = salt.template.compile_template(roster_file,
renderers,
__opts__['renderer'],
__opts__['renderer_blacklist'],
__opts__['renderer_whitelist'],
mask_value='passw*',
**kwargs)
result.setdefault('host', '{}.{}'.format(os.path.basename(roster_file), domain))
return result
except: # pylint: disable=W0702
log.warning('Unable to render roster file "%s".', roster_file, exc_info=True)
return {} |
<SYSTEM_TASK:>
Generates a random password.
<END_TASK>
<USER_TASK:>
Description:
def password(
self,
length=10,
special_chars=True,
digits=True,
upper_case=True,
lower_case=True):
"""
Generates a random password.
@param length: Integer. Length of a password
@param special_chars: Boolean. Whether to use special characters !@#$%^&*()_+
@param digits: Boolean. Whether to use digits
@param upper_case: Boolean. Whether to use upper letters
@param lower_case: Boolean. Whether to use lower letters
@return: String. Random password
""" |
choices = ""
required_tokens = []
if special_chars:
required_tokens.append(
self.generator.random.choice("!@#$%^&*()_+"))
choices += "!@#$%^&*()_+"
if digits:
required_tokens.append(self.generator.random.choice(string.digits))
choices += string.digits
if upper_case:
required_tokens.append(
self.generator.random.choice(string.ascii_uppercase))
choices += string.ascii_uppercase
if lower_case:
required_tokens.append(
self.generator.random.choice(string.ascii_lowercase))
choices += string.ascii_lowercase
assert len(
required_tokens) <= length, "Required length is shorter than required characters"
# Generate a first version of the password
chars = self.random_choices(choices, length=length)
# Pick some unique locations
random_indexes = set()
while len(random_indexes) < len(required_tokens):
random_indexes.add(
self.generator.random.randint(0, len(chars) - 1))
# Replace them with the required characters
for i, index in enumerate(random_indexes):
chars[index] = required_tokens[i]
return ''.join(chars) |
<SYSTEM_TASK:>
Calculates and returns a control digit for given list of characters basing on Identity Card Number standards.
<END_TASK>
<USER_TASK:>
Description:
def checksum_identity_card_number(characters):
"""
Calculates and returns a control digit for given list of characters basing on Identity Card Number standards.
""" |
weights_for_check_digit = [7, 3, 1, 0, 7, 3, 1, 7, 3]
check_digit = 0
for i in range(3):
check_digit += weights_for_check_digit[i] * (ord(characters[i]) - 55)
for i in range(4, 9):
check_digit += weights_for_check_digit[i] * characters[i]
check_digit %= 10
return check_digit |
<SYSTEM_TASK:>
A simple method that runs a Command.
<END_TASK>
<USER_TASK:>
Description:
def execute_from_command_line(argv=None):
"""A simple method that runs a Command.""" |
if sys.stdout.encoding is None:
print('please set python env PYTHONIOENCODING=UTF-8, example: '
'export PYTHONIOENCODING=UTF-8, when writing to stdout',
file=sys.stderr)
exit(1)
command = Command(argv)
command.execute() |
<SYSTEM_TASK:>
Validates a french catch phrase.
<END_TASK>
<USER_TASK:>
Description:
def _is_catch_phrase_valid(self, catch_phrase):
"""
Validates a french catch phrase.
:param catch_phrase: The catch phrase to validate.
""" |
for word in self.words_which_should_not_appear_twice:
# Fastest way to check if a piece of word does not appear twice.
begin_pos = catch_phrase.find(word)
end_pos = catch_phrase.find(word, begin_pos + 1)
if begin_pos != -1 and begin_pos != end_pos:
return False
return True |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.