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 ansible.constants as C
23from ansible.errors import AnsibleParserError
24from ansible.playbook.attribute import FieldAttribute
25from ansible.playbook.base import Base
26from ansible.playbook.conditional import Conditional
27from ansible.playbook.collectionsearch import CollectionSearch
28from ansible.playbook.helpers import load_list_of_tasks
29from ansible.playbook.role import Role
30from ansible.playbook.taggable import Taggable
31from ansible.utils.sentinel import Sentinel
32
33
34class Block(Base, Conditional, CollectionSearch, Taggable):
35
36    # main block fields containing the task lists
37    _block = FieldAttribute(isa='list', default=list, inherit=False)
38    _rescue = FieldAttribute(isa='list', default=list, inherit=False)
39    _always = FieldAttribute(isa='list', default=list, inherit=False)
40
41    # other fields
42    _delegate_to = FieldAttribute(isa='string')
43    _delegate_facts = FieldAttribute(isa='bool')
44
45    # for future consideration? this would be functionally
46    # similar to the 'else' clause for exceptions
47    # _otherwise = FieldAttribute(isa='list')
48
49    def __init__(self, play=None, parent_block=None, role=None, task_include=None, use_handlers=False, implicit=False):
50        self._play = play
51        self._role = role
52        self._parent = None
53        self._dep_chain = None
54        self._use_handlers = use_handlers
55        self._implicit = implicit
56
57        # end of role flag
58        self._eor = False
59
60        if task_include:
61            self._parent = task_include
62        elif parent_block:
63            self._parent = parent_block
64
65        super(Block, self).__init__()
66
67    def __repr__(self):
68        return "BLOCK(uuid=%s)(id=%s)(parent=%s)" % (self._uuid, id(self), self._parent)
69
70    def __eq__(self, other):
71        '''object comparison based on _uuid'''
72        return self._uuid == other._uuid
73
74    def __ne__(self, other):
75        '''object comparison based on _uuid'''
76        return self._uuid != other._uuid
77
78    def get_vars(self):
79        '''
80        Blocks do not store variables directly, however they may be a member
81        of a role or task include which does, so return those if present.
82        '''
83
84        all_vars = self.vars.copy()
85
86        if self._parent:
87            all_vars.update(self._parent.get_vars())
88
89        return all_vars
90
91    @staticmethod
92    def load(data, play=None, parent_block=None, role=None, task_include=None, use_handlers=False, variable_manager=None, loader=None):
93        implicit = not Block.is_block(data)
94        b = Block(play=play, parent_block=parent_block, role=role, task_include=task_include, use_handlers=use_handlers, implicit=implicit)
95        return b.load_data(data, variable_manager=variable_manager, loader=loader)
96
97    @staticmethod
98    def is_block(ds):
99        is_block = False
100        if isinstance(ds, dict):
101            for attr in ('block', 'rescue', 'always'):
102                if attr in ds:
103                    is_block = True
104                    break
105        return is_block
106
107    def preprocess_data(self, ds):
108        '''
109        If a simple task is given, an implicit block for that single task
110        is created, which goes in the main portion of the block
111        '''
112
113        if not Block.is_block(ds):
114            if isinstance(ds, list):
115                return super(Block, self).preprocess_data(dict(block=ds))
116            else:
117                return super(Block, self).preprocess_data(dict(block=[ds]))
118
119        return super(Block, self).preprocess_data(ds)
120
121    def _load_block(self, attr, ds):
122        try:
123            return load_list_of_tasks(
124                ds,
125                play=self._play,
126                block=self,
127                role=self._role,
128                task_include=None,
129                variable_manager=self._variable_manager,
130                loader=self._loader,
131                use_handlers=self._use_handlers,
132            )
133        except AssertionError as e:
134            raise AnsibleParserError("A malformed block was encountered while loading a block", obj=self._ds, orig_exc=e)
135
136    def _load_rescue(self, attr, ds):
137        try:
138            return load_list_of_tasks(
139                ds,
140                play=self._play,
141                block=self,
142                role=self._role,
143                task_include=None,
144                variable_manager=self._variable_manager,
145                loader=self._loader,
146                use_handlers=self._use_handlers,
147            )
148        except AssertionError as e:
149            raise AnsibleParserError("A malformed block was encountered while loading rescue.", obj=self._ds, orig_exc=e)
150
151    def _load_always(self, attr, ds):
152        try:
153            return load_list_of_tasks(
154                ds,
155                play=self._play,
156                block=self,
157                role=self._role,
158                task_include=None,
159                variable_manager=self._variable_manager,
160                loader=self._loader,
161                use_handlers=self._use_handlers,
162            )
163        except AssertionError as e:
164            raise AnsibleParserError("A malformed block was encountered while loading always", obj=self._ds, orig_exc=e)
165
166    def _validate_always(self, attr, name, value):
167        if value and not self.block:
168            raise AnsibleParserError("'%s' keyword cannot be used without 'block'" % name, obj=self._ds)
169
170    _validate_rescue = _validate_always
171
172    def get_dep_chain(self):
173        if self._dep_chain is None:
174            if self._parent:
175                return self._parent.get_dep_chain()
176            else:
177                return None
178        else:
179            return self._dep_chain[:]
180
181    def copy(self, exclude_parent=False, exclude_tasks=False):
182        def _dupe_task_list(task_list, new_block):
183            new_task_list = []
184            for task in task_list:
185                new_task = task.copy(exclude_parent=True)
186                if task._parent:
187                    new_task._parent = task._parent.copy(exclude_tasks=True)
188                    if task._parent == new_block:
189                        # If task._parent is the same as new_block, just replace it
190                        new_task._parent = new_block
191                    else:
192                        # task may not be a direct child of new_block, search for the correct place to insert new_block
193                        cur_obj = new_task._parent
194                        while cur_obj._parent and cur_obj._parent != new_block:
195                            cur_obj = cur_obj._parent
196
197                        cur_obj._parent = new_block
198                else:
199                    new_task._parent = new_block
200                new_task_list.append(new_task)
201            return new_task_list
202
203        new_me = super(Block, self).copy()
204        new_me._play = self._play
205        new_me._use_handlers = self._use_handlers
206        new_me._eor = self._eor
207
208        if self._dep_chain is not None:
209            new_me._dep_chain = self._dep_chain[:]
210
211        new_me._parent = None
212        if self._parent and not exclude_parent:
213            new_me._parent = self._parent.copy(exclude_tasks=True)
214
215        if not exclude_tasks:
216            new_me.block = _dupe_task_list(self.block or [], new_me)
217            new_me.rescue = _dupe_task_list(self.rescue or [], new_me)
218            new_me.always = _dupe_task_list(self.always or [], new_me)
219
220        new_me._role = None
221        if self._role:
222            new_me._role = self._role
223
224        new_me.validate()
225        return new_me
226
227    def serialize(self):
228        '''
229        Override of the default serialize method, since when we're serializing
230        a task we don't want to include the attribute list of tasks.
231        '''
232
233        data = dict()
234        for attr in self._valid_attrs:
235            if attr not in ('block', 'rescue', 'always'):
236                data[attr] = getattr(self, attr)
237
238        data['dep_chain'] = self.get_dep_chain()
239        data['eor'] = self._eor
240
241        if self._role is not None:
242            data['role'] = self._role.serialize()
243        if self._parent is not None:
244            data['parent'] = self._parent.copy(exclude_tasks=True).serialize()
245            data['parent_type'] = self._parent.__class__.__name__
246
247        return data
248
249    def deserialize(self, data):
250        '''
251        Override of the default deserialize method, to match the above overridden
252        serialize method
253        '''
254
255        # import is here to avoid import loops
256        from ansible.playbook.task_include import TaskInclude
257        from ansible.playbook.handler_task_include import HandlerTaskInclude
258
259        # we don't want the full set of attributes (the task lists), as that
260        # would lead to a serialize/deserialize loop
261        for attr in self._valid_attrs:
262            if attr in data and attr not in ('block', 'rescue', 'always'):
263                setattr(self, attr, data.get(attr))
264
265        self._dep_chain = data.get('dep_chain', None)
266        self._eor = data.get('eor', False)
267
268        # if there was a serialized role, unpack it too
269        role_data = data.get('role')
270        if role_data:
271            r = Role()
272            r.deserialize(role_data)
273            self._role = r
274
275        parent_data = data.get('parent')
276        if parent_data:
277            parent_type = data.get('parent_type')
278            if parent_type == 'Block':
279                p = Block()
280            elif parent_type == 'TaskInclude':
281                p = TaskInclude()
282            elif parent_type == 'HandlerTaskInclude':
283                p = HandlerTaskInclude()
284            p.deserialize(parent_data)
285            self._parent = p
286            self._dep_chain = self._parent.get_dep_chain()
287
288    def set_loader(self, loader):
289        self._loader = loader
290        if self._parent:
291            self._parent.set_loader(loader)
292        elif self._role:
293            self._role.set_loader(loader)
294
295        dep_chain = self.get_dep_chain()
296        if dep_chain:
297            for dep in dep_chain:
298                dep.set_loader(loader)
299
300    def _get_parent_attribute(self, attr, extend=False, prepend=False):
301        '''
302        Generic logic to get the attribute or parent attribute for a block value.
303        '''
304
305        extend = self._valid_attrs[attr].extend
306        prepend = self._valid_attrs[attr].prepend
307        try:
308            value = self._attributes[attr]
309            # If parent is static, we can grab attrs from the parent
310            # otherwise, defer to the grandparent
311            if getattr(self._parent, 'statically_loaded', True):
312                _parent = self._parent
313            else:
314                _parent = self._parent._parent
315
316            if _parent and (value is Sentinel or extend):
317                try:
318                    if getattr(_parent, 'statically_loaded', True):
319                        if hasattr(_parent, '_get_parent_attribute'):
320                            parent_value = _parent._get_parent_attribute(attr)
321                        else:
322                            parent_value = _parent._attributes.get(attr, Sentinel)
323                        if extend:
324                            value = self._extend_value(value, parent_value, prepend)
325                        else:
326                            value = parent_value
327                except AttributeError:
328                    pass
329            if self._role and (value is Sentinel or extend):
330                try:
331                    parent_value = self._role._attributes.get(attr, Sentinel)
332                    if extend:
333                        value = self._extend_value(value, parent_value, prepend)
334                    else:
335                        value = parent_value
336
337                    dep_chain = self.get_dep_chain()
338                    if dep_chain and (value is Sentinel or extend):
339                        dep_chain.reverse()
340                        for dep in dep_chain:
341                            dep_value = dep._attributes.get(attr, Sentinel)
342                            if extend:
343                                value = self._extend_value(value, dep_value, prepend)
344                            else:
345                                value = dep_value
346
347                            if value is not Sentinel and not extend:
348                                break
349                except AttributeError:
350                    pass
351            if self._play and (value is Sentinel or extend):
352                try:
353                    play_value = self._play._attributes.get(attr, Sentinel)
354                    if play_value is not Sentinel:
355                        if extend:
356                            value = self._extend_value(value, play_value, prepend)
357                        else:
358                            value = play_value
359                except AttributeError:
360                    pass
361        except KeyError:
362            pass
363
364        return value
365
366    def filter_tagged_tasks(self, all_vars):
367        '''
368        Creates a new block, with task lists filtered based on the tags.
369        '''
370
371        def evaluate_and_append_task(target):
372            tmp_list = []
373            for task in target:
374                if isinstance(task, Block):
375                    filtered_block = evaluate_block(task)
376                    if filtered_block.has_tasks():
377                        tmp_list.append(filtered_block)
378                elif (task.action in C._ACTION_META or
379                        (task.action in C._ACTION_INCLUDE and task.evaluate_tags([], self._play.skip_tags, all_vars=all_vars)) or
380                        task.evaluate_tags(self._play.only_tags, self._play.skip_tags, all_vars=all_vars)):
381                    tmp_list.append(task)
382            return tmp_list
383
384        def evaluate_block(block):
385            new_block = self.copy(exclude_tasks=True)
386            new_block.block = evaluate_and_append_task(block.block)
387            new_block.rescue = evaluate_and_append_task(block.rescue)
388            new_block.always = evaluate_and_append_task(block.always)
389            return new_block
390
391        return evaluate_block(self)
392
393    def has_tasks(self):
394        return len(self.block) > 0 or len(self.rescue) > 0 or len(self.always) > 0
395
396    def get_include_params(self):
397        if self._parent:
398            return self._parent.get_include_params()
399        else:
400            return dict()
401
402    def all_parents_static(self):
403        '''
404        Determine if all of the parents of this block were statically loaded
405        or not. Since Task/TaskInclude objects may be in the chain, they simply
406        call their parents all_parents_static() method. Only Block objects in
407        the chain check the statically_loaded value of the parent.
408        '''
409        from ansible.playbook.task_include import TaskInclude
410        if self._parent:
411            if isinstance(self._parent, TaskInclude) and not self._parent.statically_loaded:
412                return False
413            return self._parent.all_parents_static()
414
415        return True
416
417    def get_first_parent_include(self):
418        from ansible.playbook.task_include import TaskInclude
419        if self._parent:
420            if isinstance(self._parent, TaskInclude):
421                return self._parent
422            return self._parent.get_first_parent_include()
423        return None
424