Exemplo n.º 1
0
    def run_commands(self,
                     commands=None,
                     check_rc=True,
                     return_timestamps=False):
        if commands is None:
            raise ValueError("'commands' value is required")

        responses = list()
        timestamps = list()
        for cmd in to_list(commands):
            if not isinstance(cmd, Mapping):
                cmd = {'command': cmd}

            output = cmd.pop('output', None)
            if output:
                raise ValueError(
                    "'output' value %s is not supported for run_commands" %
                    output)

            try:
                out = self.send_command(**cmd)
                timestamp = get_timestamp()
            except AnsibleConnectionFailure as e:
                if check_rc:
                    raise
                out = getattr(e, 'err', to_text(e))

            responses.append(out)
            timestamps.append(timestamp)

        if return_timestamps:
            return responses, timestamps
        else:
            return responses
Exemplo n.º 2
0
        def load_from_file(*args, **kwargs):
            module, commands = args
            output = list()
            timestamps = list()

            for item in commands:
                try:
                    command = item['command']
                except Exception:
                    command = item
                filename = str(command).replace(' ', '_')
                output.append(load_fixture(filename))
                timestamps.append(get_timestamp())
            return output, timestamps
Exemplo n.º 3
0
        def load_from_file(*args, **kwargs):
            module, commands = args
            output = list()
            timestamps = list()

            for item in commands:
                try:
                    obj = json.loads(item['command'])
                    command = obj['command']
                except ValueError:
                    command = item['command']
                filename = str(command).replace(' ', '_')
                output.append(load_fixture(filename))
                timestamps.append(get_timestamp())
            return output, timestamps
Exemplo n.º 4
0
    def run_commands(self,
                     commands=None,
                     check_rc=True,
                     return_timestamps=False):
        if commands is None:
            raise ValueError("'commands' value is required")
        responses = list()
        timestamps = list()
        for cmd in to_list(commands):
            if not isinstance(cmd, Mapping):
                cmd = {'command': cmd}

            output = cmd.pop('output', None)
            if output:
                raise ValueError(
                    "'output' value %s is not supported for run_commands" %
                    output)

            try:
                timestamp = get_timestamp()
                out = self.send_command(**cmd)
            except AnsibleConnectionFailure as e:
                if check_rc:
                    raise
                out = getattr(e, 'err', e)

            if out is not None:
                try:
                    out = to_text(out, errors='surrogate_or_strict').strip()
                except UnicodeError:
                    raise ConnectionError(
                        message=u'Failed to decode output from %s: %s' %
                        (cmd, to_text(out)))

                try:
                    out = json.loads(out)
                except ValueError:
                    pass

                responses.append(out)
                timestamps.append(timestamp)
        if return_timestamps:
            return responses, timestamps
        else:
            return responses
Exemplo n.º 5
0
    def send_request(self, commands, output='text', check_status=True,
                     return_error=False, opts=None):
        # only 10 show commands can be encoded in each request
        # messages sent to the remote device
        if opts is None:
            opts = {}
        if output != 'config':
            commands = collections.deque(to_list(commands))
            stack = list()
            requests = list()

            while commands:
                stack.append(commands.popleft())
                if len(stack) == 10:
                    body = self._request_builder(stack, output)
                    data = self._module.jsonify(body)
                    requests.append(data)
                    stack = list()

            if stack:
                body = self._request_builder(stack, output)
                data = self._module.jsonify(body)
                requests.append(data)

        else:
            body = self._request_builder(commands, 'config')
            requests = [self._module.jsonify(body)]

        headers = {'Content-Type': 'application/json'}
        result = list()
        timestamps = list()
        timeout = self._module.params['timeout']
        use_proxy = self._module.params['provider']['use_proxy']

        for req in requests:
            if self._nxapi_auth:
                headers['Cookie'] = self._nxapi_auth

            timestamp = get_timestamp()
            response, headers = fetch_url(
                self._module, self._url, data=req, headers=headers,
                timeout=timeout, method='POST', use_proxy=use_proxy
            )
            self._nxapi_auth = headers.get('set-cookie')

            if opts.get('ignore_timeout') and re.search(r'(-1|5\d\d)', str(headers['status'])):
                result.append(headers['status'])
                return result
            elif headers['status'] != 200:
                self._error(**headers)

            try:
                response = self._module.from_json(response.read())
            except ValueError:
                self._module.fail_json(msg='unable to parse response')

            if response['ins_api'].get('outputs'):
                output = response['ins_api']['outputs']['output']
                for item in to_list(output):
                    if check_status is True and item['code'] != '200':
                        if return_error:
                            result.append(item)
                        else:
                            self._error(output=output, **item)
                    elif 'body' in item:
                        result.append(item['body'])
                        timestamps.append(timestamp)
                    # else:
                        # error in command but since check_status is disabled
                        # silently drop it.
                        # result.append(item['msg'])

            return result, timestamps