1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2024-09-14 20:13:21 +02:00

Do not use str() on exceptions (#46950)

This commit is contained in:
Martin Krizek 2018-11-09 07:59:30 +01:00 committed by GitHub
parent 2436aa1a4e
commit a80c25cbd9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
30 changed files with 76 additions and 66 deletions

View file

@ -274,7 +274,7 @@ class DocCLI(CLI):
except Exception as e:
display.vvv(traceback.format_exc())
raise AnsibleError(
"%s %s missing documentation (or could not parse documentation): %s\n" % (plugin_type, plugin, str(e)))
"%s %s missing documentation (or could not parse documentation): %s\n" % (plugin_type, plugin, to_native(e)))
def find_plugins(self, path, ptype):

View file

@ -39,7 +39,7 @@ from ansible.galaxy.api import GalaxyAPI
from ansible.galaxy.login import GalaxyLogin
from ansible.galaxy.role import GalaxyRole
from ansible.galaxy.token import GalaxyToken
from ansible.module_utils._text import to_text
from ansible.module_utils._text import to_native, to_text
from ansible.playbook.role.requirement import RoleRequirement
try:
@ -361,7 +361,7 @@ class GalaxyCLI(CLI):
raise AnsibleError("Invalid role requirements file")
f.close()
except (IOError, OSError) as e:
raise AnsibleError('Unable to open %s: %s' % (role_file, str(e)))
raise AnsibleError('Unable to open %s: %s' % (role_file, to_native(e)))
else:
# roles were specified directly, so we'll just go out grab them
# (and their dependencies, unless the user doesn't want us to).
@ -397,7 +397,7 @@ class GalaxyCLI(CLI):
try:
installed = role.install()
except AnsibleError as e:
display.warning("- %s was NOT installed successfully: %s " % (role.name, str(e)))
display.warning(u"- %s was NOT installed successfully: %s " % (role.name, to_text(e)))
self.exit_without_ignore()
continue
@ -451,7 +451,7 @@ class GalaxyCLI(CLI):
else:
display.display('- %s is not installed, skipping.' % role_name)
except Exception as e:
raise AnsibleError("Failed to remove role %s: %s" % (role_name, str(e)))
raise AnsibleError("Failed to remove role %s: %s" % (role_name, to_native(e)))
return 0

View file

@ -238,7 +238,7 @@ class GalaxyAPI(object):
done = (data.get('next_link', None) is None)
return results
except Exception as error:
raise AnsibleError("Failed to download the %s list: %s" % (what, str(error)))
raise AnsibleError("Failed to download the %s list: %s" % (what, to_native(error)))
@g_connect
def search_roles(self, search, **kwargs):

View file

@ -32,6 +32,7 @@ from distutils.version import LooseVersion
from shutil import rmtree
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_native, to_text
from ansible.module_utils.urls import open_url
from ansible.playbook.role.requirement import RoleRequirement
from ansible.galaxy.api import GalaxyAPI
@ -189,7 +190,7 @@ class GalaxyRole(object):
temp_file.close()
return temp_file.name
except Exception as e:
display.error("failed to download the file: %s" % str(e))
display.error(u"failed to download the file: %s" % to_text(e))
return False
@ -333,7 +334,7 @@ class GalaxyRole(object):
self.path = self.paths[current + 1]
error = False
if error:
raise AnsibleError("Could not update files in %s: %s" % (self.path, str(e)))
raise AnsibleError("Could not update files in %s: %s" % (self.path, to_native(e)))
# return the parsed yaml metadata
display.display("- %s was installed successfully" % str(self))
@ -341,7 +342,7 @@ class GalaxyRole(object):
try:
os.unlink(tmp_file)
except (OSError, IOError) as e:
display.warning("Unable to remove tmp file (%s): %s" % (tmp_file, str(e)))
display.warning(u"Unable to remove tmp file (%s): %s" % (tmp_file, to_text(e)))
return True
return False

View file

@ -268,7 +268,7 @@ from distutils.version import LooseVersion
from ansible.module_utils.basic import AnsibleModule, get_module_path
from ansible.module_utils.six import b, string_types
from ansible.module_utils._text import to_native
from ansible.module_utils._text import to_native, to_text
def relocate_repo(module, result, repo_dir, old_repo_dir, worktree_dir):
@ -286,7 +286,7 @@ def relocate_repo(module, result, repo_dir, old_repo_dir, worktree_dir):
# if we already moved the .git dir, roll it back
if os.path.exists(repo_dir):
shutil.move(repo_dir, old_repo_dir)
module.fail_json(msg='Unable to move git dir. %s' % str(err))
module.fail_json(msg=u'Unable to move git dir. %s' % to_text(err))
def head_splitter(headfile, remote, module=None, fail_on_error=False):
@ -690,7 +690,7 @@ def get_head_branch(git_path, module, dest, remote, bare=False):
module.fail_json(
msg='Current repo does not have a valid reference to a '
'separate Git dir or it refers to the invalid path',
details=str(err),
details=to_text(err),
)
# Read .git/HEAD for the name of the branch.
# If we're in a detached HEAD state, look up the branch associated with
@ -992,8 +992,8 @@ def create_archive(git_path, module, dest, archive, version, repo, result):
except OSError as e:
module.fail_json(msg="Failed to move %s to %s" %
(new_archive, archive),
details="Error occured while moving : %s"
% to_native(e))
details=u"Error occured while moving : %s"
% to_text(e))
else:
# Perform archive from local directory
git_archive(git_path, module, dest, archive, archive_fmt, version)
@ -1100,7 +1100,7 @@ def main():
module.fail_json(
msg='Current repo does not have a valid reference to a '
'separate Git dir or it refers to the invalid path',
details=str(err),
details=to_text(err),
)
gitconfig = os.path.join(repo_path, 'config')

View file

@ -65,7 +65,7 @@ except ImportError:
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six import binary_type
from ansible.module_utils._text import to_bytes
from ansible.module_utils._text import to_bytes, to_text
def has_boolean_value(module, name):
@ -238,7 +238,7 @@ def semanage_boolean_value(module, name, state):
semanage_commit(module, handle)
semanage_destroy_handle(module, handle)
except Exception as e:
module.fail_json(msg="Failed to manage policy for boolean %s: %s" % (name, str(e)))
module.fail_json(msg=u"Failed to manage policy for boolean %s: %s" % (name, to_text(e)))
return changed

View file

@ -282,7 +282,7 @@ class SysctlModule(object):
rc, out, err = self.module.run_command(sysctl_args)
if rc != 0:
self.module.fail_json(msg="Failed to reload sysctl: %s" % str(out) + str(err))
self.module.fail_json(msg="Failed to reload sysctl: %s" % to_native(out) + to_native(err))
# ==============================================================
# SYSCTL FILE MANAGEMENT
@ -297,7 +297,7 @@ class SysctlModule(object):
with open(self.sysctl_file, "r") as read_file:
lines = read_file.readlines()
except IOError as e:
self.module.fail_json(msg="Failed to open %s: %s" % (self.sysctl_file, to_native(e)))
self.module.fail_json(msg="Failed to open %s: %s" % (to_native(self.sysctl_file), to_native(e)))
for line in lines:
line = line.strip()

View file

@ -19,6 +19,8 @@ import signal
import time
import syslog
from ansible.module_utils._text import to_text
PY3 = sys.version_info[0] == 3
syslog.openlog('ansible-%s' % os.path.basename(__file__))
@ -164,7 +166,7 @@ def _run_module(wrapped_cmd, jid, job_path):
result = {
"failed": 1,
"cmd": wrapped_cmd,
"msg": str(e),
"msg": to_text(e),
"outdata": outdata, # temporary notice only
"stderr": stderr
}

View file

@ -1033,7 +1033,7 @@ class VaultEditor:
with open(filename, "rb") as fh:
data = fh.read()
except Exception as e:
raise AnsibleError(str(e))
raise AnsibleError(to_native(e))
return data

View file

@ -22,6 +22,7 @@ __metaclass__ = type
import os
from ansible.errors import AnsibleParserError, AnsibleError
from ansible.module_utils._text import to_native
from ansible.module_utils.six import iteritems, string_types
from ansible.playbook.attribute import Attribute, FieldAttribute
from ansible.playbook.base import Base
@ -80,7 +81,7 @@ class RoleMetadata(Base):
role_def['name'] = def_parsed['name']
roles.append(role_def)
except AnsibleError as exc:
raise AnsibleParserError(str(exc), obj=role_def, orig_exc=exc)
raise AnsibleParserError(to_native(exc), obj=role_def, orig_exc=exc)
current_role_path = None
if self._owner:

View file

@ -1057,7 +1057,7 @@ class ActionBase(with_metaclass(ABCMeta, object)):
with open(source, 'rb') as src:
src_contents = src.read()
except Exception as e:
raise AnsibleError("Unexpected error while reading source (%s) for diff: %s " % (source, str(e)))
raise AnsibleError("Unexpected error while reading source (%s) for diff: %s " % (source, to_native(e)))
if b"\x00" in src_contents:
diff['src_binary'] = 1

View file

@ -41,7 +41,7 @@ class ActionModule(_ActionModule):
try:
self._handle_template()
except ValueError as exc:
return dict(failed=True, msg=str(exc))
return dict(failed=True, msg=to_text(exc))
result = super(ActionModule, self).run(tmp, task_vars)
del tmp # tmp no longer has any effect

View file

@ -22,6 +22,7 @@ __metaclass__ = type
import time
from datetime import datetime, timedelta
from ansible.module_utils._text import to_text
from ansible.plugins.action import ActionBase
try:
@ -112,7 +113,7 @@ class ActionModule(ActionBase):
except TimedOutException as e:
result['failed'] = True
result['msg'] = str(e)
result['msg'] = to_text(e)
elapsed = datetime.now() - start
result['elapsed'] = elapsed.seconds

View file

@ -70,6 +70,7 @@ try:
except ImportError:
HAS_REQUESTS = False
from ansible.module_utils._text import to_text
from ansible.plugins.callback import CallbackBase
@ -152,7 +153,7 @@ class CallbackModule(CallbackBase):
verify=self.ssl_verify)
r.raise_for_status()
except requests.exceptions.RequestException as err:
print(str(err))
print(to_text(err))
def _build_log(self, data):
logs = []
@ -214,7 +215,7 @@ class CallbackModule(CallbackBase):
verify=self.ssl_verify)
r.raise_for_status()
except requests.exceptions.RequestException as err:
print(str(err))
print(to_text(err))
self.items[host] = []
def append_result(self, result):

View file

@ -24,6 +24,7 @@ import getpass
from base64 import b64encode
from datetime import datetime
from ansible.module_utils._text import to_text
from ansible.module_utils.urls import open_url
from ansible.plugins.callback import CallbackBase
@ -259,4 +260,4 @@ class CallbackModule(CallbackBase):
url_username=self.grafana_user, url_password=self.grafana_password,
http_agent=self.http_agent, force_basic_auth=self.force_basic_auth)
except Exception as e:
self._display.error('Could not submit message to Grafana: %s' % str(e))
self._display.error(u'Could not submit message to Grafana: %s' % to_text(e))

View file

@ -111,7 +111,7 @@ try:
except ImportError:
HAS_FLATDICT = False
from ansible.module_utils._text import to_bytes, to_text, to_native
from ansible.module_utils._text import to_bytes, to_text
from ansible.plugins.callback import CallbackBase
# Todo:
@ -147,7 +147,7 @@ class PlainTextSocketAppender(object):
self.open_connection()
return
except Exception as e:
self._display.vvvv("Unable to connect to Logentries: %s" % str(e))
self._display.vvvv(u"Unable to connect to Logentries: %s" % to_text(e))
root_delay *= 2
if root_delay > self.MAX_DELAY:
@ -247,7 +247,7 @@ class CallbackModule(CallbackBase):
self.use_tls = self.get_option('use_tls')
self.flatten = self.get_option('flatten')
except KeyError as e:
self._display.warning("Missing option for Logentries callback plugin: %s" % to_native(e))
self._display.warning(u"Missing option for Logentries callback plugin: %s" % to_text(e))
self.disabled = True
try:

View file

@ -53,6 +53,7 @@ try:
except ImportError:
cli = None
from ansible.module_utils._text import to_text
from ansible.module_utils.urls import open_url
from ansible.plugins.callback import CallbackBase
@ -124,8 +125,8 @@ class CallbackModule(CallbackBase):
response = open_url(self.webhook_url, data=data)
return response.read()
except Exception as e:
self._display.warning('Could not submit message to Slack: %s' %
str(e))
self._display.warning(u'Could not submit message to Slack: %s' %
to_text(e))
def v2_playbook_on_start(self, playbook):
self.playbook_name = os.path.basename(playbook._file_name)

View file

@ -20,7 +20,7 @@ DOCUMENTATION = '''
import os
from ansible.constants import TREE_DIR
from ansible.module_utils._text import to_bytes
from ansible.module_utils._text import to_bytes, to_text
from ansible.plugins.callback import CallbackBase
from ansible.utils.path import makedirs_safe
@ -53,7 +53,7 @@ class CallbackModule(CallbackBase):
with open(path, 'wb+') as fd:
fd.write(buf)
except (OSError, IOError) as e:
self._display.warning("Unable to write to %s's file: %s" % (hostname, str(e)))
self._display.warning(u"Unable to write to %s's file: %s" % (hostname, to_text(e)))
def result_to_tree(self, result):
if self.tree:

View file

@ -296,7 +296,7 @@ class Connection(NetworkConnectionBase):
ssh_config=ssh_config
)
except SSHUnknownHostError as exc:
raise AnsibleConnectionFailure(str(exc))
raise AnsibleConnectionFailure(to_native(exc))
except ImportError as exc:
raise AnsibleError("connection=netconf is not supported on {0}".format(self._network_os))

View file

@ -145,7 +145,7 @@ from ansible.module_utils.six import iteritems
from ansible.module_utils.six.moves import input
from ansible.plugins.connection import ConnectionBase
from ansible.utils.path import makedirs_safe
from ansible.module_utils._text import to_bytes, to_native
from ansible.module_utils._text import to_bytes, to_native, to_text
try:
from __main__ import display
@ -354,10 +354,10 @@ class Connection(ConnectionBase):
except paramiko.ssh_exception.BadHostKeyException as e:
raise AnsibleConnectionFailure('host key mismatch for %s' % e.hostname)
except Exception as e:
msg = str(e)
if "PID check failed" in msg:
msg = to_text(e)
if u"PID check failed" in msg:
raise AnsibleError("paramiko version issue, please upgrade paramiko on the machine running ansible")
elif "Private key file is encrypted" in msg:
elif u"Private key file is encrypted" in msg:
msg = 'ssh %s@%s:%s : %s\nTo connect as a different user, use -u <username>.' % (
self._play_context.remote_user, self._play_context.remote_addr, port, msg)
raise AnsibleConnectionFailure(msg)
@ -380,10 +380,11 @@ class Connection(ConnectionBase):
self.ssh.get_transport().set_keepalive(5)
chan = self.ssh.get_transport().open_session()
except Exception as e:
msg = "Failed to open session"
if len(str(e)) > 0:
msg += ": %s" % str(e)
raise AnsibleConnectionFailure(msg)
text_e = to_text(e)
msg = u"Failed to open session"
if text_e:
msg += u": %s" % text_e
raise AnsibleConnectionFailure(to_native(msg))
# sudo usually requires a PTY (cf. requiretty option), therefore
# we give it one by default (pty=True in ansible.cfg), and we try

View file

@ -43,7 +43,7 @@ from jinja2.filters import environmentfilter, do_groupby as _do_groupby
from ansible.errors import AnsibleError, AnsibleFilterError
from ansible.module_utils.six import iteritems, string_types, integer_types, reraise
from ansible.module_utils.six.moves import reduce, shlex_quote
from ansible.module_utils._text import to_bytes, to_text
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.module_utils.common.collections import is_sequence
from ansible.module_utils.common._collections_compat import MutableMapping
from ansible.parsing.ajson import AnsibleJSONEncoder
@ -261,7 +261,7 @@ def get_encrypted_password(password, hashtype='sha512', salt=None, salt_size=Non
try:
return passlib_or_crypt(password, hashtype, salt=salt, salt_size=salt_size, rounds=rounds)
except AnsibleError as e:
reraise(AnsibleFilterError, AnsibleFilterError(str(e), orig_exc=e), sys.exc_info()[2])
reraise(AnsibleFilterError, AnsibleFilterError(to_native(e), orig_exc=e), sys.exc_info()[2])
def to_uuid(string):

View file

@ -139,14 +139,14 @@ def logarithm(x, base=math.e):
else:
return math.log(x, base)
except TypeError as e:
raise AnsibleFilterError('log() can only be used on numbers: %s' % str(e))
raise AnsibleFilterError('log() can only be used on numbers: %s' % to_native(e))
def power(x, y):
try:
return math.pow(x, y)
except TypeError as e:
raise AnsibleFilterError('pow() can only be used on numbers: %s' % str(e))
raise AnsibleFilterError('pow() can only be used on numbers: %s' % to_native(e))
def inversepower(x, base=2):
@ -156,7 +156,7 @@ def inversepower(x, base=2):
else:
return math.pow(x, 1.0 / float(base))
except (ValueError, TypeError) as e:
raise AnsibleFilterError('root() can only be used on numbers: %s' % str(e))
raise AnsibleFilterError('root() can only be used on numbers: %s' % to_native(e))
def human_readable(size, isbits=False, unit=None):

View file

@ -27,7 +27,7 @@ import string
from xml.etree.ElementTree import fromstring
from ansible.module_utils._text import to_text
from ansible.module_utils._text import to_native, to_text
from ansible.module_utils.network.common.utils import Template
from ansible.module_utils.six import iteritems, string_types
from ansible.module_utils.common._collections_compat import Mapping
@ -96,7 +96,7 @@ def parse_cli(output, tmpl):
try:
template = Template()
except ImportError as exc:
raise AnsibleError(str(exc))
raise AnsibleError(to_native(exc))
spec = yaml.safe_load(open(tmpl).read())
obj = {}
@ -241,7 +241,7 @@ def parse_cli_textfsm(value, template):
try:
template = open(template)
except IOError as exc:
raise AnsibleError(str(exc))
raise AnsibleError(to_native(exc))
re_table = textfsm.TextFSM(template)
fsm_results = re_table.ParseText(value)
@ -333,7 +333,7 @@ def parse_xml(output, tmpl):
try:
template = Template()
except ImportError as exc:
raise AnsibleError(str(exc))
raise AnsibleError(to_native(exc))
spec = yaml.safe_load(open(tmpl).read())
obj = {}

View file

@ -65,7 +65,7 @@ import os
from ansible.errors import AnsibleError, AnsibleParserError
from ansible.plugins.lookup import LookupBase
from ansible.module_utils.urls import open_url
from ansible.module_utils._text import to_bytes
from ansible.module_utils._text import to_bytes, to_native
from ansible.module_utils.six.moves.urllib.error import HTTPError
try:
@ -118,7 +118,7 @@ class GrafanaAPI:
try:
r = open_url('%s/api/user/using/%s' % (self.grafana_url, self.grafana_org_id), headers=headers, method='POST')
except HTTPError as e:
raise GrafanaAPIException('Unable to switch to organization %s : %s' % (self.grafana_org_id, str(e)))
raise GrafanaAPIException('Unable to switch to organization %s : %s' % (self.grafana_org_id, to_native(e)))
if r.getcode() != 200:
raise GrafanaAPIException('Unable to switch to organization %s : %s' % (self.grafana_org_id, str(r.getcode())))
@ -144,12 +144,12 @@ class GrafanaAPI:
else:
r = open_url('%s/api/search/' % self.grafana_url, headers=headers, method='GET')
except HTTPError as e:
raise GrafanaAPIException('Unable to search dashboards : %s' % str(e))
raise GrafanaAPIException('Unable to search dashboards : %s' % to_native(e))
if r.getcode() == 200:
try:
dashboard_list = json.loads(r.read())
except Exception as e:
raise GrafanaAPIException('Unable to parse json list %s' % str(e))
raise GrafanaAPIException('Unable to parse json list %s' % to_native(e))
else:
raise GrafanaAPIException('Unable to list grafana dashboards : %s' % str(r.getcode()))

View file

@ -23,7 +23,7 @@ import json
import re
from ansible import constants as C
from ansible.module_utils._text import to_text, to_bytes
from ansible.module_utils._text import to_text, to_bytes, to_native
from ansible.errors import AnsibleConnectionFailure, AnsibleError
from ansible.plugins.netconf import NetconfBase
from ansible.plugins.netconf import ensure_connected
@ -116,7 +116,7 @@ class Netconf(NetconfBase):
timeout=obj._play_context.timeout
)
except SSHUnknownHostError as exc:
raise AnsibleConnectionFailure(str(exc))
raise AnsibleConnectionFailure(to_native(exc))
guessed_os = None
for c in m.server_capabilities:

View file

@ -25,6 +25,7 @@ import re
import collections
from ansible import constants as C
from ansible.module_utils._text import to_native
from ansible.module_utils.network.common.netconf import remove_namespaces
from ansible.module_utils.network.iosxr.iosxr import build_xml, etree_find
from ansible.errors import AnsibleConnectionFailure, AnsibleError
@ -111,7 +112,7 @@ class Netconf(NetconfBase):
timeout=obj._play_context.timeout
)
except SSHUnknownHostError as exc:
raise AnsibleConnectionFailure(str(exc))
raise AnsibleConnectionFailure(to_native(exc))
guessed_os = None
for c in m.server_capabilities:

View file

@ -23,7 +23,7 @@ import json
import re
from ansible import constants as C
from ansible.module_utils._text import to_text, to_bytes
from ansible.module_utils._text import to_text, to_bytes, to_native
from ansible.errors import AnsibleConnectionFailure, AnsibleError
from ansible.plugins.netconf import NetconfBase
from ansible.plugins.netconf import ensure_connected
@ -120,7 +120,7 @@ class Netconf(NetconfBase):
timeout=obj._play_context.timeout
)
except SSHUnknownHostError as exc:
raise AnsibleConnectionFailure(str(exc))
raise AnsibleConnectionFailure(to_native(exc))
guessed_os = None
for c in m.server_capabilities:

View file

@ -23,7 +23,7 @@ import json
import re
from ansible import constants as C
from ansible.module_utils._text import to_text, to_bytes
from ansible.module_utils._text import to_text, to_bytes, to_native
from ansible.errors import AnsibleConnectionFailure, AnsibleError
from ansible.plugins.netconf import NetconfBase
from ansible.plugins.netconf import ensure_connected
@ -89,7 +89,7 @@ class Netconf(NetconfBase):
timeout=obj._play_context.timeout
)
except SSHUnknownHostError as exc:
raise AnsibleConnectionFailure(str(exc))
raise AnsibleConnectionFailure(to_native(exc))
guessed_os = None
for c in m.server_capabilities:

View file

@ -969,7 +969,7 @@ class StrategyBase:
for host in included_file._hosts:
iterator.mark_host_failed(host)
self._tqm._failed_hosts[host.name] = True
display.warning(str(e))
display.warning(to_text(e))
continue
# remove hosts from notification list

View file

@ -235,7 +235,7 @@ class StrategyModule(StrategyBase):
except AnsibleError as e:
for host in included_file._hosts:
iterator.mark_host_failed(host)
display.warning(str(e))
display.warning(to_text(e))
continue
for new_block in new_blocks: