mirror of https://github.com/ansible/ansible.git
Network Module: EOS (#16158)
* add new module network * move EOS to NetworkModule * shell.py Python 3.x compatibility * implements the Command class through the connection for eos This implements a new Command class that specifies the cli command and output format. This removes the need to batch commands through the connection * initial add of netcmd modulepull/16371/head
parent
17447ff035
commit
5dccff29bf
@ -0,0 +1,202 @@
|
||||
#
|
||||
# (c) 2015 Peter Sprygada, <psprygada@ansible.com>
|
||||
#
|
||||
# This file is part of Ansible
|
||||
#
|
||||
# Ansible is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Ansible is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
import re
|
||||
import time
|
||||
import collections
|
||||
import itertools
|
||||
import shlex
|
||||
|
||||
from ansible.module_utils.basic import BOOLEANS_TRUE, BOOLEANS_FALSE
|
||||
|
||||
class Conditional(object):
|
||||
"""Used in command modules to evaluate waitfor conditions
|
||||
"""
|
||||
|
||||
OPERATORS = {
|
||||
'eq': ['eq', '=='],
|
||||
'neq': ['neq', 'ne', '!='],
|
||||
'gt': ['gt', '>'],
|
||||
'ge': ['ge', '>='],
|
||||
'lt': ['lt', '<'],
|
||||
'le': ['le', '<='],
|
||||
'contains': ['contains'],
|
||||
'matches': ['matches']
|
||||
}
|
||||
|
||||
def __init__(self, conditional, encoding='json'):
|
||||
self.raw = conditional
|
||||
self.encoding = encoding
|
||||
|
||||
key, op, val = shlex.split(conditional)
|
||||
self.key = key
|
||||
self.func = self.func(op)
|
||||
self.value = self._cast_value(val)
|
||||
|
||||
def __call__(self, data):
|
||||
value = self.get_value(dict(result=data))
|
||||
return self.func(value)
|
||||
|
||||
def _cast_value(self, value):
|
||||
if value in BOOLEANS_TRUE:
|
||||
return True
|
||||
elif value in BOOLEANS_FALSE:
|
||||
return False
|
||||
elif re.match(r'^\d+\.d+$', value):
|
||||
return float(value)
|
||||
elif re.match(r'^\d+$', value):
|
||||
return int(value)
|
||||
else:
|
||||
return unicode(value)
|
||||
|
||||
def func(self, oper):
|
||||
for func, operators in self.OPERATORS.items():
|
||||
if oper in operators:
|
||||
return getattr(self, func)
|
||||
raise AttributeError('unknown operator: %s' % oper)
|
||||
|
||||
def get_value(self, result):
|
||||
if self.encoding in ['json', 'text']:
|
||||
return self.get_json(result)
|
||||
elif self.encoding == 'xml':
|
||||
return self.get_xml(result.get('result'))
|
||||
|
||||
def get_xml(self, result):
|
||||
parts = self.key.split('.')
|
||||
|
||||
value_index = None
|
||||
match = re.match(r'^\S+(\[)(\d+)\]', parts[-1])
|
||||
if match:
|
||||
start, end = match.regs[1]
|
||||
parts[-1] = parts[-1][0:start]
|
||||
value_index = int(match.group(2))
|
||||
|
||||
path = '/'.join(parts[1:])
|
||||
path = '/%s' % path
|
||||
path += '/text()'
|
||||
|
||||
index = int(re.match(r'result\[(\d+)\]', parts[0]).group(1))
|
||||
values = result[index].xpath(path)
|
||||
|
||||
if value_index is not None:
|
||||
return values[value_index].strip()
|
||||
return [v.strip() for v in values]
|
||||
|
||||
def get_json(self, result):
|
||||
parts = re.split(r'\.(?=[^\]]*(?:\[|$))', self.key)
|
||||
for part in parts:
|
||||
match = re.findall(r'\[(\S+?)\]', part)
|
||||
if match:
|
||||
key = part[:part.find('[')]
|
||||
result = result[key]
|
||||
for m in match:
|
||||
try:
|
||||
m = int(m)
|
||||
except ValueError:
|
||||
m = str(m)
|
||||
result = result[m]
|
||||
else:
|
||||
result = result.get(part)
|
||||
return result
|
||||
|
||||
def number(self, value):
|
||||
if '.' in str(value):
|
||||
return float(value)
|
||||
else:
|
||||
return int(value)
|
||||
|
||||
def eq(self, value):
|
||||
return value == self.value
|
||||
|
||||
def neq(self, value):
|
||||
return value != self.value
|
||||
|
||||
def gt(self, value):
|
||||
return self.number(value) > self.value
|
||||
|
||||
def ge(self, value):
|
||||
return self.number(value) >= self.value
|
||||
|
||||
def lt(self, value):
|
||||
return self.number(value) < self.value
|
||||
|
||||
def le(self, value):
|
||||
return self.number(value) <= self.value
|
||||
|
||||
def contains(self, value):
|
||||
return str(self.value) in value
|
||||
|
||||
def matches(self, value):
|
||||
match = re.search(value, self.value, re.M)
|
||||
return match is not None
|
||||
|
||||
|
||||
class FailedConditionsError(Exception):
|
||||
|
||||
def __init__(self, msg, failed_conditions):
|
||||
super(FailedConditionsError, self).__init__(msg)
|
||||
self.failed_conditions = failed_conditions
|
||||
|
||||
class CommandRunner(collections.Mapping):
|
||||
|
||||
def __init__(self, module):
|
||||
self.module = module
|
||||
|
||||
self.items = dict()
|
||||
self.conditionals = set()
|
||||
|
||||
self.retries = 10
|
||||
self.interval = 1
|
||||
|
||||
def __getitem__(self, key):
|
||||
return self.items[key]
|
||||
|
||||
def __len__(self):
|
||||
return len(self.items)
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.items)
|
||||
|
||||
def add_command(self, command, output=None):
|
||||
self.module.cli.add_commands(command, output=output)
|
||||
|
||||
def add_conditional(self, condition):
|
||||
self.conditionals.add(Conditional(condition))
|
||||
|
||||
def run_commands(self):
|
||||
responses = self.module.cli.run_commands()
|
||||
for cmd, resp in itertools.izip(self.module.cli.commands, responses):
|
||||
self.items[str(cmd)] = resp
|
||||
|
||||
def run(self):
|
||||
while self.retries > 0:
|
||||
self.run_commands()
|
||||
for item in list(self.conditionals):
|
||||
if item(self.items.values()):
|
||||
self.conditionals.remove(item)
|
||||
|
||||
if not self.conditionals:
|
||||
break
|
||||
|
||||
time.sleep(self.interval)
|
||||
self.retries -= 1
|
||||
else:
|
||||
failed_conditions = [item.raw for item in self.conditionals]
|
||||
raise FailedConditionsError('timeout waiting for value', failed_conditions)
|
||||
|
@ -0,0 +1,282 @@
|
||||
#
|
||||
# (c) 2015 Peter Sprygada, <psprygada@ansible.com>
|
||||
#
|
||||
# This file is part of Ansible
|
||||
#
|
||||
# Ansible is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# Ansible is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule
|
||||
from ansible.module_utils.basic import env_fallback, get_exception
|
||||
from ansible.module_utils.shell import Shell, ShellError, HAS_PARAMIKO
|
||||
|
||||
NET_TRANSPORT_ARGS = dict(
|
||||
host=dict(required=True),
|
||||
port=dict(type='int'),
|
||||
username=dict(fallback=(env_fallback, ['ANSIBLE_NET_USERNAME'])),
|
||||
password=dict(no_log=True, fallback=(env_fallback, ['ANSIBLE_NET_PASSWORD'])),
|
||||
ssh_keyfile=dict(fallback=(env_fallback, ['ANSIBLE_NET_SSH_KEYFILE']), type='path'),
|
||||
authorize=dict(default=False, fallback=(env_fallback, ['ANSIBLE_NET_AUTHORIZE']), type='bool'),
|
||||
auth_pass=dict(no_log=True, fallback=(env_fallback, ['ANSIBLE_NET_AUTH_PASS'])),
|
||||
provider=dict(type='dict'),
|
||||
transport=dict(choices=list()),
|
||||
timeout=dict(default=10, type='int')
|
||||
)
|
||||
|
||||
NET_CONNECTION_ARGS = dict()
|
||||
|
||||
NET_CONNECTIONS = dict()
|
||||
|
||||
|
||||
def to_list(val):
|
||||
if isinstance(val, (list, tuple)):
|
||||
return list(val)
|
||||
elif val is not None:
|
||||
return [val]
|
||||
else:
|
||||
return list()
|
||||
|
||||
def connect(module):
|
||||
try:
|
||||
if not module.connected:
|
||||
module.connection.connect(module.params)
|
||||
if module.params['authorize']:
|
||||
module.connection.authorize(module.params)
|
||||
except NetworkError:
|
||||
exc = get_exception()
|
||||
module.fail_json(msg=exc.message)
|
||||
|
||||
def disconnect(module):
|
||||
try:
|
||||
if module.connected:
|
||||
module.connection.disconnect()
|
||||
except NetworkError:
|
||||
exc = get_exception()
|
||||
module.fail_json(msg=exc.message)
|
||||
|
||||
|
||||
class Command(object):
|
||||
|
||||
def __init__(self, command, output=None, prompt=None, response=None):
|
||||
self.command = command
|
||||
self.output = output
|
||||
self.prompt = prompt
|
||||
self.response = response
|
||||
self.conditions = set()
|
||||
|
||||
def __str__(self):
|
||||
return self.command
|
||||
|
||||
class Cli(object):
|
||||
|
||||
def __init__(self, connection):
|
||||
self.connection = connection
|
||||
self.default_output = connection.default_output or 'text'
|
||||
self.commands = list()
|
||||
|
||||
def __call__(self, commands, output=None):
|
||||
commands = self.to_command(commands, output)
|
||||
return self.connection.run_commands(commands)
|
||||
|
||||
def to_command(self, commands, output=None):
|
||||
output = output or self.default_output
|
||||
objects = list()
|
||||
for cmd in to_list(commands):
|
||||
if not isinstance(cmd, Command):
|
||||
cmd = Command(cmd, output)
|
||||
objects.append(cmd)
|
||||
return objects
|
||||
|
||||
def add_commands(self, commands, output=None):
|
||||
commands = self.to_command(commands, output)
|
||||
self.commands.extend(commands)
|
||||
|
||||
def run_commands(self):
|
||||
return self.connection.run_commands(self.commands)
|
||||
|
||||
class Config(object):
|
||||
|
||||
def __init__(self, connection):
|
||||
self.connection = connection
|
||||
|
||||
def invoke(self, method, *args, **kwargs):
|
||||
try:
|
||||
return method(*args, **kwargs)
|
||||
except AttributeError:
|
||||
exc = get_exception()
|
||||
raise NetworkError('undefined method "%s"' % method.__name__, exc=str(exc))
|
||||
except NetworkError:
|
||||
if raise_exc:
|
||||
raise
|
||||
exc = get_exception()
|
||||
self.fail_json(msg=exc.message, **exc.kwargs)
|
||||
except NotImplementedError:
|
||||
raise NetworkError('method not supported "%s"' % method.__name__)
|
||||
|
||||
def __call__(self, commands):
|
||||
lines = to_list(commands)
|
||||
return self.invoke(self.connection.configure, commands)
|
||||
|
||||
def load_config(self, commands, **kwargs):
|
||||
commands = to_list(commands)
|
||||
return self.invoke(self.connection.load_config, commands, **kwargs)
|
||||
|
||||
def get_config(self, **kwargs):
|
||||
return self.invoke(self.connection.get_config, **kwargs)
|
||||
|
||||
def commit_config(self, **kwargs):
|
||||
return self.invoke(self.connection.commit_config, **kwargs)
|
||||
|
||||
def abort_config(self, **kwargs):
|
||||
return self.invoke(self.connection.abort_config, **kwargs)
|
||||
|
||||
def save_config(self):
|
||||
return self.invoke(self.connection.save_config)
|
||||
|
||||
|
||||
class NetworkError(Exception):
|
||||
|
||||
def __init__(self, msg, **kwargs):
|
||||
super(NetworkError, self).__init__(msg)
|
||||
self.kwargs = kwargs
|
||||
|
||||
|
||||
class NetworkModule(AnsibleModule):
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(NetworkModule, self).__init__(*args, **kwargs)
|
||||
self.connection = None
|
||||
self._cli = None
|
||||
self._config = None
|
||||
|
||||
@property
|
||||
def cli(self):
|
||||
if not self.connected:
|
||||
connect(self)
|
||||
if self._cli:
|
||||
return self._cli
|
||||
self._cli = Cli(self.connection)
|
||||
return self._cli
|
||||
|
||||
@property
|
||||
def config(self):
|
||||
if not self.connected:
|
||||
connect(self)
|
||||
if self._config:
|
||||
return self._config
|
||||
self._config = Config(self.connection)
|
||||
return self._config
|
||||
|
||||
@property
|
||||
def connected(self):
|
||||
return self.connection._connected
|
||||
|
||||
def _load_params(self):
|
||||
super(NetworkModule, self)._load_params()
|
||||
provider = self.params.get('provider') or dict()
|
||||
for key, value in provider.items():
|
||||
for args in [NET_TRANSPORT_ARGS, NET_CONNECTION_ARGS]:
|
||||
if key in args:
|
||||
if self.params.get(key) is None and value is not None:
|
||||
self.params[key] = value
|
||||
|
||||
|
||||
class NetCli(object):
|
||||
"""Basic paramiko-based ssh transport any NetworkModule can use."""
|
||||
|
||||
def __init__(self):
|
||||
if not HAS_PARAMIKO:
|
||||
raise NetworkError(
|
||||
msg='paramiko is required but does not appear to be installed. '
|
||||
'It can be installed using `pip install paramiko`'
|
||||
)
|
||||
|
||||
self.shell = None
|
||||
self._connected = False
|
||||
self.default_output = 'text'
|
||||
|
||||
def connect(self, params, kickstart, **kwargs):
|
||||
host = params['host']
|
||||
port = params.get('port') or 22
|
||||
|
||||
username = params['username']
|
||||
password = params.get('password')
|
||||
key_file = params.get('ssh_keyfile')
|
||||
timeout = params['timeout']
|
||||
|
||||
try:
|
||||
self.shell = Shell(
|
||||
kickstart=kickstart,
|
||||
prompts_re=self.CLI_PROMPTS_RE,
|
||||
errors_re=self.CLI_ERRORS_RE,
|
||||
)
|
||||
self.shell.open(
|
||||
host, port=port, username=username, password=password,
|
||||
key_filename=key_file, timeout=timeout,
|
||||
)
|
||||
except ShellError:
|
||||
exc = get_exception()
|
||||
raise NetworkError(
|
||||
msg='failed to connect to %s:%s' % (host, port), exc=str(exc)
|
||||
)
|
||||
|
||||
def disconnect(self, **kwargs):
|
||||
self._connected = False
|
||||
self.shell.close()
|
||||
|
||||
def execute(self, commands, **kwargs):
|
||||
try:
|
||||
return self.shell.send(commands)
|
||||
except ShellError:
|
||||
exc = get_exception()
|
||||
raise NetworkError(exc.message, commands=commands)
|
||||
|
||||
|
||||
def get_module(connect_on_load=True, **kwargs):
|
||||
argument_spec = NET_TRANSPORT_ARGS.copy()
|
||||
argument_spec['transport']['choices'] = NET_CONNECTIONS.keys()
|
||||
argument_spec.update(NET_CONNECTION_ARGS.copy())
|
||||
|
||||
if kwargs.get('argument_spec'):
|
||||
argument_spec.update(kwargs['argument_spec'])
|
||||
kwargs['argument_spec'] = argument_spec
|
||||
|
||||
module = NetworkModule(**kwargs)
|
||||
|
||||
try:
|
||||
transport = module.params['transport'] or '__default__'
|
||||
cls = NET_CONNECTIONS[transport]
|
||||
module.connection = cls()
|
||||
except KeyError:
|
||||
module.fail_json(msg='Unknown transport or no default transport specified')
|
||||
except (TypeError, NetworkError):
|
||||
exc = get_exception()
|
||||
module.fail_json(msg=exc.message)
|
||||
|
||||
if connect_on_load:
|
||||
connect(module)
|
||||
|
||||
return module
|
||||
|
||||
def register_transport(transport, default=False):
|
||||
def register(cls):
|
||||
NET_CONNECTIONS[transport] = cls
|
||||
if default:
|
||||
NET_CONNECTIONS['__default__'] = cls
|
||||
return cls
|
||||
return register
|
||||
|
||||
def add_argument(key, value):
|
||||
NET_CONNECTION_ARGS[key] = value
|
||||
|
Loading…
Reference in New Issue