messages.py 88.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
- re-use this also for the interactinggration testing;
14
15
16
- 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.2.15, 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.2.15, 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.2.15", "description": "Skip testcase", "node": "someNode", "testcase_id": "TD_COAP_CORE_03"}'
Federico Sismondi's avatar
add doc    
Federico Sismondi committed
47

48
# We can use the Message class to import json into Message objects:
Federico Sismondi's avatar
add doc    
Federico Sismondi committed
49
>>> m=MsgTestSuiteStart()
50
51
>>> m.routing_key
'testsuite.start'
Federico Sismondi's avatar
add doc    
Federico Sismondi committed
52
>>> m.to_json()
53
'{"_api_version": "1.2.15", "description": "Test suite START command"}'
Federico Sismondi's avatar
add doc    
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.2.15, 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.2.15, 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
add doc    
Federico Sismondi committed
80

81
82
83
84
# 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'}'

85
86
"""
from collections import OrderedDict
87
import logging
88
import time
89
90
91
import json
import uuid

92
93
logger = logging.getLogger(__name__)

94
API_VERSION = '1.2.15'
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.2.15", "capture_id": "TD_COAP_CORE_01"}'
205
206
        >>> json_message = m.to_json()
        >>> json_message
207
        '{"_api_version": "1.2.15", "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

215
        global rk_pattern_to_message_type_map
216
217
218

        props_dict = {}

219
220
221
222
        # 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:
223
            raise NonCompliantMessageFormatError("Routing key pattern not recogized for RKEY=%s" % routing_key)
224
225
226
227
228

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

229
        # fill message body from provided json
230
        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

        # let's update the messages properties
        if properties:
            built_message.update_properties(**props_dict)
244
        built_message.routing_key = routing_key
245
246
247

        return built_message

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
    When not passing request_message as argument
396
    """
397

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

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

            # 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,
                }
410

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

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

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

422
        else:  # note this doesnt copy amqp properties from original
Federico Sismondi's avatar
Federico Sismondi committed
423
            super(MsgReply, self).__init__(**kwargs)
424
425
426
            logger.info(
                '[messages] lazy message reply generated. Do not expect correlation between request and reply amqp'
                'properties  %s' % repr(self)[:70]
Federico Sismondi's avatar
Federico Sismondi committed
427
            )
428

429
430
431
432
433
434
435
436
    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

437
438
439

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

Federico Sismondi's avatar
Federico Sismondi committed
443
444
    def __init__(self, request_message, **kwargs):
        assert request_message
445
        super(MsgErrorReply, self).__init__(request_message, **kwargs)
446
447

    _msg_data_template = {
448
        "ok": False,
449
450
        "error_message": None,
        "error_code": None
451
452
    }

Federico Sismondi's avatar
Federico Sismondi committed
453

454
# # # # # # CORE API messages # # # # #
455
456

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

    Type: Event

    Pub/Sub: UI -> SO

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

    _msg_data_template = {
    }
470

Federico Sismondi's avatar
Federico Sismondi committed
471

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

    Type: Event

    Pub/Sub: UI -> SO

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

    _msg_data_template = {
    }


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

    Type: Event

    Pub/Sub: UI -> SO

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

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

    _msg_data_template = {
    }


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

    Type: Event

    Pub/Sub: UI -> SO

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

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

    _msg_data_template = {
    }


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

    Type: Event

    Pub/Sub: UI -> SO

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

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

    _msg_data_template = {
    }


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

    Type: Event

    Pub/Sub: UI -> SO

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

    _msg_data_template = {
    }


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

    Type: Event

    Pub/Sub: UI -> SO

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

    _msg_data_template = {
    }


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

    Type: Event

    Pub/Sub: UI -> SO

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

    _msg_data_template = {
    }


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

    Type: Event

    Pub/Sub: UI -> SO

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

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

    _msg_data_template = {
    }


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

    Type: Event

    Pub/Sub: UI -> SO

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

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


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

    Type: Event

    Pub/Sub: UI -> SO

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

    _msg_data_template = {
    }


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

    Type: Event

    Pub/Sub: UI -> SO

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

    _msg_data_template = {
    }


652
# # # # # # GUI API messages # # # # # # # #
653

654
class MsgUiReply(MsgReply):
Federico Sismondi's avatar
Federico Sismondi committed
655
656
657
658
659
660
661
    routing_key = "ui.user.all.reply"

    _msg_data_template = {
        "fields": [
        ]
    }

662

663
class MsgUiDisplay(Message):
664
665
666
667
668
669
670
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

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

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


687
class MsgUiRequest(Message):
688
689
690
691
692
693
694
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

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

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

709
710

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

    Type: Event

    Pub/Sub: TT -> UI

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

    _msg_data_template = {
    }


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

    Type: Event

    Pub/Sub: UI -> TT

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

    """
    example:
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
775
776
    [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
    ---------------  ---------------------------------------------------------------------------------------------------
777

778
779
780
781
    """
    routing_key = "ui.core.session.get.reply"

    _msg_data_template = {
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
        "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"
        ]
804
805
806
    }


807
808
809
810
811
812
813
814
815
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
816
817
818
819
820
821
    """

    _msg_data_template = {
        "tags": {},
        "fields": [
            {
822
                "name": "some_info",
Pauline Gaudet-Chardonnet's avatar
Pauline Gaudet-Chardonnet committed
823
                "type": "radio",
824
                "label": "choice number 1",
Pauline Gaudet-Chardonnet's avatar
Pauline Gaudet-Chardonnet committed
825
826
827
                "value": True
            },
            {
828
                "name": "some_info",
Pauline Gaudet-Chardonnet's avatar
Pauline Gaudet-Chardonnet committed
829
                "type": "radio",
830
                "label": "choice number 2",
Pauline Gaudet-Chardonnet's avatar
Pauline Gaudet-Chardonnet committed
831
832
833
834
835
                "value": False
            },
        ]
    }

836
837

class MsgUiRequestQuestionCheckbox(MsgUiRequest):
Pauline Gaudet-Chardonnet's avatar
Pauline Gaudet-Chardonnet committed
838
839
840
841
842
843
844
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

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

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

866
867

class MsgUiRequestQuestionSelect(MsgUiRequest):
Pauline Gaudet-Chardonnet's avatar
Pauline Gaudet-Chardonnet committed
868
869
870
871
872
873
874
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

875
    Description: Message for select request on UI
Pauline Gaudet-Chardonnet's avatar
Pauline Gaudet-Chardonnet committed
876
877
878
879
880
881
882
883
884
    """

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

894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916

class MsgUiSendFileToDownload(MsgUiDisplay):
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

    Description: Message for file download on UI
    """

    _msg_data_template = {
        "tags": {},
        "fields": [
            {
                "name": "some_test_pcap_file.pcap",
                "type": "data",
                "value": None,  # base64_encoded
            }
        ]
    }

917
918

class MsgUiRequestUploadFile(MsgUiRequest):
Pauline Gaudet-Chardonnet's avatar
Pauline Gaudet-Chardonnet committed
919
920
921
922
923
924
925
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

926
    Description: Message for file upload request on UI
Pauline Gaudet-Chardonnet's avatar
Pauline Gaudet-Chardonnet committed
927
928
929
930
931
932
933
934
935
936
937
    """

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

939
940

class MsgUiRequestTextInput(MsgUiRequest):
941
942
943
944
945
946
947
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

948
    Description: Message for requesting a text input on UI
949
950
951
    """

    _msg_data_template = {
952
953
954
955
956
957
958
        "tags": {},
        "fields": [
            {
                "name": "input_name",
                "type": "text"
            },
        ]
959
960
961
    }


962
class MsgUiRequestConfirmationButton(MsgUiRequest):
963
964
965
966
967
968
969
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

970
    Description: Message for requesting confirmation button
971
972
973
    """

    _msg_data_template = {
974
        "tags": {},
975
976
        "fields": [
            {
977
978
979
                "name": "test_button",
                "type": "button",
                "value": True
980
981
982
983
984
            },
        ]
    }


985
class MsgUiDisplayMarkdownText(MsgUiDisplay):
986
987
988
989
990
991
992
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

993
    Description: Message for displaying Markdown text to user interface
994
995
996
    """

    _msg_data_template = {
Federico Sismondi's avatar
Federico Sismondi committed
997
        "level": None,
998
        "tags": {},
999
1000
1001
1002
1003
        "fields": [
            {
                "type": "p",
                "value": "Hello World!"
            },
1004
1005
1006
        ]
    }

1007

1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
class MsgUiDisplayIFrame(Message):
    """
    Requirements: ...

    Type: Event

    Pub/Sub: TT -> UI

    Description: Message for displaying iframing GUI and external server
    """

    routing_key = "ui.user.all.display"

    _msg_data_template = {
        "level": None,
        "tags": {},
        "fields": [
            {
                "type": "iframe",
                "name": "my_iframe",
                "value": "https://www.w3schools.com"
            },
        ]
    }

1033
# # # # # # AGENT MESSAGES # # # # # #
Federico Sismondi's avatar
Federico Sismondi committed
1034

1035

Federico Sismondi's avatar
Federico Sismondi committed
1036
1037
class MsgAgentTunStart(Message):
    """
1038
    Requirements: Testing Tool MAY implement (if IP tun needed)
Federico Sismondi's avatar
Federico Sismondi committed
1039

1040
    Type: Event
Federico Sismondi's avatar
Federico Sismondi committed
1041

1042
    Pub/Sub: Testing Tool -> Agent
Federico Sismondi's avatar
Federico Sismondi committed
1043

1044
    Description: Message for triggering start IP tun interface in OS where the agent is running
Federico Sismondi's avatar
Federico Sismondi committed
1045
    """
1046
1047
1048
1049

    # 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
1050
1051

    _msg_data_template = {
1052
1053
1054
        "name": "agent_TT",
        "ipv6_prefix": "bbbb",
        "ipv6_host": ":3",
1055
        "ipv6_no_forwarding": False,
1056
1057
1058
        "ipv4_host": None,
        "ipv4_network": None,
        "ipv4_netmask": None,
1059
1060
        # following 3 are used to notify backend when Agent needs to re-route traffic to another interface
        "re_route_packets_if": None,
Federico Sismondi's avatar
Federico Sismondi committed
1061
1062
        "re_route_packets_prefix": None,
        "re_route_packets_host": None,
Federico Sismondi's avatar
Federico Sismondi committed
1063
1064
1065
    }


1066
class MsgAgentTunStarted(Message):
1067
    """
1068
    Requirements: Message for indicating that agent tun has been started
1069
1070
1071

    Type: Event

1072
    Pub/Sub: Agent -> Testing Tool
1073
1074
1075

    Description: TBD
    """
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.*.ip.tun.started"
1080
1081

    _msg_data_template = {
1082
1083
1084
1085
1086
1087
1088
        "name": "agent_TT",
        "ipv6_prefix": "bbbb",
        "ipv6_host": ":3",
        "ipv4_host": None,
        "ipv4_network": None,
        "ipv4_netmask": None,
        "ipv6_no_forwarding": False,
1089
1090
        # following 3 are used to notify backend when Agent needs to re-route traffic to another interface
        "re_route_packets_if": None,
Federico Sismondi's avatar
Federico Sismondi committed
1091
1092
        "re_route_packets_prefix": None,
        "re_route_packets_host": None,
1093
1094
1095
    }


1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
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
    """
1106
1107
1108
1109

    # when publishing message * should be replaced by agent name (coap_client, coap_server)
    # * normally corresponds to iut role
    routing_key = "toAgent.*.802154.serial.start"
1110
1111

    _msg_data_template = {
1112
1113
1114
        "name": None,
        "port": None,
        "boudrate": None,
1115
1116
1117
    }


1118
class MsgAgentSerialStarted(Message):
Federico Sismondi's avatar
Federico Sismondi committed
1119
    """
1120
    Requirements: TBD
Federico Sismondi's avatar
Federico Sismondi committed
1121

1122
    Type: Event
Federico Sismondi's avatar
Federico Sismondi committed
1123

1124
    Pub/Sub: Testing Tool -> Agent
Federico Sismondi's avatar
Federico Sismondi committed
1125

1126
    Description: Message for indicating that agent serial interface has been started
Federico Sismondi's avatar
Federico Sismondi committed
1127
    """
1128
1129
1130
1131

    # 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
1132
1133

    _msg_data_template = {
1134
1135
1136
        "name": None,
        "port": None,
        "boudrate": None,
Federico Sismondi's avatar
Federico Sismondi committed
1137
1138
    }

1139

1140
1141
class MsgPacketInjectRaw(Message):
    """
1142
    Requirements: Message to be captured by the agent an push into the correct embedded interface (e.g. tun, serial, etc..)
1143
1144
1145
1146
1147
1148
1149

    Type: Event

    Pub/Sub: Testing Tool -> Agent

    Description: TBD
    """
1150

1151
1152
1153
    # 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"
1154
1155

    _msg_data_template = {
1156
        "timestamp": 1488586183.45,
1157
1158
1159
1160
1161
1162
        "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]}


1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
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
    """
1173

1174
1175
1176
    # 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"
1177
1178

    _msg_data_template = {
1179
        "timestamp": 1488586183.45,
1180
1181
1182
1183
        "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]}
1184

1185
1186

# # # # # # SESSION MESSAGES # # # # # #
1187

1188
class MsgTestingToolTerminate(Message):
1189
    """
1190
    Requirements: TT SHOULD listen to event, and handle a gracefully termination of all it's processes
Federico Sismondi's avatar
Federico Sismondi committed
1191

1192
    Type: Event
Federico Sismondi's avatar
Federico Sismondi committed
1193

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

1196
    Description: Testing tool should stop all it's processes gracefully.
1197
    """
1198
    routing_key = "testingtool.terminate"
1199
1200

    _msg_data_template = {
1201
        "description": "Command TERMINATE testing tool execution"
1202
1203
1204
1205
1206
    }


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

1209
    Type: Event
Federico Sismondi's avatar
Federico Sismondi committed
1210

1211
    Pub/Sub: Testing Tool -> GUI
Federico Sismondi's avatar
Federico Sismondi committed
1212

1213
    Description: Used to indicate to the GUI that testing is ready to start the test suite
1214
    """
1215
    routing_key = "testingtool.ready"
1216
1217
</