PageRenderTime 66ms CodeModel.GetById 8ms app.highlight 50ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/ansible/playbook/block.py

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