messages.py 85.8 KB
Newer Older
1 2 3
# -*- coding: utf-8 -*-

"""
4 5 6 7

About the library:
-----------------

8
This module provides the API message formats used by ioppytest test framework.
9 10 11

The idea is to be able to have an
- organized and centralized way of dealing with the big amount of messages formats used in the platform;
12
- to be able to import (or just copy/paste) these messages for interacting with components on the event bus ,
13 14 15 16
- re-use this also for the integration testing;
- to have version control the messages e.g. messages_testcase_start API v1 and API v2;
- to have a direct way of exporting this as doc.

17

18
Some conventions:
19
---------------------
20 21
- if event is a service request then the routing key (r_key) is someRpcExecutionEvent.request
- a reply to a service will be on topic/r_key : someRpcExecutionEvent.reply
22 23 24
- reply.correlation_id = request.correlation_id


25 26
Usage:
------
Federico Sismondi's avatar
Federico Sismondi committed
27
>>> m = MsgTestCaseSkip(testcase_id = 'some_testcase_id')
28
>>> m
29
MsgTestCaseSkip(_api_version = 1.0.17, description = Skip testcase, node = someNode, testcase_id = some_testcase_id, )
30
>>> m.routing_key
31
'testsuite.testcase.skip'
32 33
>>> m.message_id # doctest: +SKIP
'802012eb-24e3-45c4-9dcc-dc293c584f63'
34
>>> m.testcase_id
Federico Sismondi's avatar
Federico Sismondi committed
35
'some_testcase_id'
36

37
# also we can modify some of the fields (rewrite the default ones)
Federico Sismondi's avatar
Federico Sismondi committed
38
>>> m = MsgTestCaseSkip(testcase_id = 'TD_COAP_CORE_03')
39
>>> m
40
MsgTestCaseSkip(_api_version = 1.0.17, description = Skip testcase, node = someNode, testcase_id = TD_COAP_CORE_03, )
41
>>> m.testcase_id
Federico Sismondi's avatar
Federico Sismondi committed
42
'TD_COAP_CORE_03'
43

44 45
# and even export the message in json format (for example for sending the message though the amqp event bus)
>>> m.to_json()
46
'{"_api_version": "1.0.17", "description": "Skip testcase", "node": "someNode", "testcase_id": "TD_COAP_CORE_03"}'
Federico Sismondi's avatar
Federico Sismondi committed
47

48
# We can use the Message class to import json into Message objects:
Federico Sismondi's avatar
Federico Sismondi committed
49
>>> m=MsgTestSuiteStart()
50 51
>>> m.routing_key
'testsuite.start'
Federico Sismondi's avatar
Federico Sismondi committed
52
>>> m.to_json()
53
'{"_api_version": "1.0.17", "description": "Test suite START command"}'
Federico Sismondi's avatar
Federico Sismondi committed
54
>>> json_message = m.to_json()
55 56
>>> obj=Message.load(json_message,'testsuite.start', None )
>>> obj
57
MsgTestSuiteStart(_api_version = 1.0.17, description = Test suite START command, )
58
>>> type(obj) # doctest: +SKIP
59
<class 'messages.MsgTestSuiteStart'>
60

61
# We can use the library for generating error responses:
62 63 64
# the request:
>>> m = MsgSniffingStart()
>>>
65

66 67 68
# the error reply (note that we pass the message of the request to build the reply):
>>> err = MsgErrorReply(m)
>>> err
69
MsgErrorReply(_api_version = 1.0.17, error_code = None, error_message = None, ok = False, )
70 71

# properties of the message are auto-generated:
72
>>> m.reply_to
73
'sniffing.start.reply'
74
>>> err.routing_key
75
'sniffing.start.reply'
76 77 78 79
>>> m.correlation_id # doctest: +SKIP
'360b0f67-4455-43e3-a00f-eca91f2e84da'
>>> err.correlation_id # doctest: +SKIP
'360b0f67-4455-43e3-a00f-eca91f2e84da'
Federico Sismondi's avatar
Federico Sismondi committed
80

81 82 83 84 85
# we can get all the AMQP properties also as a dict:
>>> err.get_properties() # doctest: +SKIP
'{'timestamp': 1515172549, 'correlation_id': '16257581-06be-4088-a1f6-5672cc73d8f2', 'message_id': '1ec12c2b-33c7-44ad-97b8-5099c4d52e81', 'content_type': 'application/json'}'


86 87 88
"""

from collections import OrderedDict
89
import logging
90
import time
91 92 93
import json
import uuid

94
API_VERSION = '1.0.17'
95

96 97 98 99 100 101 102 103 104

class NonCompliantMessageFormatError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)


Federico Sismondi's avatar
Federico Sismondi committed
105
class Message(object):
106
    def __init__(self, **kwargs):
107 108
        global API_VERSION

109 110 111
        try:
            # hard copy the message template
            self._msg_data = {k: v for k, v in self._msg_data_template.items()}
112 113 114
        except AttributeError:  # if message is built directly using Message class then there's no data template
            self._msg_data = {}
            self._msg_data_template = {}
115

116 117
        # init properties
        self._properties = dict(
118 119
            content_type="application/json",
            message_id=str(uuid.uuid4()),
120
            timestamp=int(time.time())
121 122
        )

123
        try:
124
            if self.routing_key.endswith(".request"):
125 126
                self._properties["reply_to"] = self.routing_key.replace(".request", ".reply")
                self._properties["correlation_id"] = self._properties["message_id"]
127
        except AttributeError:
128
            pass
129

130
        # rewrite default data fields with the passed args
131 132 133
        self._msg_data.update(kwargs)

        # add API's version
134
        if "_api_version" not in self._msg_data:
135
            self._msg_data["_api_version"] = API_VERSION
136

Federico Sismondi's avatar
Federico Sismondi committed
137
        # add values as object's attributes
138 139 140
        for key in self._msg_data:
            setattr(self, key, self._msg_data[key])

141 142 143 144
        # add props as objects attributes
        for key in self._properties:
            setattr(self, key, self._properties[key])

145 146
    def to_dict(self):
        resp = {}
147 148
        # let's use sorted so API returns items inside always in the same order
        for field in sorted(self._msg_data.keys()):
149
            resp[field] = getattr(self, field)
150

151 152 153 154 155 156 157 158
        return resp

    def to_odict(self):
        resp = {}
        # let's use sorted so API returns items inside always in the same order
        for field in sorted(self._msg_data.keys()):
            resp[field] = getattr(self, field)

159
        return OrderedDict(sorted(resp.items(), key=lambda t: t[0]))  # sorted by key
160 161

    def to_json(self):
162
        return json.dumps(self.to_odict())
163

164
    def get_properties(self):
165
        resp = dict()
166 167 168
        for field in self._properties:
            resp[field] = getattr(self, field)
        return resp
169

170
    def __str__(self):
171 172 173 174 175
        s = " - " * 20 + "\n"
        s += "Message routing key: %s" % self.routing_key
        s += "\n -  -  - \n"
        s += "Message properties: %s" % json.dumps(self.get_properties(), indent=4, )
        s += "\n -  -  - \n"
176
        s += "Message body: %s" % json.dumps(self.to_odict(), indent=4, )
177
        s += "\n" + " - " * 20
178
        return s
179

180 181
    def update_properties(self, **kwargs):
        for key, value in kwargs.items():
182 183 184
            # if key in self._properties:
            #     setattr(self, key, value)
            setattr(self, key, value)
185

186 187 188 189 190 191 192 193 194 195
    @classmethod
    def load(cls, json_body, routing_key, properties=None):
        """
        Builds a python object representation of the AMQP message based on the ones defined by the event bus API.

        :param json_body: json description of message's body (amqp payload)
        :param routing_key: Maps to the right Message builder, passed argument cannot contain special char like * or #
        :param properties: Used for building more complete complex representation (e.g. for reply_to corre_id params)
        :return: The python Message object or subclass (e.g. MsgPacketSniffedRaw)

196 197
        about r_key matching mechanism:
            fromAgent.coap_client.packet.raw -> matches fromAgent.*.packet.raw -> returns MsgPacketSniffedRaw
198 199 200 201 202 203

        # We can use the Message class to build Message objects from json + rkey:
        >>> m=MsgSniffingGetCapture()
        >>> m.routing_key
        'sniffing.getcapture.request'
        >>> m.to_json()
204
        '{"_api_version": "1.0.17", "capture_id": "TD_COAP_CORE_01"}'
205 206
        >>> json_message = m.to_json()
        >>> json_message
207
        '{"_api_version": "1.0.17", "capture_id": "TD_COAP_CORE_01"}'
208 209
        >>> obj=Message.load(json_message,'testsuite.start', None )
        >>> type(obj) # doctest
210
        <class 'messages.MsgTestSuiteStart'>
211 212 213


        """
214
        global rk_pattern_to_message_type_map
215 216 217

        props_dict = {}

218 219 220 221 222 223 224 225 226 227 228 229 230
        # get message type from predefined rkey patterns
        try:
            message_type = rk_pattern_to_message_type_map.get_message_type(routing_key)
        except KeyError as e:
            raise NonCompliantMessageFormatError("ROUTING KEY PATTERN not recogized for RKEY=%s \nBODY=%s" %
                                                 (routing_key, json_body))

        # build message skeleton (all fields as None)
        default_values_dict = message_type().to_dict()
        payload_dict = dict.fromkeys(default_values_dict.keys(), None)

        # fill messages from provided json
        payload_dict.update(json.loads(json_body))
231 232 233 234 235 236 237 238
        built_message = message_type(**payload_dict)

        # let's process the properties arguments
        if properties is None:
            pass
        elif type(properties) is dict:
            props_dict.update(properties)
        else:
239
            raise NotImplementedError('Incompatible properties input or not yet supported')
240 241 242 243 244 245 246

        # let's update the messages properties
        if properties:
            built_message.update_properties(**props_dict)

        return built_message

247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    @classmethod
    def load_from_pika(cls, method, props, body):
        """
        Builds a python object representation of the AMQP message based on the ones defined by the event bus API.
        Takes as arguments pika objects method, properties and body returned by channel.basic_consume method
        """
        global rk_pattern_to_message_type_map

        props_dict = {
            'content_type': props.content_type,
            'delivery_mode': props.delivery_mode,
            'correlation_id': props.correlation_id,
            'reply_to': props.reply_to,
            'message_id': props.message_id,
            'timestamp': props.timestamp,
            'user_id': props.user_id,
            'app_id': props.app_id,
        }

        routing_key = method.routing_key
        json_body = body.decode('utf-8')

        return Message.load(json_body, routing_key, props_dict)

271 272
    @classmethod
    def from_json(cls, body):
273 274 275 276 277 278
        """
        :param body: json string or string encoded as utf-8
        :return:  Message object generated from the body
        :raises NonCompliantMessageFormatError: If the message cannot be build from the provided json
        """

279
        raise DeprecationWarning()
280

281 282 283 284 285 286 287 288 289
        # if type(body) is str:
        #     message_dict = json.loads(body)
        # # Note: pika re-encodes json.dumps strings as utf-8 for some reason, the following line undoes this
        # elif type(body) is bytes:
        #     message_dict = json.loads(body.decode("utf-8"))
        # else:
        #     raise NonCompliantMessageFormatError("Not a Json")
        #
        # return cls.from_dict(message_dict)
290 291 292 293 294 295 296 297 298

    @classmethod
    def from_dict(cls, message_dict):
        """
        :param body: dict
        :return:  Message object generated from the body
        :raises NonCompliantMessageFormatError: If the message cannot be build from the provided json
        """

299
        raise DeprecationWarning()
300

301 302 303 304 305 306 307 308
        # assert type(message_dict) is dict
        #
        # message_type = message_dict["_type"]
        #
        # if message_type in message_types_dict:
        #     return message_types_dict[message_type](**message_dict)
        # else:
        #     raise NonCompliantMessageFormatError("Cannot load json message: %s" % str(message_dict))
309

310
    def __repr__(self):
311
        ret = "%s(" % self.__class__.__name__
312
        for key, value in self.to_odict().items():
313 314
            ret += "%s = %s, " % (key, value)
        ret += ")"
315 316
        return ret

317

318 319 320 321 322 323 324 325
class RoutingKeyToMessageMap:
    """
    Special dict to map routing keys to messages of Message type.
    Lookup is slow but it's due to the fact of using WILDCARDs (no hash mechanism can be used :/ )

    example of use:
        >>> r_map=RoutingKeyToMessageMap({'fromAgent.*.packet.raw':MsgPacketSniffedRaw })
        >>> r_map
326
        {'fromAgent.*.packet.raw': <class 'messages.MsgPacketSniffedRaw'>}
327
        >>> r_map.get_message_type('fromAgent.agent1.packet.raw')
328
        <class 'messages.MsgPacketSniffedRaw'>
329
        >>> r_map.get_message_type('blabla.agent1.packet.raw') #IGNORE_EXCEPTION_DETAIL
330
        Traceback (most recent call last):
331 332 333 334 335 336 337
          File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/doctest.py", line 1320, in __run
            compileflags, 1), test.globs)
          File "<doctest __main__.RoutingKeyToMessageMap[3]>", line 1, in <module>
            r_map.get_message_type('blabla.agent1.packet.raw') #IGNORE_EXCEPTION_DETAIL
          File "/Users/fsismondi/dev/f-interop-utils/messages.py", line 355, in get_message_type
            "Routing Key pattern not found in mapping rkey patterns -> messages table, RKEY: %s" %routing_key)
        KeyError: 'Routing Key pattern not found in mapping rkey patterns -> messages table, RKEY: blabla.agent1.packet.raw'
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
        >>>

    """
    # TODO implement # wildcard
    WILDCARDS = ('*', '#')
    TERM_SEPARATOR = '.'

    def __init__(self, rkey_to_message_dict):
        self.rkey_to_message_dict = rkey_to_message_dict

    def __repr__(self):
        return repr(self.rkey_to_message_dict)

    def get_message_type(self, routing_key):
        for key in self.rkey_to_message_dict.keys():
            if self.equals(key, routing_key):
                return self.rkey_to_message_dict[key]
355
        raise KeyError(
356
            "Routing Key pattern not found in mapping rkey patterns -> messages table, RKEY: %s" % routing_key)
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390

    @classmethod
    def equals(cls, r1, r2):

        def equal_terms(term_1, term_2):
            if term_1 == '*' or term_2 == '*':
                return True
            else:
                return term_1 == term_2

        complex_matching = False

        for wc in cls.WILDCARDS:
            if wc in r1 or wc in r2:
                complex_matching = True
                break

        if '#' in r1 or '#' in r2:
            raise NotImplementedError("Wildcard # still not supported in matching mechanism")

        if not complex_matching:
            return r1 == r2
        else:
            if len(r1.split(cls.TERM_SEPARATOR)) != len(r2.split(cls.TERM_SEPARATOR)):
                return False
            else:
                for term1, term2 in zip(r1.split(cls.TERM_SEPARATOR), r2.split(cls.TERM_SEPARATOR)):
                    if not equal_terms(term1, term2):
                        return False
                    else:
                        continue
                return True


391 392 393
class MsgReply(Message):
    """
    Auxiliary class which creates replies messages with fields based on the request.
394
    Routing key, corr_id are generated based on the request message
395
    """
396

397
    def __init__(self, request_message=None, **kwargs):
398

399
        if request_message and hasattr(request_message, "routing_key"):
400
            if request_message.routing_key.endswith(".request"):
401
                self.routing_key = request_message.routing_key.replace(".request", ".reply")
402 403 404 405 406 407 408

            # if not data template, then let's build one for a reply
            # (possible when creating a MsgReply directly and not by using subclass)
            if not hasattr(self, "_msg_data_template"):
                self._msg_data_template = {
                    "ok": True,
                }
409

410 411 412 413 414
            elif 'ok' not in self._msg_data_template:
                self._msg_data_template.update({
                    "ok": True,
                })

415
            super(MsgReply, self).__init__(**kwargs)
416

417 418 419
            # overwrite correlation id template and attribute
            self._properties["correlation_id"] = request_message.correlation_id
            self.correlation_id = request_message.correlation_id
420

421
        else:  # note this doesnt generate amqp properties
Federico Sismondi's avatar
Federico Sismondi committed
422
            super(MsgReply, self).__init__(**kwargs)
423
            logging.warning(
Federico Sismondi's avatar
Federico Sismondi committed
424
                '[messages] lazy response built, generating reply message without properties for %s' % repr(self)[:70]
Federico Sismondi's avatar
Federico Sismondi committed
425
            )
426

427 428 429 430 431 432 433 434
    def correlate_to(self, request_message):
        """
        add to reply message the right correlation information to request
        """
        # overwrite correlation id template and attribute
        self._properties["correlation_id"] = request_message.correlation_id
        self.correlation_id = request_message.correlation_id

435 436 437

class MsgErrorReply(MsgReply):
    """
438
    see section "F-Interop conventions" on top
439
    """
440

441 442
    def __init__(self, request_message, **kwargs):
        assert request_message
443
        super(MsgErrorReply, self).__init__(request_message, **kwargs)
444 445

    _msg_data_template = {
446
        "ok": False,
447 448
        "error_message": None,
        "error_code": None
449 450
    }

Federico Sismondi's avatar
Federico Sismondi committed
451

452
# # # # # # CORE API messages # # # # #
453 454

class MsgOrchestratorVersionReq(Message):
455 456 457 458 459 460 461 462 463
    """
    Requirements: ...

    Type: Event

    Pub/Sub: UI -> SO

    Description: Message for returning current version of SO
    """
464
    routing_key = "orchestrator.version.request"
465 466 467

    _msg_data_template = {
    }
468

Federico Sismondi's avatar
Federico Sismondi committed
469

470 471 472 473 474 475 476 477 478 479
class MsgOrchestratorUsersList(Message):
    """
    Requirements: ...

    Type: Event

    Pub/Sub: UI -> SO

    Description: Message for returning user list of SO
    """
480
    routing_key = "orchestrator.users.list.request"
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495

    _msg_data_template = {
    }


class MsgOrchestratorUserAdd(Message):
    """
    Requirements: ...

    Type: Event

    Pub/Sub: UI -> SO

    Description: Message for adding a user to SO
    """
496

497
    routing_key = "orchestrator.users.add.request"
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512

    _msg_data_template = {
    }


class MsgOrchestratorUserDelete(Message):
    """
    Requirements: ...

    Type: Event

    Pub/Sub: UI -> SO

    Description: Message for deleting a user from SO
    """
513

514
    routing_key = "orchestrator.users.delete.request"
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529

    _msg_data_template = {
    }


class MsgOrchestratorUserGet(Message):
    """
    Requirements: ...

    Type: Event

    Pub/Sub: UI -> SO

    Description: Message for getting a user from SO
    """
530

531
    routing_key = "orchestrator.users.get.request"
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546

    _msg_data_template = {
    }


class MsgOrchestratorSessionsList(Message):
    """
    Requirements: ...

    Type: Event

    Pub/Sub: UI -> SO

    Description: Message for listing sessions from SO
    """
547
    routing_key = "orchestrator.sessions.list.request"
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562

    _msg_data_template = {
    }


class MsgOrchestratorSessionsGet(Message):
    """
    Requirements: ...

    Type: Event

    Pub/Sub: UI -> SO

    Description: Message for getting a session from SO
    """
563
    routing_key = "orchestrator.sessions.get.request"
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578

    _msg_data_template = {
    }


class MsgOrchestratorSessionsAdd(Message):
    """
    Requirements: ...

    Type: Event

    Pub/Sub: UI -> SO

    Description: Message for adding a session to SO
    """
579
    routing_key = "orchestrator.sessions.add.request"
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594

    _msg_data_template = {
    }


class MsgOrchestratorSessionsDelete(Message):
    """
    Requirements: ...

    Type: Event

    Pub/Sub: UI -> SO

    Description: Message for deleting a session to SO
    """
595

596
    routing_key = "orchestrator.sessions.delete.request"
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612

    _msg_data_template = {
    }


class MsgOrchestratorSessionsUpdate(Message):
    """
    Requirements: ...

    Type: Event

    Pub/Sub: UI -> SO

    Description: Message for updating a session from SO
    """

613
    routing_key = "orchestrator.sessions.update.request"
614 615 616 617 618 619 620 621 622 623 624 625 626 627
    _msg_data_template = {
    }


class MsgOrchestratorTestsGet(Message):
    """
    Requirements: ...

    Type: Event

    Pub/Sub: UI -> SO

    Description: Message for getting tests from SO
    """
628
    routing_key = "orchestrator.tests.get.request"
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643

    _msg_data_template = {
    }


class MsgOrchestratorTestsGetContributorName(Message):
    """
    Requirements: ...

    Type: Event

    Pub/Sub: UI -> SO

    Description: Message for getting tests from SO with contributor and name
    """
644
    routing_key = "orchestrator.tests.get_contributor_name.request"
645 646 647 648 649

    _msg_data_template = {
    }


650
# # # # # # GUI API messages # # # # # # # #
651

652
class MsgUiReply(MsgReply):
653 654 655 656 657 658 659
    routing_key = "ui.user.all.reply"

    _msg_data_template = {
        "fields": [
        ]
    }

660

661
class MsgUiDisplay(Message):
662 663 664 665 666 667 668
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

669
    Description: Message to display in user interface
670
    """
671
    routing_key = "ui.user.all.display"
672 673

    _msg_data_template = {
674
        "level": None,
675
        "tags": {},
676
        "fields": [
677
            {
678 679
                "type": "p",
                "value": "Hello World!"
680 681 682 683 684
            },
        ]
    }


685
class MsgUiRequest(Message):
686 687 688 689 690 691 692
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

693
    Description: Message for requesting action or information to user
694 695 696 697
    """
    routing_key = "ui.user.all.request"

    _msg_data_template = {
698
        "tags": {},
699 700
        "fields": [
            {
701 702
                "name": "input_name",
                "type": "text"
703 704 705 706
            },
        ]
    }

707 708

class MsgUiRequestSessionConfiguration(Message):
Pauline Gaudet-Chardonnet's avatar
Pauline Gaudet-Chardonnet committed
709 710 711 712 713 714 715
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

Federico Sismondi's avatar
Federico Sismondi committed
716
    Description: Message for requesting session information to UI
717
    """
Federico Sismondi's avatar
Federico Sismondi committed
718
    routing_key = "ui.core.session.get.request"
719 720 721 722 723

    _msg_data_template = {
    }


724
class MsgUiSessionConfigurationReply(MsgUiReply):
725 726 727 728 729 730 731 732 733 734 735 736
    """
    Requirements: ...

    Type: Event

    Pub/Sub: UI -> TT

    Description: Message for requesting session information to UI
    """

    """
    example:
737

738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
    [Session message] [<class 'messages.MsgUiSessionConfigurationReply'>] 

    ---------------  ---------------------------------------------------------------------------------------------------
     login              96QOPB1H
     testSuiteType      interoperability
     configuration      {'testsuite.additional_session_resource': 'automated_iut-coap_server-californium'}
     amqp_url           amqp://96QOPB1H:7OPU5N5E@mq.dev.f-interop.eu:443/396d9c99-3fd9-49dd-9515-a4ba745071c4
     messagesRequest    {}
     start_date         2018-01-17T13:51:31.264000+00:00
     id                 396d9c99-3fd9-49dd-9515-a4ba745071c4
     users              federico_sismondiojxu
                         myslice
     password           7OPU5N5E
     status             open
     _api_version
     logs               {'date': '2018-01-17T13:45:37.438000+00:00', 'type': 'info', 'message': 'Session created loca...
                         {'date': '2018-01-17T13:45:37.485000+00:00', 'type': 'info', 'message': 'Deploying session'}
                         {'date': '2018-01-17T13:45:37.577000+00:00', 'type': 'info', 'message': 'Created user at Ses...
                         {'date': '2018-01-17T13:45:38.027000+00:00', 'type': 'info', 'message': 'Created session at ...
                         {'date': '2018-01-17T13:45:38.027000+00:00', 'type': 'info', 'message': 'Session deployed'}
                         {'date': '2018-01-17T13:45:38.078000+00:00', 'type': 'info', 'message': 'Starting session'}
                         {'date': '2018-01-17T13:45:39.336000+00:00', 'type': 'info', 'message': 'Session started'}
                         {'date': '2018-01-17T13:51:04.967000+00:00', 'type': 'info', 'message': 'Stopping session'}
                         {'date': '2018-01-17T13:51:15.665000+00:00', 'type': 'info', 'message': 'Session stopped'}
                         {'date': '2018-01-17T13:51:15.666000+00:00', 'type': 'info', 'message': 'Messages cleared'}
                         {'date': '2018-01-17T13:51:15.699000+00:00', 'type': 'info', 'message': 'Stop listening to t...
                         {'date': '2018-01-17T13:51:31.264000+00:00', 'type': 'info', 'message': 'Starting session'}
                         {'date': '2018-01-17T13:51:32.462000+00:00', 'type': 'info', 'message': 'Session started'}
     end_date           2018-01-17T13:51:04.967000+00:00
     shared             False
     listen             True
     messages
     messagesReply
     testSuite          http://orchestrator.dev.f-interop.eu:8181/tests/f-interop/interoperability-coap-single-user
     messagesDisplay    {}
     slice_id           urn:publicid:IDN+finterop:project1+slice+testing
    ---------------  ---------------------------------------------------------------------------------------------------
775

776 777 778 779
    """
    routing_key = "ui.core.session.get.reply"

    _msg_data_template = {
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
        "amqp_url": "amqp://WX9D3L5A:5S68CRDC@mq.dev.f-interop.eu:443/277704a1-03c0-467c-b00d-c984976692d7",
        "logs": [
            {
                "date": "2018-05-07T12:50:47.224000+00:00",
                "message": "Session created locally",
                "type": "info"
            },
        ],
        "resources": [
            {}
        ],
        "shared": True,
        "slice_id": "urn:publicid:IDN+finterop:project1+slice+testing",
        "start_date": "2018-05-07T12:50:48.128000+00:00",
        "status": "open",
        "testSuite": "http://orchestrator.dev.f-interop.eu:8181/tests/f-interop/dummy-tool-shared",
        "testSuiteType": "interoperability",
        "users": [
            "federico_sismondiojxu",
            "myslice",
            "federicosismondiparu"
        ]
802 803 804
    }


805 806 807 808 809 810 811 812 813
class MsgUiRequestQuestionRadio(MsgUiRequest):
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

    Description: Message for radio request on UI
Pauline Gaudet-Chardonnet's avatar
Pauline Gaudet-Chardonnet committed
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
    """

    _msg_data_template = {
        "tags": {},
        "fields": [
            {
                "name": "True",
                "type": "radio",
                "value": True
            },
            {
                "name": "False",
                "type": "radio",
                "value": False
            },
        ]
    }

832 833

class MsgUiRequestQuestionCheckbox(MsgUiRequest):
Pauline Gaudet-Chardonnet's avatar
Pauline Gaudet-Chardonnet committed
834 835 836 837 838 839 840
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

841
    Description: Message for checkbox request on UI
Pauline Gaudet-Chardonnet's avatar
Pauline Gaudet-Chardonnet committed
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
    """

    _msg_data_template = {
        "tags": {},
        "fields": [
            {
                "name": "Choice1",
                "label": "Choice1",
                "type": "checkbox",
                "value": 0
            },
            {
                "name": "Choice2",
                "label": "Choice2",
                "type": "checkbox",
                "value": 1
            },
        ]
    }

862 863

class MsgUiRequestQuestionSelect(MsgUiRequest):
Pauline Gaudet-Chardonnet's avatar
Pauline Gaudet-Chardonnet committed
864 865 866 867 868 869 870
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

871
    Description: Message for select request on UI
Pauline Gaudet-Chardonnet's avatar
Pauline Gaudet-Chardonnet committed
872 873 874 875 876 877 878 879 880
    """

    _msg_data_template = {
        "tags": {},
        "fields": [
            {
                "name": "ideal_select",
                "type": "select",
                "options": [
881 882 883
                    {"label": "choice 1", "value": 1},
                    {"label": "choice 2", "value": 2},
                    {"label": "choice 3", "value": 3},
Pauline Gaudet-Chardonnet's avatar
Pauline Gaudet-Chardonnet committed
884 885 886 887 888 889
                ],
                "value": 1
            }
        ]
    }

890 891

class MsgUiRequestUploadFile(MsgUiRequest):
Pauline Gaudet-Chardonnet's avatar
Pauline Gaudet-Chardonnet committed
892 893 894 895 896 897 898
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

899
    Description: Message for file upload request on UI
Pauline Gaudet-Chardonnet's avatar
Pauline Gaudet-Chardonnet committed
900 901 902 903 904 905 906 907 908 909 910
    """

    _msg_data_template = {
        "tags": {},
        "fields": [
            {
                "name": "upload a file",
                "type": "file"
            }
        ]
    }
911

912 913

class MsgUiRequestTextInput(MsgUiRequest):
914 915 916 917 918 919 920
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

921
    Description: Message for requesting a text input on UI
922 923 924
    """

    _msg_data_template = {
925 926 927 928 929 930 931
        "tags": {},
        "fields": [
            {
                "name": "input_name",
                "type": "text"
            },
        ]
932 933 934
    }


935
class MsgUiRequestConfirmationButton(MsgUiRequest):
936 937 938 939 940 941 942
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

943
    Description: Message for requesting confirmation button
944 945 946
    """

    _msg_data_template = {
947
        "tags": {},
948 949
        "fields": [
            {
950 951 952
                "name": "test_button",
                "type": "button",
                "value": True
953 954 955 956 957
            },
        ]
    }


958
class MsgUiDisplayMarkdownText(MsgUiDisplay):
959 960 961 962 963 964 965
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

966
    Description: Message for displaying Markdown text to user interface
967 968 969
    """

    _msg_data_template = {
970
        "level": None,
971
        "tags": {},
972 973 974 975 976
        "fields": [
            {
                "type": "p",
                "value": "Hello World!"
            },
977 978 979
        ]
    }

980

981
# # # # # # AGENT MESSAGES # # # # # #
Federico Sismondi's avatar
Federico Sismondi committed
982

983

Federico Sismondi's avatar
Federico Sismondi committed
984 985
class MsgAgentTunStart(Message):
    """
986
    Requirements: Testing Tool MAY implement (if IP tun needed)
Federico Sismondi's avatar
Federico Sismondi committed
987

988
    Type: Event
Federico Sismondi's avatar
Federico Sismondi committed
989

990
    Pub/Sub: Testing Tool -> Agent
Federico Sismondi's avatar
Federico Sismondi committed
991

992
    Description: Message for triggering start IP tun interface in OS where the agent is running
Federico Sismondi's avatar
Federico Sismondi committed
993
    """
994 995 996 997

    # when publishing message * should be replaced by agent name (coap_client, coap_server)
    # * normally corresponds to iut role
    routing_key = "toAgent.*.ip.tun.start"
Federico Sismondi's avatar
Federico Sismondi committed
998 999

    _msg_data_template = {
1000 1001 1002
        "name": "agent_TT",
        "ipv6_prefix": "bbbb",
        "ipv6_host": ":3",
1003
        "ipv6_no_forwarding": False,
1004 1005 1006
        "ipv4_host": None,
        "ipv4_network": None,
        "ipv4_netmask": None,
1007 1008
        # following 3 are used to notify backend when Agent needs to re-route traffic to another interface
        "re_route_packets_if": None,
1009 1010
        "re_route_packets_prefix": None,
        "re_route_packets_host": None,
Federico Sismondi's avatar
Federico Sismondi committed
1011 1012 1013
    }


1014
class MsgAgentTunStarted(Message):
1015
    """
1016
    Requirements: Message for indicating that agent tun has been started
1017 1018 1019

    Type: Event

1020
    Pub/Sub: Agent -> Testing Tool
1021 1022 1023

    Description: TBD
    """
1024 1025 1026 1027

    # when publishing message * should be replaced by agent name (coap_client, coap_server)
    # * normally corresponds to iut role
    routing_key = "fromAgent.*.ip.tun.started"
1028 1029

    _msg_data_template = {
1030 1031 1032 1033 1034 1035 1036
        "name": "agent_TT",
        "ipv6_prefix": "bbbb",
        "ipv6_host": ":3",
        "ipv4_host": None,
        "ipv4_network": None,
        "ipv4_netmask": None,
        "ipv6_no_forwarding": False,
1037 1038
        # following 3 are used to notify backend when Agent needs to re-route traffic to another interface
        "re_route_packets_if": None,
1039 1040
        "re_route_packets_prefix": None,
        "re_route_packets_host": None,
1041 1042 1043
    }


1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
class MsgAgentSerialStart(Message):
    """
    Requirements: Testing Tool MAY implement (if serial interface is needed for the test)

    Type: Event

    Pub/Sub: Testing Tool -> Agent

    Description: Message for triggering start of serial interface , which communicates with probe 802.15.4
    """
1054 1055 1056 1057

    # when publishing message * should be replaced by agent name (coap_client, coap_server)
    # * normally corresponds to iut role
    routing_key = "toAgent.*.802154.serial.start"
1058 1059 1060 1061 1062 1063 1064 1065

    _msg_data_template = {
        "name": "tbd",
        "port": "tbd",
        "boudrate": "tbd",
    }


1066
class MsgAgentSerialStarted(Message):
Federico Sismondi's avatar
Federico Sismondi committed
1067
    """
1068
    Requirements: TBD
Federico Sismondi's avatar
Federico Sismondi committed
1069

1070
    Type: Event
Federico Sismondi's avatar
Federico Sismondi committed
1071

1072
    Pub/Sub: Testing Tool -> Agent
Federico Sismondi's avatar
Federico Sismondi committed
1073

1074
    Description: Message for indicating that agent serial interface has been started
Federico Sismondi's avatar
Federico Sismondi committed
1075
    """
1076 1077 1078 1079

    # when publishing message * should be replaced by agent name (coap_client, coap_server)
    # * normally corresponds to iut role
    routing_key = "fromAgent.*.802154.serial.started"
Federico Sismondi's avatar
Federico Sismondi committed
1080 1081

    _msg_data_template = {
1082 1083 1084
        "name": "tbd",
        "port": "tbd",
        "boudrate": "tbd",
Federico Sismondi's avatar
Federico Sismondi committed
1085 1086
    }

1087

1088 1089
class MsgPacketInjectRaw(Message):
    """
1090
    Requirements: Message to be captured by the agent an push into the correct embedded interface (e.g. tun, serial, etc..)
1091 1092 1093 1094 1095 1096 1097

    Type: Event

    Pub/Sub: Testing Tool -> Agent

    Description: TBD
    """
1098

1099 1100 1101
    # when publishing message * should be replaced by agent name (coap_client, coap_server)
    # * normally corresponds to iut role
    routing_key = "toAgent.*.ip.tun.packet.raw"
1102 1103

    _msg_data_template = {
1104
        "timestamp": 1488586183.45,
1105 1106 1107 1108 1109 1110
        "interface_name": "tun0",
        "data": [96, 0, 0, 0, 0, 36, 0, 1, 254, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 255, 2, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 22, 58, 0, 5, 2, 0, 0, 1, 0, 143, 0, 112, 7, 0, 0, 0, 1, 4, 0, 0, 0, 255, 2, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]}


1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
class MsgPacketSniffedRaw(Message):
    """
    Description: Message captured by the agent in one of its embedded interfaces (e.g. tun, serial, etc..)

    Type: Event

    Pub/Sub: Agent -> Testing Tool

    Description: TBD
    """
1121

1122 1123 1124
    # when publishing message * should be replaced by agent name (coap_client, coap_server)
    # * normally corresponds to iut role
    routing_key = "fromAgent.*.ip.tun.packet.raw"
1125 1126

    _msg_data_template = {
1127
        "timestamp": 1488586183.45,
1128 1129 1130 1131
        "interface_name": "tun0",
        "data": [96, 0, 0, 0, 0, 36, 0, 1, 254, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 255, 2, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 22, 58, 0, 5, 2, 0, 0, 1, 0, 143, 0, 112, 7, 0, 0, 0, 1, 4, 0, 0, 0, 255, 2, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]}
1132

1133 1134

# # # # # # SESSION MESSAGES # # # # # #
1135

1136
class MsgTestingToolTerminate(Message):
1137
    """
1138
    Requirements: TT MUST listen to event, and handle a gracefully termination of all it's processes
Federico Sismondi's avatar
Federico Sismondi committed
1139

1140
    Type: Event
Federico Sismondi's avatar
Federico Sismondi committed
1141

1142
    Pub/Sub: GUI, (or Orchestrator) -> Testing Tool
Federico Sismondi's avatar
Federico Sismondi committed
1143

1144
    Description: Testing tool should stop all it's processes gracefully.
1145
    """
1146
    routing_key = "testingtool.terminate"
1147 1148

    _msg_data_template = {
1149
        "description": "Command TERMINATE testing tool execution"
1150 1151 1152 1153 1154
    }


class MsgTestingToolReady(Message):
    """
1155
    Requirements: TT MUST publish event as soon as TT is up and listening on the event bus
Federico Sismondi's avatar
Federico Sismondi committed
1156

1157
    Type: Event
Federico Sismondi's avatar
Federico Sismondi committed
1158

1159
    Pub/Sub: Testing Tool -> GUI
Federico Sismondi's avatar
Federico Sismondi committed
1160

1161
    Description: Used to indicate to the GUI that testing is ready to start the test suite
1162
    """
1163
    routing_key = "testingtool.ready"
1164 1165

    _msg_data_template = {
1166
        "description": "Testing tool READY to start test suite."
1167 1168 1169 1170 1171
    }


class MsgTestingToolComponentReady(Message):
    """
1172
    Requirements: Testing Tool SHOULD implement (other components should not subscribe to event)
Federico Sismondi's avatar
Federico Sismondi committed
1173

1174
    Type: Event
Federico Sismondi's avatar
Federico Sismondi committed
1175

1176
    Pub/Sub: Any Testing tool's component -> Test Coordinator
Federico Sismondi's avatar
Federico Sismondi committed
1177

1178
    Description: Once a testing tool's component is ready, it should publish a compoennt ready message
1179
    """
1180
    routing_key = "testingtool.component.ready"
1181 1182

    _msg_data_template = {
1183
        "component": "SomeComponent",
1184
        "description": "Component READY to start test suite."
1185 1186 1187
    }


1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
class MsgSessionChat(Message):
    """
    Requirements: GUI should implement

    Type: Event

    Pub/Sub: UI 1 (2) -> UI 2 (1)

    Description: Generic descriptor of chat messages
    """
1198
    routing_key = "chat"
1199 1200 1201

    _msg_data_template = {
        "user_name": "Ringo",
1202
        "node": "tbd",
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
        "description": "I've got blisters on my fingers!"
    }


class MsgSessionLog(Message):
    """
    Requirements: Testing Tool SHOULD implement

    Type: Event

    Pub/Sub: Any Testing tool's component -> user/devs interfaces

    Description: Generic descriptor of log messages
    """
1217
    routing_key = "log.*.*"  # e.g log.warning.the_drummer
1218 1219

    _msg_data_template = {
Federico Sismondi's avatar
Federico Sismondi committed
1220
        "component": "misc",
1221
        "message": "I've got blisters on my fingers!"
1222 1223 1224
    }


1225
# TODO depricate this in favour of new UI call for getting the config
1226 1227
class MsgSessionConfiguration(Message):
    """
1228
    Requirements: TT MUST listen to event, and configure accordingly
1229 1230 1231 1232 1233

    Type: Event

    Pub/Sub: Orchestrator -> Testing Tool

1234
    Description: TT MUST listen to this message and configure the testsuite correspondingly
1235
    """
1236
    routing_key = "session.configuration"
1237

1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
    _msg_data_template = {
        "session_id": "666",
        "configuration": {
            'testsuite.testcases': [
                'someTestCaseId1',
                'someTestCaseId2'
            ]
        },
        "testing_tools": "f-interop/someTestToolId",
        "users": [
            "u1",
            "f-interop"
        ],
    }


1254 1255
class MsgTestingToolConfigured(Message):
    """
1256
    Requirements: TT MUST publish event once session.configuration message has been processed.
Federico Sismondi's avatar
Federico Sismondi committed
1257

1258
    Type: Event
Federico Sismondi's avatar
Federico Sismondi committed
1259

1260
    Pub/Sub: Testing Tool -> Orchestrator, GUI
Federico Sismondi's avatar
Federico Sismondi committed
1261

1262
    Description: The goal is to notify orchestrator and other components that the testing tool has been configured
1263 1264
    """

1265
    routing_key = "testingtool.configured"
1266 1267

    _msg_data_template = {
1268
        "description": "Testing tool CONFIGURED",
1269