scheme.py 23.2 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
33
# 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__ = "17/12/2018"


from xml.etree.ElementTree import TreeBuilder, Element, ElementTree
from collections import defaultdict
from itertools import count, chain
payno's avatar
payno committed
34
from typing import Union
35
36
37
38
39
import json
import pprint
import base64
import pickle
import logging
40
import typing
41
from .node import Node
42
from .link import Link
43
44
45
46
47
48
49
50
51
from ast import literal_eval

_logger = logging.getLogger(__name__)


class Scheme(object):
    """
    class to define a workflow scheme from nodes and links

52
53
54
55
56
57
58
    :param typing.Iterable nodes: set of Node contained in this scheme.
                                  note: subschemes are considered as Node.
                                  So if any defined it should be given as a
                                  Node
    :param typing.Iterable links: set of Link
    :type: typing.Iterable

59
    """
60
61
62
63
64
    _JSON_DESCRIPTION = 'description'
    _JSON_TITLE = 'title'
    _JSON_NODES = 'nodes'
    _JSON_LINKS = 'links'

payno's avatar
payno committed
65
66
67
68
    def __init__(self, nodes: typing.Iterable = None,
                 links: typing.Iterable = None,
                 description: str = None,
                 title: str = None):
69
70
71
72
        self.__rnodes = None
        self.__rlinks = None
        self.__rsub_schemes = None

73
74
75
        self._reset(nodes=nodes, links=links, description=description,
                    title=title)

76
    @property
payno's avatar
payno committed
77
    def rnodes(self) -> Union[None, list]:
78
79
80
81
82
83
84
85
86
        """All the nodes recursively. So this mean contained in this scheme or
        in a subscheme"""
        if self.__rnodes is None:
            self.__rnodes = list(self.nodes)
            for subscheme in self.sub_schemes:
                self.__rnodes.extend(subscheme.rnodes)
        return self.__rnodes

    @property
payno's avatar
payno committed
87
    def rlinks(self) -> Union[None, dict]:
88
89
90
91
92
93
94
95
96
        """all the links recursively. So this mean contained in this scheme or
        in a subscheme"""
        if self.__rlinks is None:
            self.__rlinks = self.links
            for subscheme in self.sub_schemes:
                self.__rlinks.update(subscheme.rlinks)
        return self.__rlinks

    @property
payno's avatar
payno committed
97
    def sub_schemes(self) -> Union[None, list]:
98
99
100
101
        """list of sub schemes contained by this scheme"""
        return self.__sub_schemes

    @property
payno's avatar
payno committed
102
    def rsub_schemes(self) -> Union[None, list]:
103
104
105
106
107
108
109
110
        """list of all sub schemes contained in this scheme recursively
        """
        if self.__rsub_schemes is None:
            self.__rsub_schemes = self.sub_schemes
            for sub_scheme in self.sub_schemes:
                self.__rsub_schemes.extend(sub_scheme.rsub_schemes)
        return self.__rsub_schemes

payno's avatar
payno committed
111
    def _reset(self, nodes, links, description, title) -> None:
112
113
        self.title = title or ''
        self.description = description or ''
114
115
116
117
118
119
        # clear structure
        self.links = {}  # keys are link ID, values are Link
        self.__sub_schemes = []
        self.__rnodes = None
        self.__rlinks = None

120
121
122
123
124
125
126
        if links is not None:
            for link in links:
                self.links[link.id] = link
        self.nodes = nodes or []
        """list of nodes"""
        self.nodes_dict = {}
        """dict with node id as key and node as value"""
127
128

        # register all sub scheme
129
        for node in self.nodes:
130
131
132
133
134
            if isinstance(node, SubScheme):
                self.__sub_schemes.append(node)
                self.nodes_dict[node.id] = node
        # update nodes for sub_schemes
        for node in self.rnodes:
135
            self.nodes_dict[node.id] = node
136

137
138
139
        if links is not None:
            self._update_nodes_from_links()

payno's avatar
payno committed
140
    def final_nodes(self) -> list:
141
142
143
144
145
146
        """

        :return: list of final nodes (with no output) and which hasn't any
                 control node upstream
        """
        res = []
147
        for node in self.rnodes:
148
149
150
151
152
            assert isinstance(node, Node)
            if node.isfinal():
                res.append(node)
        return res

payno's avatar
payno committed
153
    def start_nodes(self) -> list:
154
155
156
        """

        :return: list of nodes starting the workflow. Those does not require
157
                 any input_data.
158
159
        :rtype: list
        """
160
        res = []
161
        for node in self.rnodes:
162
163
164
165
166
            assert isinstance(node, Node)
            if node.isstart():
                res.append(node)
        return res

payno's avatar
payno committed
167
    def endlessNodes(self) -> list:
168
169
170
171
172
        """

        :return: list of final nodes.
        :rtype: list
        """
173
        res = []
174
        for node in self.rnodes:
175
176
177
178
179
            assert isinstance(node, Node)
            if node.endless is True:
                res.append(node)
        return res

payno's avatar
payno committed
180
    def save_to(self, output_file: str) -> None:
181
182
        """
        Save the scheme as an xml formated file to `stream`
183

184
        :param output_file: name of the output file.
185
        :type: str
186
        """
Olof Svensson's avatar
Olof Svensson committed
187
        if output_file.lower().endswith('.json'):
188
189
190
191
            self.save_as_json(output_file)
        else:
            self.save_as_xml(output_file)

payno's avatar
payno committed
192
    def save_as_xml(self, output_file: str) -> None:
193
194
195
196
197
        """
        save current scheme to a default xml format

        :param str output_file: file path
        """
198
199
200
201
202
        tree = self.scheme_to_etree(data_format="literal")
        indent(tree.getroot(), 0)

        tree.write(output_file)

payno's avatar
payno committed
203
    def save_as_json(self, output_file: str) -> None:
204
205
206
207
208
209
210
211
        """
        save current scheme to a default json format

        :param str output_file: file path
        """
        with open(output_file, 'w') as json_file:
            json.dump(self.to_json(), json_file)

payno's avatar
payno committed
212
    def nodes_to_json(self) -> list:
213
214
215
216
217
218
219
220
221
222
        """

        :return: nodes to json compatible format
        :rtype: list
        """
        res = []
        for node in self.nodes:
            res.append(node.to_json())
        return res

223
    @staticmethod
payno's avatar
payno committed
224
    def nodes_from_json(json_data: dict) -> tuple:
225
226
227
        """

        :param json_data: data containing the json definition
228
229
230
        :return: nodes, sub_schemes
        :rtype: tuple
        :raises: ValueError if the json is not a valid Node description
231
        """
232
233
234
235
236
237
238
239
        nodes = []
        sub_schemes = []
        for node_json_data in json_data:
            # if contains a node description then this is a subscheme
            if Scheme._JSON_NODES in node_json_data:
                sub_scheme = SubScheme.load_from_json(node_json_data)
                sub_schemes.append(sub_scheme)
            else:
240
                nodes.append(Node.from_json(node_json_data))
241
        return nodes, sub_schemes
242

payno's avatar
payno committed
243
    def links_to_json(self) -> list:
244
245
246
247
248
249
250
251
252
253
        """

        :return: links to json compatible format
        :rtype: list
        """
        res = []
        for link in self.links.values():
            res.append(link.to_json())
        return res

254
    @staticmethod
payno's avatar
payno committed
255
    def links_from_json(json_data: dict) -> list:
256
257
258
259
260
261
        """

        :param json_data: data containing the json definition
        :return: list of Link defined by the json data
        :rtype: list
        """
262
263
264
265
        links = []
        for link_json_data in json_data:
            links.append(Link.from_json(link_json_data))
        return links
266

payno's avatar
payno committed
267
    def to_json(self) -> dict:
268
269
270
271
272
273
        """
        Convert scheme to json

        :return: json dict
        :rtype: dict
        """
274
275
276
277
278
279
280
281
        return {
            self._JSON_DESCRIPTION: self.description,
            self._JSON_TITLE: self.title,
            self._JSON_NODES: self.nodes_to_json(),
            self._JSON_LINKS: self.links_to_json(),
        }

    @staticmethod
282
283
284
285
286
287
288
289
290
    def from_json_file(json_file_path: str):
        """
        Create and load Scheme from a json file

        :param str json_file_path: json file
        :return: Scheme fitting the json description
        :rtype: Scheme
        :raises: ValueError if file not found or invalid
        """
291
292
293
294
295
296
297
298
299
        scheme = Scheme()
        try:
            scheme.load_from_json_file(json_file_path)
        except ValueError as e:
            _logger.error(e)
            return None
        else:
            return scheme

300
    def load_from_json_file(self, json_file_path: str):
301
302
303
304
        """

        :param str json_file_path: path to the json file containing the scheme
                                   description
305

306
307
        :return: Scheme fitting the json description contains if the file.
                 If description is incomplete, return None
308
        :rtype: Union[Scheme, None]
309
310
311
312
313
314
315
316
317
        """
        try:
            with open(json_file_path, 'r') as json_file:
                json_data = json.load(json_file)
        except IOError as e:
            _logger.error('fail to read json file', str(e))
        else:
            self.load_from_json(json_data=json_data)

318
    @staticmethod
payno's avatar
payno committed
319
    def load_scheme_info_from_json(json_data: dict) -> tuple:
320
        """
321
        load fom json stream the Scheme Information
322
323

        :param json_data: scheme description
324
325
        :return: nodes, links, sub-schemes, title, description
        :rtype: tuple
326
327
        """
        # load title
328
        if Scheme._JSON_TITLE not in json_data:
329
330
331
            _logger.warning('no title found in the json')
            title = None
        else:
332
            title = json_data[Scheme._JSON_TITLE]
333
        # load description
334
        if Scheme._JSON_DESCRIPTION not in json_data:
335
336
337
            _logger.warning('no description found in the json')
            description = None
        else:
338
            description = json_data[Scheme._JSON_DESCRIPTION]
339
        # load links
340
        if Scheme._JSON_LINKS not in json_data:
341
342
343
344
            _logger.error('no link found in the json')
            links = None
        else:
            try:
345
                links = Scheme.links_from_json(json_data=json_data[Scheme._JSON_LINKS])
346
347
348
349
            except ValueError as e:
                _logger.error(e)
                links = None
        # load nodes
350
351
        nodes, sub_schemes = None, None
        if Scheme._JSON_NODES not in json_data:
352
353
354
            _logger.error('no nodes found in the json')
        else:
            try:
355
                nodes, sub_schemes = Scheme.nodes_from_json(json_data=json_data[Scheme._JSON_NODES])
356
357
358
            except ValueError as e:
                _logger.error(e)
                nodes = None
359
360
        return nodes, links, sub_schemes, title, description

payno's avatar
payno committed
361
    def load_from_json(self, json_data: dict):
362
        """
363

364
365
366
367
368
        :param json_data: scheme description
        :raise ValueError: if sink or source channel missing or if link id
                           missing or if sink or source node missing
        """
        nodes, links, sub_schemes, title, description = self.load_scheme_info_from_json(json_data)
369
370
371
372
373
        # create scheme if possible
        if nodes is None or links is None:
            raise ValueError('unable to load scheme from json description.'
                             'Information missing')
        else:
374
375
            if sub_schemes is not None:
                nodes.extend(sub_schemes)
376
377
378
            self._reset(nodes=nodes, links=links, description=description,
                        title=title)

payno's avatar
payno committed
379
380
    def scheme_to_etree(self, data_format:str = "literal",
                        pickle_fallback: bool = False):
381
        """
382
        Return an 'xml.etree.ElementTree' representation of the scheme.
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
        """
        builder = TreeBuilder(element_factory=Element)
        builder.start("scheme", {"version": "2.0",
                                 "title": self.title or "",
                                 "description": self.description or ""})

        # Nodes
        node_ids = defaultdict(count().__next__)
        builder.start("nodes", {})
        for node in self.nodes:  # type: SchemeNode
            attrs = {"id": node.id,
                     "qualified_name": node._qualified_name,
                     }

            if type(node) is not Node:
                attrs["scheme_node_type"] = "%s.%s" % (type(node).__name__,
                                                       type(node).__module__)
            builder.start("node", attrs)
            builder.end("node")

        builder.end("nodes")

        # Links
        link_ids = defaultdict(count().__next__)
        builder.start("links", {})
        for link in self.links:  # type: SchemeLink
            source = link.source_node_id
            sink = link.sink_node_id
            source_id = node_ids[source]
            sink_id = node_ids[sink]
            attrs = {"id": str(link_ids[link]),
                     "source_node_id": str(source_id),
                     "sink_node_id": str(sink_id),
                     "source_channel": link.source_channel,
                     "sink_channel": link.sink_channel,
                     "enabled": "true" if link.enabled else "false",
                     }
            builder.start("link", attrs)
            builder.end("link")

        builder.end("links")

        # Annotations
        annotation_ids = defaultdict(count().__next__)
        builder.start("thumbnail", {})
        builder.end("thumbnail")

        # Node properties/settings
        builder.start("node_properties", {})
        for node in self.nodes:
            data = None
            if node.properties:
                try:
                    data, format = dumps(node.properties, format=data_format,
                                         pickle_fallback=pickle_fallback)
                except Exception:
                    _logger.error("Error serializing properties for node %r",
                              node.title, exc_info=True)
                if data is not None:
                    builder.start("properties",
                                  {"node_id": str(node_ids[node]),
                                   "format": format})
                    builder.data(data)
                    builder.end("properties")

        builder.end("node_properties")

        builder.end("scheme")
        root = builder.close()
        tree = ElementTree(root)
        return tree

    def _update_nodes_from_links(self):
        """
        Update upstream and downstream nodes from links definition
        """
        self._clear_nodes_connections()
        for link_id, link in self.links.items():
            source_node = self.nodes_dict[link.source_node_id]
            sink_node = self.nodes_dict[link.sink_node_id]
            source_node.downstream_nodes.add(self.nodes_dict[link.sink_node_id])
            sink_node.upstream_nodes.add(self.nodes_dict[link.source_node_id])

    def _clear_nodes_connections(self):
        """
        clear for all nodes downstream and upstream nodes
        """
        for node in self.nodes:
            assert isinstance(node, Node)
            node.downstream_nodes = set()
            node.upstream_nodes = set()

    def has_final_join(self):
476
477
478
479
480
        """
        :return: True if we need to send a 'end' signal before closing the
                 workflow. This is needed in the 'acquisition workflow' like
                 tomwer and the DataWatcher process for example.
        :rtype: bool
481
482
483
484
485
486
487
488
        """
        for node in self.nodes:
            if node.need_stop_join:
                return True
        return False

    @staticmethod
    def from_desc(desc):
489
490
491
492
493
494
        """

        :param desc:
        :return: instance of Scheme from it description.
        :rtype: :class:`Scheme`
        """
495
496
497
498
        nodes = []
        nodes_dict = {}

        for node_d in desc.nodes:
499
            node = Node(id=node_d.id, processing_pt=node_d.qualified_name)
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
            nodes.append(node)
            nodes_dict[node.id] = node
            data = node_d.data
            if data:
                properties = loads(data.data, data.format)
                node.properties = properties
            else:
                node.properties = {}
            node.qualified_name = node_d.qualified_name

        for link_d in desc.links:
            upstream_node = nodes_dict[link_d.source_node_id]
            assert isinstance(upstream_node, Node)
            downstream_node = nodes_dict[link_d.sink_node_id]
            upstream_node.downstream_nodes.add(downstream_node)
            downstream_node.upstream_nodes.add(upstream_node)

        scheme = Scheme(nodes=nodes, links=desc.links)
        scheme.title = desc.title
        scheme.description = desc.description

        return scheme

523
    def load_handlers(self):
524
525
526
        """
        load all nodes handlers.
        """
527
528
529
        for node in self.nodes:
            node.load_handlers()

530

531
class SubScheme(Scheme, Node):
532
533
534
535
536
537
538
539
540
541
542
543
544
    """
    Define a sub-scheme of the workflow (or subworkflow). SubScheme are
    as Scheme expect that they are not 'root'.

    :param nodes: set of Node
    :type: typing.Iterable
    :param links: set of Node
    :type: typing.Iterable
    :param description: description of the subscheme
    :type: str
    :param error_handler: ErrorHandler
    """
    def __init__(self, nodes: typing.Iterable, links: typing.Iterable,
545
546
547
548
                 description: str=None, error_handler=None, title='', id=None):
        Node.__init__(self, processing_pt=None, error_handler=error_handler,
                      id=id)
        Scheme.__init__(self, nodes=nodes, links=links, title=title,
549
550
                        description=description)

551
552
553
554
555
556
557
558
559
560
561
562
    def to_json(self):
        """
        Convert sub scheme to json

        :return: json dict
        :rtype: dict
        """
        desc = Scheme.to_json(self)
        desc.update(Node.to_json(self))
        return desc

    @staticmethod
payno's avatar
payno committed
563
    def load_from_json(json_data: dict):
564
565
        """

566
567
        :param json_data: scheme description.

568
        :raise ValueError: if sink or source channel missing or if link id
569
                           missing or if sink or source node missing.
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
        """
        nodes, links, sub_schemes, title, description = Scheme.load_scheme_info_from_json(json_data)
        _id, _properties, _process_pt = Node.load_node_info_from_json(json_data)
        if _properties is not None:
            _logger.warning('SubScheme properties are not managed')
        if _process_pt is not None:
            _logger.warning('SubScheme pointer to ptocess is not managed')
        # create scheme if possible
        if nodes is None or links is None:
            raise ValueError('unable to load scheme from json description.'
                             'Information missing')
        sub_scheme = SubScheme(nodes=nodes, links=links,
                               description=description, title=title, id=_id)
        return sub_scheme

585

586
587
588
589
590
591
592
def contains_control_nodes(nodes_list: typing.Iterable):
    """
    Return the list of the 'control' nodes.

    :param typing.Iterable nodes_list:
    :return:
    """
593
594
595
596
597
598
    for _node in nodes_list:
        if _node.endless or contains_control_nodes(_node.upstream_nodes):
            return True
    return False


599
600
601
602
603
604
605
606
def loads(string: str, format: str) -> object:
    """load stream from the given format.

    :param str string: stream to load
    :param str format: format
    :return: object contained in the stream
    :rtype: object
    """
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
    if format == "literal":
        return literal_eval(string)
    elif format == "json":
        return json.loads(string)
    elif format == "pickle":
        return pickle.loads(base64.decodebytes(string.encode('ascii')))
    else:
        raise ValueError("Unknown format")


def indent(element, level=0, indent="\t"):
    """
    Indent an instance of a :class:`Element`. Based on
    (http://effbot.org/zone/element-lib.htm#prettyprint).

    """
    def empty(text):
        return not text or not text.strip()

    def indent_(element, level, last):
        child_count = len(element)

        if child_count:
            if empty(element.text):
                element.text = "\n" + indent * (level + 1)

            if empty(element.tail):
                element.tail = "\n" + indent * (level + (-1 if last else 0))

            for i, child in enumerate(element):
                indent_(child, level + 1, i == child_count - 1)

        else:
            if empty(element.tail):
                element.tail = "\n" + indent * (level + (-1 if last else 0))

    return indent_(element, level, True)


def dumps(obj, format="literal", prettyprint=False, pickle_fallback=False):
    """
    Serialize `obj` using `format` ('json' or 'literal') and return its
    string representation and the used serialization format ('literal',
    'json' or 'pickle').

    If `pickle_fallback` is True and the serialization with `format`
    fails object's pickle representation will be returned

    """
    if format == "literal":
        try:
            return (literal_dumps(obj, prettyprint=prettyprint, indent=1),
                    "literal")
        except (ValueError, TypeError) as ex:
            if not pickle_fallback:
                raise

            _logger.debug("Could not serialize to a literal string")

    elif format == "json":
        try:
            return (json.dumps(obj, indent=1 if prettyprint else None),
                    "json")
        except (ValueError, TypeError):
            if not pickle_fallback:
                raise

            _logger.debug("Could not serialize to a json string")

    elif format == "pickle":
        return base64.encodebytes(pickle.dumps(obj)).decode('ascii'), "pickle"

    else:
        raise ValueError("Unsupported format %r" % format)

    if pickle_fallback:
        _logger.warning("Using pickle fallback")
        return base64.encodebytes(pickle.dumps(obj)).decode('ascii'), "pickle"
    else:
        raise Exception("Something strange happened.")


# This is a subset of PyON serialization.
def literal_dumps(obj, prettyprint=False, indent=4):
    """
    Write obj into a string as a python literal.
    """
    memo = {}
    NoneType = type(None)

    def check(obj):
        if type(obj) in [int, float, bool, NoneType, str, bytes]:
            return True

        if id(obj) in memo:
            raise ValueError("{0} is a recursive structure".format(obj))

        memo[id(obj)] = obj

        if type(obj) in [list, tuple]:
            return all(map(check, obj))
        elif type(obj) is dict:
            return all(map(check, chain(iter(obj.keys()), iter(obj.values()))))
        else:
            raise TypeError("{0} can not be serialized as a python "
                             "literal".format(type(obj)))

    check(obj)

    if prettyprint:
        return pprint.pformat(obj, indent=indent)
    else:
        return repr(obj)