node.py 9.34 KB
Newer Older
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
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2017 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ###########################################################################*/

__authors__ = ["H.Payno"]
__license__ = "MIT"
__date__ = "29/05/2017"

import functools
import logging
import traceback
33
import json
34
import inspect
35
36
import importlib
from importlib.machinery import SourceFileLoader
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

_logger = logging.getLogger(__file__)

global next_node_free_idF
next_node_free_id = 0


def get_next_node_free_id():
    global next_node_free_id
    _id = next_node_free_id
    next_node_free_id += 1
    return _id


def trace_unhandled_exceptions(func):
    @functools.wraps(func)
    def wrapped_func(*args, **kwargs):
        try:
            outData = func(*args, **kwargs)
        except Exception as e:
            _logger.exception(e)
            errorMessage = '{0}'.format(e)
            traceBack = traceback.format_exc()
            return WorkflowException(
                    msg=errorMessage,
                    traceBack=traceBack,
                    data=args[1]
            )
        return outData

    return wrapped_func


class Node(object):
    """
72
    Node in the `.Scheme`. Will be associated to a core process.
73

74
75
76
77
    :param processing_pt: pointer to a class or a function or str defining the
                          callback. If the callback is a class then the handler
                          should be defined or the class should have a default
                          'process' function that will be called by default.
78
79
80
81
82
83
84
85
    :param int id: unique id of the node.
    :param dict properties: properties of the node
    :param str luigi_task: luigi task associate to this node
    """

    need_stop_join = False
    """flag to stop the node only when receive the 'stop' signal"""

86
87
88
89
    _JSON_PROCESS_PT = 'process_pt'
    _JSON_ID = 'id'
    _JSON_PROPERTIES = 'properties'

90
    def __init__(self, processing_pt, id=None, properties=None,
91
                 error_handler=None):
92
        self.id = get_next_node_free_id() if id is None else id
93
94
95
96
97
98
99
100
101
        """int of the node id"""
        self.properties = properties or {}
        """dict of the node properties"""
        self.upstream_nodes = set()
        """Set of upstream nodes"""
        self.downstream_nodes = set()
        """Set of downstream nodes"""
        self.__process_instance = None
        """"""
102
        self._process_pt = processing_pt
103
        """process instance"""
104
105
106
        self._handlers = {}
        """handlers with link name as key and callback as value.
        The default handler is store under the 'None' value"""
107
108
109
110
        self._error_handler = error_handler
        self.outData = None

    @property
111
112
113
114
    def handlers(self):
        return self._handlers

    @property
115
116
    def process_pt(self):
        return self._process_pt
117
118

    def isfinal(self):
119
120
121
122
123
        """

        :return: True if the node is at the end of a branch.
        :rtype: bool
        """
124
125
126
        return len(self.downstream_nodes) is 0

    def isstart(self):
127
128
129
130
131
        """

        :return: True if the node does not requires any input
        :rtype: bool
        """
132
133
        return len(self.upstream_nodes) is 0

134
    def load_handlers(self):
135
136
137
138
139
140
        """
        load handlers from the `processing_pt` defined.
        For callable it will always be `processing_pt`.
        But for not-callable class it will be class function defined in the
        `inputs` variable.
        """
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
        self._handlers.clear()
        assert self._process_pt is not None
        if callable(self._process_pt):
            self.__process_instance = self._process_pt
            self._handlers[None] = self._process_pt
        else:
            if not type(self._process_pt) is str:
                raise ValueError('process_pt should be a callable or path to a class or function')
            else:
                sname = self._process_pt.rsplit('.')
                if not (len(sname) > 1):
                    raise ValueError('Invalid name')
                class_name = sname[-1]
                del sname[-1]
                module_name = '.'.join(sname)
                if module_name.endswith('.py'):
                    # warning: in this case the file should not have any relative
                    module = SourceFileLoader(module_name,
                                              module_name).load_module()
                else:
                    module = importlib.import_module(module_name)

163
164
165
166
167
                class_or_fct = getattr(module, class_name)
                if inspect.isclass(class_or_fct):
                    self.__process_instance = class_or_fct()
                else:
                    self.__process_instance = class_or_fct
168
169
170
171
172
173
174
175
176
177
178
179
                if callable(self.__process_instance):
                    self._handlers[None] = self.__process_instance
                # manage the case where a class has several input handler
                if hasattr(self.__process_instance, 'inputs'):
                    for input_ in self.__process_instance.inputs:
                        input_name, input_type, input_handler = input_
                        self._handlers[input_name] = input_handler

        if len(self._handlers) == 0:
            raise ValueError('Fail to init handlers, none defined for ' + str(self._process_pt))

    @staticmethod
180
    def execute(process_pt, properties, input_name, input_data):
181
182
183
184
185
186
187
188
189
190
191
192
        """
        Create an instance of a node with 'process_pt' and execute it with the
        given input_name, properties and input_data.

        :param str process_pt: name of the process to execute
         (can be a module.class name, or a module.function)
        :param dict properties: process properties
        :param str input_name: name of the input data
        :param input_data: input data :warning: Should be serializable

        :return: output data. :warning: Should be serializable
        """
193
194
        node = Node(processing_pt=process_pt, properties=properties)
        node.load_handlers()
195
196
197
198
199
200
201
202
203
204
205
        if input_name in node.handlers:
            out = node.handlers[input_name](input_data)
        elif None in node.handlers:
            out = node.handlers[None](input_data)
        else:
            raise KeyError(input_name, 'is not managed by', str(node._process_pt))
        if hasattr(out, 'to_dict'):
            return out.to_dict()
        else:
            return out

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
253
254
255
256
257
    def to_json(self):
        """

        :return: json description of the node
        :rtype: dict
        """
        return {
            self._JSON_PROCESS_PT: self.process_pt,
            self._JSON_ID: self.id,
            self._JSON_PROPERTIES: self.properties,
        }

    @staticmethod
    def from_json(json_data):
        """

        :param json_data: node description
        :return: New node created from the json description
        :rtype: Node
        :raise ValueError: if properties or id or processing_pt missing
        """
        # load properties
        if Node._JSON_PROPERTIES not in json_data:
            _logger.error('Missing node properties in json description')
            _properties = None
        else:
            _properties = json_data[Node._JSON_PROPERTIES]
            assert type(_properties) is dict
        # load id
        if Node._JSON_ID not in json_data:
            _logger.error('Missing node id in json description')
            _id = None
        else:
            _id = json_data[Node._JSON_ID]
            assert type(_id) is int
        # load process_pt
        if Node._JSON_PROCESS_PT not in json_data:
            _logger.error('Missing node process_pt in json description')
            _process_pt = None
        else:
            _process_pt = json_data[Node._JSON_PROCESS_PT]

        if _properties is None or _id is None or _process_pt is None:
            raise ValueError('Unable to create Node from json, core information '
                             'are missing')
        else:
            return Node(id=_id, properties=_properties,
                        processing_pt=_process_pt)

    def __str__(self):
        return "node %s - %s" % (self.id, self.processing_pt)

258
259
260
261
262
263
264
265
266

class WorkflowException(Exception):
    def __init__(self, traceBack="", data=None, msg=None):
        if data is None:
            data = {}
        super(WorkflowException, self).__init__(msg)
        self.errorMessage = msg
        self.data = data
        self.traceBack = traceBack