1# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
2#
3# This file is part of Ansible
4#
5# Ansible is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation, either version 3 of the License, or
8# (at your option) any later version.
9#
10# Ansible is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
17
18# Make coding more python3-ish
19from __future__ import (absolute_import, division, print_function)
20__metaclass__ = type
21
22import re
23
24from ansible.errors.yaml_strings import (
25    YAML_COMMON_DICT_ERROR,
26    YAML_COMMON_LEADING_TAB_ERROR,
27    YAML_COMMON_PARTIALLY_QUOTED_LINE_ERROR,
28    YAML_COMMON_UNBALANCED_QUOTES_ERROR,
29    YAML_COMMON_UNQUOTED_COLON_ERROR,
30    YAML_COMMON_UNQUOTED_VARIABLE_ERROR,
31    YAML_POSITION_DETAILS,
32    YAML_AND_SHORTHAND_ERROR,
33)
34from ansible.module_utils._text import to_native, to_text
35from ansible.module_utils.common._collections_compat import Sequence
36
37
38class AnsibleError(Exception):
39    '''
40    This is the base class for all errors raised from Ansible code,
41    and can be instantiated with two optional parameters beyond the
42    error message to control whether detailed information is displayed
43    when the error occurred while parsing a data file of some kind.
44
45    Usage:
46
47        raise AnsibleError('some message here', obj=obj, show_content=True)
48
49    Where "obj" is some subclass of ansible.parsing.yaml.objects.AnsibleBaseYAMLObject,
50    which should be returned by the DataLoader() class.
51    '''
52
53    def __init__(self, message="", obj=None, show_content=True, suppress_extended_error=False, orig_exc=None):
54        super(AnsibleError, self).__init__(message)
55
56        # we import this here to prevent an import loop problem,
57        # since the objects code also imports ansible.errors
58        from ansible.parsing.yaml.objects import AnsibleBaseYAMLObject
59
60        self._obj = obj
61        self._show_content = show_content
62        if obj and isinstance(obj, AnsibleBaseYAMLObject):
63            extended_error = self._get_extended_error()
64            if extended_error and not suppress_extended_error:
65                self.message = '%s\n\n%s' % (to_native(message), to_native(extended_error))
66            else:
67                self.message = '%s' % to_native(message)
68        else:
69            self.message = '%s' % to_native(message)
70        if orig_exc:
71            self.orig_exc = orig_exc
72
73    def __str__(self):
74        return self.message
75
76    def __repr__(self):
77        return self.message
78
79    def _get_error_lines_from_file(self, file_name, line_number):
80        '''
81        Returns the line in the file which corresponds to the reported error
82        location, as well as the line preceding it (if the error did not
83        occur on the first line), to provide context to the error.
84        '''
85
86        target_line = ''
87        prev_line = ''
88
89        with open(file_name, 'r') as f:
90            lines = f.readlines()
91
92            # In case of a YAML loading error, PyYAML will report the very last line
93            # as the location of the error. Avoid an index error here in order to
94            # return a helpful message.
95            file_length = len(lines)
96            if line_number >= file_length:
97                line_number = file_length - 1
98
99            # If target_line contains only whitespace, move backwards until
100            # actual code is found. If there are several empty lines after target_line,
101            # the error lines would just be blank, which is not very helpful.
102            target_line = lines[line_number]
103            while not target_line.strip():
104                line_number -= 1
105                target_line = lines[line_number]
106
107            if line_number > 0:
108                prev_line = lines[line_number - 1]
109
110        return (target_line, prev_line)
111
112    def _get_extended_error(self):
113        '''
114        Given an object reporting the location of the exception in a file, return
115        detailed information regarding it including:
116
117          * the line which caused the error as well as the one preceding it
118          * causes and suggested remedies for common syntax errors
119
120        If this error was created with show_content=False, the reporting of content
121        is suppressed, as the file contents may be sensitive (ie. vault data).
122        '''
123
124        error_message = ''
125
126        try:
127            (src_file, line_number, col_number) = self._obj.ansible_pos
128            error_message += YAML_POSITION_DETAILS % (src_file, line_number, col_number)
129            if src_file not in ('<string>', '<unicode>') and self._show_content:
130                (target_line, prev_line) = self._get_error_lines_from_file(src_file, line_number - 1)
131                target_line = to_text(target_line)
132                prev_line = to_text(prev_line)
133                if target_line:
134                    stripped_line = target_line.replace(" ", "")
135
136                    # Check for k=v syntax in addition to YAML syntax and set the appropriate error position,
137                    # arrow index
138                    if re.search(r'\w+(\s+)?=(\s+)?[\w/-]+', prev_line):
139                        error_position = prev_line.rstrip().find('=')
140                        arrow_line = (" " * error_position) + "^ here"
141                        error_message = YAML_POSITION_DETAILS % (src_file, line_number - 1, error_position + 1)
142                        error_message += "\nThe offending line appears to be:\n\n%s\n%s\n\n" % (prev_line.rstrip(), arrow_line)
143                        error_message += YAML_AND_SHORTHAND_ERROR
144                    else:
145                        arrow_line = (" " * (col_number - 1)) + "^ here"
146                        error_message += "\nThe offending line appears to be:\n\n%s\n%s\n%s\n" % (prev_line.rstrip(), target_line.rstrip(), arrow_line)
147
148                    # TODO: There may be cases where there is a valid tab in a line that has other errors.
149                    if '\t' in target_line:
150                        error_message += YAML_COMMON_LEADING_TAB_ERROR
151                    # common error/remediation checking here:
152                    # check for unquoted vars starting lines
153                    if ('{{' in target_line and '}}' in target_line) and ('"{{' not in target_line or "'{{" not in target_line):
154                        error_message += YAML_COMMON_UNQUOTED_VARIABLE_ERROR
155                    # check for common dictionary mistakes
156                    elif ":{{" in stripped_line and "}}" in stripped_line:
157                        error_message += YAML_COMMON_DICT_ERROR
158                    # check for common unquoted colon mistakes
159                    elif (len(target_line) and
160                            len(target_line) > 1 and
161                            len(target_line) > col_number and
162                            target_line[col_number] == ":" and
163                            target_line.count(':') > 1):
164                        error_message += YAML_COMMON_UNQUOTED_COLON_ERROR
165                    # otherwise, check for some common quoting mistakes
166                    else:
167                        # FIXME: This needs to split on the first ':' to account for modules like lineinfile
168                        # that may have lines that contain legitimate colons, e.g., line: 'i ALL= (ALL) NOPASSWD: ALL'
169                        # and throw off the quote matching logic.
170                        parts = target_line.split(":")
171                        if len(parts) > 1:
172                            middle = parts[1].strip()
173                            match = False
174                            unbalanced = False
175
176                            if middle.startswith("'") and not middle.endswith("'"):
177                                match = True
178                            elif middle.startswith('"') and not middle.endswith('"'):
179                                match = True
180
181                            if (len(middle) > 0 and
182                                    middle[0] in ['"', "'"] and
183                                    middle[-1] in ['"', "'"] and
184                                    target_line.count("'") > 2 or
185                                    target_line.count('"') > 2):
186                                unbalanced = True
187
188                            if match:
189                                error_message += YAML_COMMON_PARTIALLY_QUOTED_LINE_ERROR
190                            if unbalanced:
191                                error_message += YAML_COMMON_UNBALANCED_QUOTES_ERROR
192
193        except (IOError, TypeError):
194            error_message += '\n(could not open file to display line)'
195        except IndexError:
196            error_message += '\n(specified line no longer in file, maybe it changed?)'
197
198        return error_message
199
200
201class AnsibleAssertionError(AnsibleError, AssertionError):
202    '''Invalid assertion'''
203    pass
204
205
206class AnsibleOptionsError(AnsibleError):
207    ''' bad or incomplete options passed '''
208    pass
209
210
211class AnsibleParserError(AnsibleError):
212    ''' something was detected early that is wrong about a playbook or data file '''
213    pass
214
215
216class AnsibleInternalError(AnsibleError):
217    ''' internal safeguards tripped, something happened in the code that should never happen '''
218    pass
219
220
221class AnsibleRuntimeError(AnsibleError):
222    ''' ansible had a problem while running a playbook '''
223    pass
224
225
226class AnsibleModuleError(AnsibleRuntimeError):
227    ''' a module failed somehow '''
228    pass
229
230
231class AnsibleConnectionFailure(AnsibleRuntimeError):
232    ''' the transport / connection_plugin had a fatal error '''
233    pass
234
235
236class AnsibleAuthenticationFailure(AnsibleConnectionFailure):
237    '''invalid username/password/key'''
238    pass
239
240
241class AnsibleCallbackError(AnsibleRuntimeError):
242    ''' a callback failure '''
243    pass
244
245
246class AnsibleTemplateError(AnsibleRuntimeError):
247    '''A template related errror'''
248    pass
249
250
251class AnsibleFilterError(AnsibleTemplateError):
252    ''' a templating failure '''
253    pass
254
255
256class AnsibleLookupError(AnsibleTemplateError):
257    ''' a lookup failure '''
258    pass
259
260
261class AnsibleUndefinedVariable(AnsibleTemplateError):
262    ''' a templating failure '''
263    pass
264
265
266class AnsibleFileNotFound(AnsibleRuntimeError):
267    ''' a file missing failure '''
268
269    def __init__(self, message="", obj=None, show_content=True, suppress_extended_error=False, orig_exc=None, paths=None, file_name=None):
270
271        self.file_name = file_name
272        self.paths = paths
273
274        if message:
275            message += "\n"
276        if self.file_name:
277            message += "Could not find or access '%s'" % to_text(self.file_name)
278        else:
279            message += "Could not find file"
280
281        if self.paths and isinstance(self.paths, Sequence):
282            searched = to_text('\n\t'.join(self.paths))
283            if message:
284                message += "\n"
285            message += "Searched in:\n\t%s" % searched
286
287        message += " on the Ansible Controller.\nIf you are using a module and expect the file to exist on the remote, see the remote_src option"
288
289        super(AnsibleFileNotFound, self).__init__(message=message, obj=obj, show_content=show_content,
290                                                  suppress_extended_error=suppress_extended_error, orig_exc=orig_exc)
291
292
293# These Exceptions are temporary, using them as flow control until we can get a better solution.
294# DO NOT USE as they will probably be removed soon.
295# We will port the action modules in our tree to use a context manager instead.
296class AnsibleAction(AnsibleRuntimeError):
297    ''' Base Exception for Action plugin flow control '''
298
299    def __init__(self, message="", obj=None, show_content=True, suppress_extended_error=False, orig_exc=None, result=None):
300
301        super(AnsibleAction, self).__init__(message=message, obj=obj, show_content=show_content,
302                                            suppress_extended_error=suppress_extended_error, orig_exc=orig_exc)
303        if result is None:
304            self.result = {}
305        else:
306            self.result = result
307
308
309class AnsibleActionSkip(AnsibleAction):
310    ''' an action runtime skip'''
311
312    def __init__(self, message="", obj=None, show_content=True, suppress_extended_error=False, orig_exc=None, result=None):
313        super(AnsibleActionSkip, self).__init__(message=message, obj=obj, show_content=show_content,
314                                                suppress_extended_error=suppress_extended_error, orig_exc=orig_exc, result=result)
315        self.result.update({'skipped': True, 'msg': message})
316
317
318class AnsibleActionFail(AnsibleAction):
319    ''' an action runtime failure'''
320    def __init__(self, message="", obj=None, show_content=True, suppress_extended_error=False, orig_exc=None, result=None):
321        super(AnsibleActionFail, self).__init__(message=message, obj=obj, show_content=show_content,
322                                                suppress_extended_error=suppress_extended_error, orig_exc=orig_exc, result=result)
323        self.result.update({'failed': True, 'msg': message})
324
325
326class _AnsibleActionDone(AnsibleAction):
327    ''' an action runtime early exit'''
328    pass
329
330
331class AnsibleFilterTypeError(AnsibleTemplateError, TypeError):
332    ''' a Jinja filter templating failure due to bad type'''
333    pass
334