summaryrefslogtreecommitdiff
path: root/taskflow/engines/action_engine/analyzer.py
blob: 77f7df37ef24440e4041330d583ee530fa7d6aab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# -*- coding: utf-8 -*-

#    Copyright (C) 2013 Yahoo! Inc. All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import abc
import itertools
import weakref

from networkx.algorithms import traversal
import six

from taskflow import states as st


@six.add_metaclass(abc.ABCMeta)
class Decider(object):
    """Base class for deciders.

    Provides interface to be implemented by sub-classes
    Decider checks whether next atom in flow should be executed or not
    """

    @abc.abstractmethod
    def check(self, runtime):
        """Returns bool of whether this decider should allow running."""

    @abc.abstractmethod
    def affect(self, runtime):
        """If the :py:func:`~.check` returns false, affects associated atoms.

        """

    def check_and_affect(self, runtime):
        """Handles :py:func:`~.check` + :py:func:`~.affect` in right order."""
        proceed = self.check(runtime)
        if not proceed:
            self.affect(runtime)
        return proceed


class IgnoreDecider(Decider):
    """Checks any provided edge-deciders and determines if ok to run."""

    def __init__(self, atom, edge_deciders):
        self._atom = atom
        self._edge_deciders = edge_deciders

    def check(self, runtime):
        """Returns bool of whether this decider should allow running."""
        results = {}
        for name in six.iterkeys(self._edge_deciders):
            results[name] = runtime.storage.get(name)
        for local_decider in six.itervalues(self._edge_deciders):
            if not local_decider(history=results):
                return False
        return True

    def affect(self, runtime):
        """If the :py:func:`~.check` returns false, affects associated atoms.

        This will alter the associated atom + successor atoms by setting there
        state to ``IGNORE`` so that they are ignored in future runtime
        activities.
        """
        successors_iter = runtime.analyzer.iterate_subgraph(self._atom)
        runtime.reset_nodes(itertools.chain([self._atom], successors_iter),
                            state=st.IGNORE, intention=st.IGNORE)


class NoOpDecider(Decider):
    """No-op decider that says it is always ok to run & has no effect(s)."""

    def check(self, runtime):
        """Always good to go."""
        return True

    def affect(self, runtime):
        """Does nothing."""


class Analyzer(object):
    """Analyzes a compilation and aids in execution processes.

    Its primary purpose is to get the next atoms for execution or reversion
    by utilizing the compilations underlying structures (graphs, nodes and
    edge relations...) and using this information along with the atom
    state/states stored in storage to provide other useful functionality to
    the rest of the runtime system.
    """

    def __init__(self, runtime):
        self._runtime = weakref.proxy(runtime)
        self._storage = runtime.storage
        self._execution_graph = runtime.compilation.execution_graph

    def get_next_nodes(self, node=None):
        """Get next nodes to run (originating from node or all nodes)."""
        if node is None:
            execute = self.browse_nodes_for_execute()
            revert = self.browse_nodes_for_revert()
            return execute + revert
        state = self.get_state(node)
        intention = self._storage.get_atom_intention(node.name)
        if state == st.SUCCESS:
            if intention == st.REVERT:
                return [
                    (node, NoOpDecider()),
                ]
            elif intention == st.EXECUTE:
                return self.browse_nodes_for_execute(node)
            else:
                return []
        elif state == st.REVERTED:
            return self.browse_nodes_for_revert(node)
        elif state == st.FAILURE:
            return self.browse_nodes_for_revert()
        else:
            return []

    def browse_nodes_for_execute(self, node=None):
        """Browse next nodes to execute.

        This returns a collection of nodes that *may* be ready to be
        executed, if given a specific node it will only examine the successors
        of that node, otherwise it will examine the whole graph.
        """
        if node is not None:
            nodes = self._execution_graph.successors(node)
        else:
            nodes = self._execution_graph.nodes_iter()
        ready_nodes = []
        for node in nodes:
            is_ready, late_decider = self._get_maybe_ready_for_execute(node)
            if is_ready:
                ready_nodes.append((node, late_decider))
        return ready_nodes

    def browse_nodes_for_revert(self, node=None):
        """Browse next nodes to revert.

        This returns a collection of nodes that *may* be ready to be be
        reverted, if given a specific node it will only examine the
        predecessors of that node, otherwise it will examine the whole
        graph.
        """
        if node is not None:
            nodes = self._execution_graph.predecessors(node)
        else:
            nodes = self._execution_graph.nodes_iter()
        ready_nodes = []
        for node in nodes:
            is_ready, late_decider = self._get_maybe_ready_for_revert(node)
            if is_ready:
                ready_nodes.append((node, late_decider))
        return ready_nodes

    def _get_maybe_ready(self, atom, transition_to, allowed_intentions,
                         connected_fetcher, connected_checker,
                         decider_fetcher):
        state = self.get_state(atom)
        ok_to_transition = self._runtime.check_atom_transition(atom, state,
                                                               transition_to)
        if not ok_to_transition:
            return (False, None)
        intention = self._storage.get_atom_intention(atom.name)
        if intention not in allowed_intentions:
            return (False, None)
        connected_states = self._storage.get_atoms_states(
            connected_atom.name for connected_atom in connected_fetcher(atom))
        ok_to_run = connected_checker(six.itervalues(connected_states))
        if not ok_to_run:
            return (False, None)
        else:
            return (True, decider_fetcher(atom))

    def _get_maybe_ready_for_execute(self, atom):
        """Returns if an atom is *likely* ready to be executed."""

        def decider_fetcher(atom):
            edge_deciders = self._runtime.fetch_edge_deciders(atom)
            if edge_deciders:
                return IgnoreDecider(atom, edge_deciders)
            else:
                return NoOpDecider()

        connected_checker = lambda connected_iter: \
            all(state == st.SUCCESS and intention == st.EXECUTE
                for state, intention in connected_iter)
        connected_fetcher = self._execution_graph.predecessors_iter
        return self._get_maybe_ready(atom, st.RUNNING, [st.EXECUTE],
                                     connected_fetcher, connected_checker,
                                     decider_fetcher)

    def _get_maybe_ready_for_revert(self, atom):
        """Returns if an atom is *likely* ready to be reverted."""
        connected_checker = lambda connected_iter: \
            all(state in (st.PENDING, st.REVERTED)
                for state, _intention in connected_iter)
        decider_fetcher = lambda atom: NoOpDecider()
        connected_fetcher = self._execution_graph.successors_iter
        return self._get_maybe_ready(atom, st.REVERTING, [st.REVERT, st.RETRY],
                                     connected_fetcher, connected_checker,
                                     decider_fetcher)

    def iterate_subgraph(self, atom):
        """Iterates a subgraph connected to given atom."""
        for _src, dst in traversal.dfs_edges(self._execution_graph, atom):
            yield dst

    def iterate_retries(self, state=None):
        """Iterates retry atoms that match the provided state.

        If no state is provided it will yield back all retry atoms.
        """
        for atom in self._runtime.fetch_atoms_by_kind('retry'):
            if not state or self.get_state(atom) == state:
                yield atom

    def iterate_all_nodes(self):
        """Yields back all nodes in the execution graph."""
        for node in self._execution_graph.nodes_iter():
            yield node

    def find_atom_retry(self, atom):
        """Returns the retry atom associated to the given atom (or none)."""
        return self._execution_graph.node[atom].get('retry')

    def is_success(self):
        """Checks if all nodes in the execution graph are in 'happy' state."""
        for atom in self.iterate_all_nodes():
            atom_state = self.get_state(atom)
            if atom_state == st.IGNORE:
                continue
            if atom_state != st.SUCCESS:
                return False
        return True

    def get_state(self, atom):
        """Gets the state of a given atom (from the backend storage unit)."""
        return self._storage.get_atom_state(atom.name)