ioppytest_cli.py 39.3 KB
Newer Older
1
import os
2
from os.path import expanduser
3 4
import sys
import pika
5
import errno
6
import base64
7 8 9
import logging
import threading
import traceback
10

11
from collections import OrderedDict
12

13
import click
14 15 16
from click_repl import ExitReplException
from click_repl import repl as repl_base
from prompt_toolkit.history import FileHistory
17

18 19 20
# for using it as library and as a __main__
try:
    from messages import *
21
    from event_bus_utils import AmqpListener
22 23
    from tabulate import tabulate
except:
24 25 26
    from ..messages import *
    from ..event_bus_utils import AmqpListener
    from ..tabulate import tabulate
27

28 29
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.WARNING)

30 31 32
COMPONENT_ID = 'ioppytest-cli'

HOME = expanduser("~")
Federico Sismondi's avatar
Federico Sismondi committed
33

34 35 36 37 38 39 40 41 42 43
# click colors:: black (might gray) , red, green, yellow (might be an orange), blue, magenta, cyan, white (might gray)
COLOR_DEFAULT = 'white'
COLOR_SESSION_LOG = 'white'
COLOR_COORDINATION_MESSAGE = 'cyan'
COLOR_SESSION_ASSISTANCE = 'cyan'
COLOR_CHAT_MESSAGE = 'green'
COLOR_CHAT_MESSAGE_ECHO = 'green'
COLOR_ERROR_MESSAGE = 'red'
COLOR_TEST_SESSION_HELPER_MESSAGE = 'yellow'

44 45
# DIR used for network dumps and other type of tmp files
TEMP_DIR = 'tmp'
46
WAIT_TIME_FOR_USER_INPUT = 60
47

48 49 50 51 52 53 54
DEFAULT_TOPIC_SUBSCRIPTIONS = [
    '#'
]

MESSAGE_TYPES_NOT_ECHOED = [
]

Federico Sismondi's avatar
Federico Sismondi committed
55 56
CONNECTION_SETUP_RETRIES = 3

57 58 59 60 61 62 63 64 65 66
session_profile = OrderedDict(
    {
        'user_name': "Walter White",
        'protocol': "coap",
        'node': "both",
        'amqp_url': "amqp://{0}:{1}@{2}/{3}".format("guest", "guest", "localhost", "/"),
        'amqp_exchange': "amq.topic",
    }
)

67
state_lock = threading.RLock()
68 69 70 71 72 73 74 75 76
state = {
    'testcase_id': None,
    'step_id': None,
    'last_message': None,
    'suggested_cmd': None,
    'connection': None,
    'channel': None,
}
profile_choices = {
Federico Sismondi's avatar
Federico Sismondi committed
77 78
    'protocol': ['coap', '6lowpan', 'onem2m'],
    'node': ['coap_client', 'coap_server']
79 80
}

Federico Sismondi's avatar
Federico Sismondi committed
81
# e.g. MsgTestingToolConfigured is normally followed by a test suite start (ts_start)
82 83 84 85 86 87 88 89
UI_suggested_actions = {
    MsgTestingToolConfigured: 'ts_start',
    MsgTestCaseReady: 'tc_start',
    MsgStepStimuliExecute: 'stimuli',
    MsgStepVerifyExecute: 'verify',
}


Federico Sismondi's avatar
Federico Sismondi committed
90 91
def _init_action_suggested():
    state['suggested_cmd'] = 'ts_start'
92 93 94 95 96 97 98


@click.group()
def cli():
    pass


99 100 101
@cli.command()
def repl():
    """
Federico Sismondi's avatar
Federico Sismondi committed
102
    Interactive shell, allows user to interact with the ioppytest testing tool
103
    """
104 105 106 107 108 109 110 111 112

    history_path_file = "{dir}{sep}{comp_name}-history".format(dir=HOME, sep=os.path.sep, comp_name=COMPONENT_ID)
    if not os.path.exists(os.path.dirname(history_path_file)):
        try:
            os.makedirs(os.path.dirname(history_path_file))
        except OSError as exc:  # Guard against race condition
            if exc.errno != errno.EEXIST:
                raise

113
    prompt_kwargs = {
114
        'history': FileHistory(history_path_file),
115
    }
116
    _echo_log_message('saving CMD history at: {}'.format(history_path_file))
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132

    _echo_welcome_message()
    _pre_configuration()
    _echo_session_helper("\nYou can press TAB for the available commands at any time \n")

    _echo_session_helper("\nThe command <action [param]> needs to be used for executing the test actions\n")
    _echo_session_helper(
        "\nNote that <action suggested> will help you navigate through the session by executing the "
        "actions the backend normally expects for a standard session flow :)\n")
    _init_action_suggested()

    _set_up_connection()

    repl_base(click.get_current_context(), prompt_kwargs=prompt_kwargs)


133
@cli.command()
134 135 136
@click.option('-ll', '--lazy-listener',
              is_flag=True,
              default=False,
137
              help="lazy-listener doest perform conversion to Messages objects")
138
def connect(lazy_listener):
139 140 141
    """
    Connect to an AMQP session and start consuming messages
    """
142
    _set_up_connection(lazy_listener=lazy_listener)
143 144 145 146 147


@cli.command()
def exit():
    """
Federico Sismondi's avatar
Federico Sismondi committed
148
    Exits REPL
149 150 151 152

    """
    _exit()

153

154 155 156 157 158 159 160 161 162 163 164 165 166 167
@cli.command()
def download_network_traces():
    """
    Downloads all networks traces generated during the session
    """
    global state

    _handle_get_testcase_list()
    ls = state['tc_list'].copy()

    for tc_item in ls:
        try:
            tc_id = tc_item['testcase_id']
            msg = MsgSniffingGetCapture(capture_id=tc_id)
168
            response = _amqp_request(msg, COMPONENT_ID)
169 170

            if response.ok:
171
                _save_file_from_base64(response.filename, response.value, TEMP_DIR)
172 173 174 175 176 177 178 179
                _echo_input("downloaded network trace %s , into dir: %s" % (response.filename, TEMP_DIR))
            else:
                raise Exception(response.error_message)

        except Exception as e:
            _echo_error('Error trying to download network traces for testcase : %s' % tc_id)
            _echo_error(e)

180

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
@cli.command()
@click.argument('path-to-file', type=click.Path(exists=True))
@click.option('--text-message', default=None, help="Message to be displayed in GUI")
@click.option('--user-id', default='all', help="User ID in case there are several users in session")
def gui_request_file_upload(path_to_file, text_message, user_id):
    """
    Request user to upload a file, saves it in directory (if provided) or else in .tmp
    """
    global state

    msg_request = MsgUiRequestUploadFile()

    msg_request.fields = [
        {
            "name": text_message,
            "type": "file",
        }
    ]

    if user_id:
        msg_request.routing_key = "ui.user.{}.request".format(user_id)

Federico Sismondi's avatar
Federico Sismondi committed
203
    _echo_input("sending request to {}".format(msg_request.routing_key))
204 205 206 207 208 209 210 211 212 213
    msg_response = _amqp_request(msg_request, COMPONENT_ID, timeout=WAIT_TIME_FOR_USER_INPUT)
    values_dict = msg_response.fields.pop()  # If there's more than one then GUI fucked up

    value = values_dict['value']
    filename = values_dict['filename']

    _save_file_from_base64(filename, value, path_to_file)
    _echo_input("saved file {} in path {}".format(filename, path_to_file))


Federico Sismondi's avatar
Federico Sismondi committed
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
@cli.command()
@click.argument('text-message')
@click.option('--user-id', default='all', help="User ID in case there are several users in session")
def gui_display_message(text_message, user_id):
    """
    Sends message to GUI
    """
    global state

    msg_display = MsgUiDisplay()

    msg_display.fields = [
        {
            "name": text_message,
            "type": "p",
        }
    ]

    if user_id:
        msg_display.routing_key = "ui.user.{}.display".format(user_id)

    _publish_message(msg_display)
    _echo_input("message display sent to {}".format(msg_display.routing_key))


239 240 241 242 243 244 245 246 247
@cli.command()
def clear():
    """
    Clear screen
    """

    click.clear()


Federico Sismondi's avatar
Federico Sismondi committed
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
def _handle_testcase_select():
    #  requires testing tool to implement GetTestCases feature see MsgTestSuiteGetTestCases
    _handle_get_testcase_list()
    ls = state['tc_list'].copy()

    i = 1
    for tc_item in ls:
        _echo_dispatcher("%s -> %s" % (i, tc_item['testcase_id']))
        i += 1

    resp = click.prompt('Select number of test case to execute from list', type=int)

    try:
        _echo_input("entered %s, corresponding to %s" % (resp, ls[resp - 1]['testcase_id']))
    except Exception as e:
        _echo_error("wrong input \n %s" % e)
        return

    msg = MsgTestCaseSelect(
        testcase_id=ls[resp - 1]['testcase_id']
    )

270
    _publish_message(msg)
Federico Sismondi's avatar
Federico Sismondi committed
271 272 273


def _handle_get_testcase_list():
Federico Sismondi's avatar
Federico Sismondi committed
274
    #  requires testing tool to implement GetTestCases feature, see MsgTestSuiteGetTestCases
275

276
    request_message = MsgTestSuiteGetTestCases()
Federico Sismondi's avatar
Federico Sismondi committed
277

278 279 280 281 282 283
    try:
        testcases_list_reponse = _amqp_request(request_message, COMPONENT_ID)
    except Exception as e:
        _echo_error('Is testing tool up?')
        _echo_error(e)
        return
Federico Sismondi's avatar
Federico Sismondi committed
284

285 286 287 288 289
    try:
        state['tc_list'] = testcases_list_reponse.tc_list
    except Exception as e:
        _echo_error(e)
        return
Federico Sismondi's avatar
Federico Sismondi committed
290

291
    _echo_list_of_dicts_as_table(state['tc_list'])
Federico Sismondi's avatar
Federico Sismondi committed
292

293

294 295 296
def _handle_action_testsuite_start():
    if click.confirm('Do you want START test suite?'):
        msg = MsgTestSuiteStart()
297
        _publish_message(msg)
298 299 300 301


def _handle_action_testcase_start():
    if click.confirm('Do you want START test case?'):
302
        msg = MsgTestCaseStart()  # TODO no testcase id input?
303
        _publish_message(msg)
304 305 306 307 308


def _handle_action_testsuite_abort():
    if click.confirm('Do you want ABORT test suite?'):
        msg = MsgTestSuiteAbort()
309
        _publish_message(msg)
310 311 312 313 314


def _handle_action_testcase_skip():
    if click.confirm('Do you want SKIP current test case?'):
        msg = MsgTestCaseSkip()
315
        _publish_message(msg)
316 317 318 319 320


def _handle_action_testcase_restart():
    if click.confirm('Do you want RESTART current test case?'):
        msg = MsgTestCaseRestart()
321
        _publish_message(msg)
322 323 324 325 326 327 328 329 330 331 332 333 334


def _handle_action_stimuli():
    if isinstance(state['last_message'], MsgStepStimuliExecute):
        _echo_session_helper(list_to_str(state['last_message'].description))

    resp = click.confirm('Did you execute last STIMULI step (if any received)?')

    if resp:
        msg = MsgStepStimuliExecuted(
            node=session_profile['node'],
            node_execution_mode="user_assisted"
        )
335
        _publish_message(msg)
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

    else:
        _echo_error('Please execute all pending STIMULI steps')


def _handle_action_verify():
    if isinstance(state['last_message'], MsgStepVerifyExecute):
        _echo_session_helper(list_to_str(state['last_message'].description))

    resp = click.prompt("Last verify step was <ok> or not <nok>", type=click.Choice(['ok', 'nok']))

    msg = MsgStepVerifyExecuted(
        response_type="bool",
        verify_response=True if resp == 'ok' else False,
        node=session_profile['node'],
        node_execution_mode="user_assisted"
    )

354
    _publish_message(msg)
355 356 357 358 359 360 361


message_handles_options = {'ts_start': _handle_action_testsuite_start,
                           'ts_abort': _handle_action_testsuite_abort,
                           'tc_start': _handle_action_testcase_start,
                           'tc_restart': _handle_action_testcase_restart,
                           'tc_skip': _handle_action_testcase_skip,
Federico Sismondi's avatar
Federico Sismondi committed
362 363
                           'tc_list': _handle_get_testcase_list,
                           'tc_select': _handle_testcase_select,
364 365 366 367 368 369 370 371 372 373
                           'verify': _handle_action_verify,
                           'stimuli': _handle_action_stimuli,
                           'suggested': None,
                           }


@cli.command()
@click.argument('api_call', type=click.Choice(message_handles_options.keys()))
def action(api_call):
    """
374
    Execute interop test action
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
    """

    _echo_input(api_call)

    if api_call == 'suggested':
        if state['suggested_cmd']:
            _echo_dispatcher("Executing : %s" % state['suggested_cmd'])
            message_handles_options[state['suggested_cmd']]()
            state['suggested_cmd'] = None
            return
        else:
            _echo_error('No suggested message yet.')
            return

    elif api_call in message_handles_options:
        func = message_handles_options[api_call]
        func()

    else:
        _echo_dispatcher('Command <action %s> not accepted' % api_call)


397 398 399 400 401 402 403 404 405 406 407
ignorable_message_types = {
    'dissections': [MsgDissectionAutoDissect],
    'packets': [MsgPacketSniffedRaw, MsgPacketInjectRaw],
    'ui': [MsgUiRequestTextInput,
           MsgUiRequestConfirmationButton,
           MsgUiDisplay,
           MsgUiDisplayMarkdownText,
           MsgUiReply]
}


408
@cli.command()
409
@click.argument('message_type', type=click.Choice(list(ignorable_message_types.keys())))
410 411
def ignore(message_type):
    """
Federico Sismondi's avatar
Federico Sismondi committed
412
    (REPL only) Do not notify any more on message type
413
    """
414 415
    try:
        for item in ignorable_message_types[message_type]:
416 417
            _add_to_ignore_message_list(item)
            _echo_dispatcher('Ignore message category %s: (%s)' % (message_type, str(item)))
418 419 420
    except KeyError as ke:
        _echo_error('Couldnt add to ignored list..')
        _echo_error(ke)
421 422


423 424 425
@cli.command()
def enter_debug_context():
    """
Federico Sismondi's avatar
Federico Sismondi committed
426
    (REPL only) Provides user with some extra debugging commands
427 428 429 430

    """
    global message_handles_options

431 432 433 434 435 436 437 438 439 440 441 442
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    #  this build dinamically a REPL call per each message defined in messages library

    dummy_messages_dict = {k: v for (k, v) in globals().items() if 'Msg' in k}

    def _send_dummy_message():
        ctx = click.get_current_context()
        message_name = ctx.command.name.replace('_send_', '')

        try:
            message_t = dummy_messages_dict[message_name]()
            _echo_input("trying to send message: %s" % repr(message_t))
443
            _publish_message(message_t)
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463

        except Exception as e:
            _echo_error("Error found: %s" % e)
            return

    for message in list(dummy_messages_dict.keys()):
        name = "_send_%s" % message
        _echo_session_helper('adding cmd: %s' % name)
        c = click.Command(
            name=name,
            callback=_send_dummy_message,
            # params=[
            #     message
            # ],
            short_help="Send dummy %s message to bus." % message
        )

        cli.add_command(c)
        # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

464 465
    # TODO group cmds
    @cli.command()
466
    @click.option('-tc', '--testcase-id', default=None, help="testcase id")
467
    def _sniffer_start(testcase_id):
468 469 470
        """
        Sniffer start
        """
471 472 473 474 475 476 477
        if testcase_id is None:
            testcase_id = 'PCAP_TEST'

        _echo_input("Executing debug message %s" % sys._getframe().f_code.co_name)
        msg = MsgSniffingStart(capture_id=testcase_id,
                               filter_if='tun0',
                               filter_proto='udp')
478
        _publish_message(msg)
479 480

    @cli.command()
481
    def _sniffer_stop():
482 483 484
        """
        Sniffer stop
        """
485 486
        _echo_input("Executing debug message %s" % sys._getframe().f_code.co_name)
        msg = MsgSniffingStop()
487
        _publish_message(msg)
488 489

    @cli.command()
490
    def _sniffer_get_last_capture():
491 492 493
        """
        Sniffer get last capture
        """
494 495
        _echo_input("Executing debug message %s" % sys._getframe().f_code.co_name)
        msg = MsgSniffingGetCaptureLast()
496
        _publish_message(msg)
497

498 499 500 501 502
    @cli.command()
    def _configure_perf_tt():
        """
        Send example configuration message for perf TT
        """
503 504 505
        _echo_input("Executing debug message %s" % sys._getframe().f_code.co_name)
        from message_examples import PERF_TT_CONFIGURATION
        message = MsgSessionConfiguration(**PERF_TT_CONFIGURATION)  # builds a config for the perf TT
506
        _publish_message(message)
507

508 509 510 511 512
    @cli.command()
    def _configure_comi_tt():
        """
        Send example configuration message for CoMI TT
        """
513 514 515
        _echo_input("Executing debug message %s" % sys._getframe().f_code.co_name)
        from message_examples import COMI_TT_CONFIGURATION
        message = MsgSessionConfiguration(**COMI_TT_CONFIGURATION)  # builds a config message
516
        _publish_message(message)
517

518 519 520 521 522 523 524 525
    @cli.command()
    def _configure_6lowpan_tt():
        """
        Send example configuration message for SIXLOWPAN TT
        """
        _echo_input("Executing debug message %s" % sys._getframe().f_code.co_name)
        from message_examples import SIXLOWPAN_TT_CONFIGURATION
        message = MsgSessionConfiguration(**SIXLOWPAN_TT_CONFIGURATION)  # builds a config message
526
        _publish_message(message)
527

528 529 530 531 532 533 534 535
    @cli.command()
    def _test_tat_analyze_6lowpan():
        """
        Send example 6lowpan tat analysis request
        """
        _echo_input("Executing debug message %s" % sys._getframe().f_code.co_name)
        from message_examples import SIXLOWPAN_TAT_ANALYZE
        message = MsgInteropTestCaseAnalyze(**SIXLOWPAN_TAT_ANALYZE)
536
        _publish_message(message)
537

538 539 540 541 542
    @cli.command()
    def _configure_coap_tt():
        """
        Send example configuration message for CoAP TT
        """
543 544 545
        _echo_input("Executing debug message %s" % sys._getframe().f_code.co_name)
        from message_examples import COAP_TT_CONFIGURATION
        message = MsgSessionConfiguration(**COAP_TT_CONFIGURATION)  # builds a config message
546
        _publish_message(message)
547

548 549 550 551 552
    @cli.command()
    def _get_session_configuration_from_ui():
        """
        Get session config from UI
        """
553 554
        _echo_input("Executing debug message %s" % sys._getframe().f_code.co_name)
        req = MsgUiRequestSessionConfiguration()
555
        _publish_message(req)
556

557 558
    @cli.command()
    @click.argument('testcase_id')
559
    def _testcase_skip(testcase_id):
560
        """
561
        Skip a particular testcase
562
        """
563 564 565 566 567
        _echo_input("Executing debug message %s" % sys._getframe().f_code.co_name)

        msg = MsgTestCaseSkip(
            testcase_id=testcase_id
        )
568
        _publish_message(msg)
569 570 571

    @cli.command()
    @click.argument('text')
572
    def _ui_display_markdown_text(text):
573
        """
574
        Send message to GUI
575
        """
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
        _echo_input("Executing debug message %s" % sys._getframe().f_code.co_name)

        msg = MsgUiDisplayMarkdownText()

        _echo_input(text)

        if text:
            fields = [
                {
                    'type': 'p',
                    'value': text
                }
            ]
            msg.fields = fields

591
        _publish_message(msg)
592

593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
    @cli.command()
    @click.argument('text')
    def _ui_send_confirmation_button(text):
        """
        Send button to GUI
        """
        _echo_input("Executing debug message %s" % sys._getframe().f_code.co_name)

        msg = MsgUiRequestConfirmationButton()

        _echo_input(text)

        msg.fields = [{
            "name": text,
            "type": "button",
            "value": True
        }]

611
        _publish_message(msg)
612

613 614 615 616 617 618 619 620 621 622 623 624 625 626
    @cli.command()
    @click.argument('text')
    def _ui_send_confirmation_button(text):
        """
        Send button to GUI
        """
        _echo_input("Executing debug message %s" % sys._getframe().f_code.co_name)

        msg = MsgSessionLog(
            component=COMPONENT_ID,
            message=text
        )

        _echo_input(text)
627
        _publish_message(msg)
628

629 630 631 632 633 634 635 636 637 638 639 640 641 642
    @cli.command()
    @click.argument('text')
    def _ui_send_confirmation_button(text):
        """
        Send button to GUI
        """
        _echo_input("Executing debug message %s" % sys._getframe().f_code.co_name)

        msg = MsgSessionLog(
            component=COMPONENT_ID,
            message=text
        )

        _echo_input(text)
643
        _publish_message(msg)
644

645
    _echo_session_helper("Entering debugger context, added extra CMDs, please type --help for more info")
646 647


648 649 650 651
@cli.command()
@click.argument('message', nargs=-1)
def chat(message):
    """
652
    Send chat message, useful for user-to-user test sessions
653 654 655 656 657 658 659 660 661 662
    """

    m = ''

    for word in message:
        m += " %s" % word

    c = MsgSessionChat(description=m,
                       user_name=session_profile['user_name'],
                       iut_node=session_profile['node'])
663
    _publish_message(c)
664 665 666 667 668


@cli.command()
def check_connection():
    """
Federico Sismondi's avatar
Federico Sismondi committed
669
    (REPL only) Check if AMQP connection is active
670 671 672 673 674
    """
    conn_ok = _connection_ok()
    _echo_dispatcher('connection is %s' % 'OK' if conn_ok else 'not OK')
    return conn_ok

675

676 677 678 679 680 681 682 683 684 685 686
@cli.command()
def get_session_status():
    """
    Retrieves status information from testing tool
    """

    #  requires testing tool to implement GetStatus feature, see MsgTestSuiteGetStatus
    if _connection_ok():
        request_message = MsgTestSuiteGetStatus()

        try:
687
            status_resp = _amqp_request(request_message, COMPONENT_ID)
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
        except Exception as e:
            _echo_error('Is testing tool up?')
            _echo_error(e)
            return

        resp = status_resp.to_dict()
        tc_states = resp['tc_list']
        del resp['tc_list']

        # print general states
        _echo_dict_as_table(resp)

        list = []
        list.append(('testcase id', 'testcase ref', 'testcase status'))
        for tc in tc_states:
            if tc:
                val1, val2, val3, _, _, _ = tc.values()
                list.append((val1, val2, val3))
        # print tc states
        _echo_list_as_table(list, first_row_is_header=True)

    else:
        _echo_error('No connection established')

712 713

@cli.command()
714
def get_session_parameters():
715 716 717 718 719 720 721 722 723 724
    """
    Print session state and parameters
    """

    _echo_context()


def _connection_ok():
    conn_ok = False
    try:
725
        conn_ok = state['connection'] is not None and state['connection'].is_open
726 727 728 729 730 731 732 733 734 735
    except AttributeError as ae:
        pass
    except TypeError as ae:
        pass

    return conn_ok


def _echo_context():
    table = []
736 737 738 739 740
    d = {}
    d.update(session_profile)
    d.update(state)
    for key, val in d.items():
        table.append((key, list_to_str(str(val))))
741 742 743
    _echo_list_as_table(table)


744
def _set_up_connection(create_listener=True, lazy_listener=False):
745 746
    # conn for repl publisher
    try:
Federico Sismondi's avatar
Federico Sismondi committed
747
        retries_left = CONNECTION_SETUP_RETRIES
748
        state_lock.acquire()
Federico Sismondi's avatar
Federico Sismondi committed
749 750
        while retries_left > 0:
            try:
751

Federico Sismondi's avatar
Federico Sismondi committed
752 753 754 755 756
                state['connection'] = pika.BlockingConnection(pika.URLParameters(session_profile['amqp_url']))
                state['channel'] = state['connection'].channel()
                break
            except pika.exceptions.ConnectionClosed:
                retries_left -= 1
757 758
                _echo_session_helper("Couldnt establish connection, retrying .. %s/%s " % (
                    CONNECTION_SETUP_RETRIES - retries_left, CONNECTION_SETUP_RETRIES))
Federico Sismondi's avatar
Federico Sismondi committed
759

760 761 762 763 764 765
    except pika.exceptions.ProbableAccessDeniedError:
        _echo_error('Probable access denied error. Is provided AMQP_URL correct?')
        state['connection'] = None
        state['channel'] = None
        return

766 767 768
    finally:
        state_lock.release()

769 770 771 772 773 774 775 776 777 778
    # note we have a separate conn for amqp listener (each pika threads needs a different connection)
    if 'amqp_listener_thread' in state and state['amqp_listener_thread'] is not None:
        _echo_log_message('stopping amqp listener thread')
        th = state['amqp_listener_thread']
        th.stop()
        th.join(2)
        if th.isAlive():
            _echo_log_message('amqp listener thread doesnt want to stop, lets terminate it..')
            th.terminate()

779 780 781 782 783
    if create_listener is False:
        return

    # set up listener thread which will call callback each time there's a new message in bus and matches a topic

784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
    if lazy_listener:
        amqp_listener_thread = AmqpListener(
            amqp_url=session_profile['amqp_url'],
            amqp_exchange=session_profile['amqp_exchange'],
            callback=None,
            topics=DEFAULT_TOPIC_SUBSCRIPTIONS,
            use_message_typing=False,
        )
    else:
        amqp_listener_thread = AmqpListener(
            amqp_url=session_profile['amqp_url'],
            amqp_exchange=session_profile['amqp_exchange'],
            callback=_message_handler,
            topics=DEFAULT_TOPIC_SUBSCRIPTIONS,
            use_message_typing=True,
        )
Federico Sismondi's avatar
Federico Sismondi committed
800

801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
    amqp_listener_thread.start()
    state['amqp_listener_thread'] = amqp_listener_thread


def _pre_configuration():
    global session_profile

    for key, _ in session_profile.items():
        if key in profile_choices.keys():
            selection_type = click.Choice(profile_choices[key])
        else:
            selection_type = str

        value = click.prompt('Please type %s ' % key,
                             type=selection_type,
                             default=session_profile[key])
        _echo_input(value)
        session_profile.update({key: value})


def _add_to_ignore_message_list(msg_type):
    global MESSAGE_TYPES_NOT_ECHOED
    if msg_type.__name__ in globals():
        MESSAGE_TYPES_NOT_ECHOED.append(msg_type)


def _message_handler(msg):
    global state
    """
    This method first prints message into user interface then evaluates if there's any associated action to message.
    :param msg:
    :return:
    """

    if type(msg) in MESSAGE_TYPES_NOT_ECHOED:
        pass  # do not echo
    else:
        # echo
        _echo_dispatcher(msg)

    # process message
    if isinstance(msg, Message):
        state['last_message'] = msg
        if type(msg) in UI_suggested_actions:
            state['suggested_cmd'] = UI_suggested_actions[type(msg)]
            _echo_session_helper(
                'Suggested following action to execute: <action %s> or or <action suggested>' % state['suggested_cmd'])

    elif isinstance(msg, MsgTestCaseVerdict):
        #  Save verdict
        json_file = os.path.join(
            TEMP_DIR,
            msg.testcase_id + '_verdict.json'
        )
        with open(json_file, 'w') as f:
            f.write(msg.to_json())

    elif isinstance(msg, (MsgStepStimuliExecute, MsgStepVerifyExecute)):
        state['step_id'] = msg.step_id

    elif isinstance(msg, MsgTestCaseReady):
        state['testcase_id'] = msg.testcase_id


def _exit():
    _quit_callback()

    if 'amqp_listener_thread' in state and state['amqp_listener_thread'] is not None:
        state['amqp_listener_thread'].stop()
        state['amqp_listener_thread'].join()

    if 'connection' in state and state['connection'] is not None:
        state['connection'].close()

    raise ExitReplException()


Federico Sismondi's avatar
Federico Sismondi committed
878 879 880
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# UI echo functions

881 882 883
def _echo_welcome_message():
    m = """
    Welcome to F-Interop platform!
Federico Sismondi's avatar
Federico Sismondi committed
884 885 886 887 888 889
    The Test assistant will help you go through the interoperability session (messages in cyan).

    """
    _echo_session_helper(m)

    m = """
890 891 892 893
    *************************************************************************************
    *   If you experience any problems, or you have any suggestions or feedback         *
    *   don't hesitate to drop me an email at:  federico[dot]sismondi[at]gmail[dot]com  *
    *************************************************************************************
894 895 896 897 898 899 900 901 902 903 904 905 906 907
    """
    _echo_session_helper(m)


def _echo_dispatcher(msg):
    """
    :param msg: String, dict or Message object
    :return: echoes using click API
    """

    if type(msg) is str:
        click.echo(click.style(msg, fg=COLOR_DEFAULT))
    elif isinstance(msg, MsgSessionLog):
        _echo_log_message(msg)
Federico Sismondi's avatar
Federico Sismondi committed
908 909
    elif isinstance(msg, MsgPacketSniffedRaw):
        _echo_data_message(msg)
910 911
    elif isinstance(msg, MsgSessionChat):
        _echo_chat_message(msg)
912 913 914
    elif isinstance(msg, MsgSessionConfiguration):
        # fixme hanlde extremly long fields in a more generic way
        msg.configuration = ['...ommited fields...']  # this fields is normally monstrously big
915 916 917
        _echo_backend_message(msg)
    elif isinstance(msg, dict):
        click.echo(click.style(repr(msg), fg=COLOR_DEFAULT))
918 919 920 921 922 923
    elif isinstance(msg, (MsgUiDisplay, MsgUiDisplayMarkdownText, MsgUiRequestConfirmationButton)):
        _echo_gui_message(msg)

    # default echo for objects of Message type
    elif isinstance(msg, Message):
        _echo_backend_message(msg)
924 925 926 927 928 929 930 931 932 933 934 935
    else:
        click.echo(click.style(msg, fg=COLOR_DEFAULT))


def _quit_callback():
    click.echo(click.style('Quitting!', fg=COLOR_ERROR_MESSAGE))


def _echo_backend_message(msg):
    assert isinstance(msg, Message)

    try:
936
        m = "\n[Event bus message] [%s] " % type(msg)
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
        if hasattr(m, 'description'):
            m += m.description

        click.echo(click.style(m, fg=COLOR_TEST_SESSION_HELPER_MESSAGE))

    except AttributeError as err:
        _echo_error(err)

    if isinstance(msg, MsgTestCaseReady):
        pass

    elif isinstance(msg, MsgDissectionAutoDissect):
        _echo_frames_as_table(msg.frames)
        return

    elif isinstance(msg, MsgTestCaseVerdict):
953 954 955 956 957 958 959
        verdict = msg.to_dict()
        partial_verdict = verdict.pop('partial_verdicts')

        _echo_dict_as_table(verdict)
        click.echo()

        if partial_verdict:
960 961 962 963 964
            click.echo(click.style("Partial verdicts:", fg=COLOR_TEST_SESSION_HELPER_MESSAGE))
            _echo_testcase_partial_verdicts_as_table(msg.partial_verdicts)
        return

    elif isinstance(msg, MsgTestSuiteReport):
965
        _echo_report_as_table(msg.tc_results)
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
        return

    elif isinstance(msg, MsgTestingToolComponentReady):
        pass

    elif isinstance(msg, MsgTestingToolComponentShutdown):
        pass

    _echo_dict_as_table(msg.to_dict())


def _echo_testcase_partial_verdicts_as_table(pvs):
    assert type(pvs) is list

    table = []
    table.append(('Step ID', 'Partial verdict', 'Description'))
    for item in pvs:
        try:
            assert type(item) is list
            cell_1 = item.pop(0)
            cell_2 = item.pop(0)
            cell_3 = list_to_str(item)
            table.append((cell_1, cell_2, cell_3))
        except Exception as e:

            _echo_error(e)
            _echo_error(traceback.format_exc())

    click.echo(click.style(tabulate(table, headers="firstrow"), fg=COLOR_TEST_SESSION_HELPER_MESSAGE))

Federico Sismondi's avatar
Federico Sismondi committed
996

Federico Sismondi's avatar
Federico Sismondi committed
997 998 999 1000
def _echo_list_of_dicts_as_table(l):
    try:

        assert type(l) is list
1001

Federico Sismondi's avatar
Federico Sismondi committed
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
        table = []
        first = True

        for d in l:  # for each dict obj in the list
            if d:
                if first:  # adds table header , we assume all dicts have same keys
                    first = False
                    table.append(tuple(d.keys()))
                table.append(tuple(d.values()))

1012
        _echo_list_as_table(table, first_row_is_header=True)
1013

Federico Sismondi's avatar
Federico Sismondi committed
1014 1015
    except Exception as e:
        _echo_error('wrong frame format passed?')
Federico Sismondi's avatar
Federico Sismondi committed
1016 1017
        if l:
            _echo_error(l)
Federico Sismondi's avatar
Federico Sismondi committed
1018 1019
        _echo_error(e)
        _echo_error(traceback.format_exc())
1020

Federico Sismondi's avatar
Federico Sismondi committed
1021

1022
def _echo_report_as_table(tc_report_list):
1023 1024
    try:

1025
        assert type(tc_report_list) is list
1026

1027
        # testcases = [(k, v) for k, v in report_dict.items() if k.lower().startswith('td')]
1028
        testcases = tc_report_list
1029

1030
        for tc_report in testcases:
1031
            table = []
1032 1033
            table.append(("Testcase ID", 'Final verdict', 'Description'))

1034 1035 1036 1037 1038
            tc_id = tc_report['testcase_id'] if 'testcase_id' in tc_report else '???'
            verd = tc_report['verdict'] if 'verdict' in tc_report else '???'
            desc = tc_report['description'] if 'description' in tc_report else '???'

            table.append((tc_id, verd, desc))
1039 1040 1041
            # testcase report
            click.echo()
            click.echo(click.style(tabulate(table, headers="firstrow"), fg=COLOR_TEST_SESSION_HELPER_MESSAGE))
1042 1043 1044
            if 'partial_verdicts' in tc_report:
                click.echo()
                _echo_testcase_partial_verdicts_as_table(tc_report['partial_verdicts'])
1045
            click.echo()
1046 1047 1048 1049 1050

    except Exception as e:
        _echo_error('wrong frame format passed?')
        _echo_error(e)
        _echo_error(traceback.format_exc())
1051
        _echo_error(json.dumps(tc_report_list))
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085


def _echo_frames_as_table(frames: list):
    assert type(frames) is list

    try:
        for frame in frames:
            table = []
            assert type(frame) is dict
            table.append(('frame id', frame['id']))
            table.append(('frame timestamp', frame['timestamp']))
            table.append(('frame error', frame['error']))

            # frame header print
            click.echo()  # new line
            click.echo(click.style(tabulate(table), fg=COLOR_TEST_SESSION_HELPER_MESSAGE))

            # print one table per layer
            for layer_as_dict in frame['protocol_stack']:
                assert type(layer_as_dict) is dict
                table = []
                for key, value in layer_as_dict.items():
                    temp = [key, value]
                    table.append(temp)
                click.echo(click.style(tabulate(table), fg=COLOR_TEST_SESSION_HELPER_MESSAGE))

            click.echo()  # new line

    except Exception as e:
        _echo_error('wrong frame format passed?')
        _echo_error(e)
        _echo_error(traceback.format_exc())


Federico Sismondi's avatar
Federico Sismondi committed
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
def _echo_list_as_table(ls: list, first_row_is_header=False):
    list_flat_items = []
    assert type(ls) is list

    for row in ls:
        assert type(row) is not str
        list_flat_items.append(tuple(list_to_str(item) for item in row))

    if first_row_is_header:
        click.echo(click.style(tabulate(list_flat_items, headers="firstrow"), fg=COLOR_TEST_SESSION_HELPER_MESSAGE))
    else:
        click.echo(click.style(tabulate(list_flat_items), fg=COLOR_TEST_SESSION_HELPER_MESSAGE))

Federico Sismondi's avatar
Federico Sismondi committed
1099
    click.echo()  # new line
1100 1101 1102 1103 1104


def _echo_dict_as_table(d: dict):
    table = []
    for key, value in d.items():
Federico Sismondi's avatar
Federico Sismondi committed
1105 1106 1107 1108
        if type(value) is list:
            temp = [key, list_to_str(value)]
        else:
            temp = [key, value]
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
        table.append(temp)

    click.echo()  # new line
    click.echo(click.style(tabulate(table), fg=COLOR_TEST_SESSION_HELPER_MESSAGE))


def _echo_session_helper(msg: str):
    click.echo(click.style('[Test Assistant] %s' % msg, fg=COLOR_SESSION_ASSISTANCE))


def _echo_input(msg):
    click.echo(click.style('[User input] %s' % msg, fg=COLOR_DEFAULT))


def _echo_error(msg):
    click.echo(click.style('[Error] %s' % msg, fg=COLOR_ERROR_MESSAGE))


def _echo_chat_message(msg: MsgSessionChat):
    if msg.iut_node == session_profile['node']:  # it's echo message
        click.echo(click.style('[Chat message sent] %s' % list_to_str(msg.description), fg=COLOR_CHAT_MESSAGE_ECHO))
    else:
        click.echo(click.style('[Chat message from %s] %s' % (msg.user_name, list_to_str(msg.description)),
                               fg=COLOR_CHAT_MESSAGE))


Federico Sismondi's avatar
Federico Sismondi committed
1135 1136 1137 1138 1139 1140 1141 1142
def _echo_data_message(msg):
    assert isinstance(msg, (MsgPacketInjectRaw, MsgPacketSniffedRaw))
    click.echo(click.style(
        '[agent] Packet captured on %s. Routing key: %s' % (msg.interface_name, msg.routing_key),
        fg=COLOR_SESSION_LOG)
    )


1143 1144
def _echo_gui_message(msg):
    click.echo(
1145 1146 1147 1148 1149 1150
        click.style("[UI message]\n\tMessage: %s \n\ttags: %s\n\tFields: %s \n\tR_key: %s \n\tcorr_id: %s" %
                    (
                        repr(msg)[:70],
                        str(msg.tags),
                        str(msg.fields)[:70],
                        msg.routing_key,
1151
                        msg.correlation_id if hasattr(msg, 'correlation_id') else ''
1152 1153
                    ),
                    fg=COLOR_SESSION_LOG))
1154 1155


1156 1157
def _echo_log_message(msg):
    if isinstance(msg, MsgSessionLog):
Federico Sismondi's avatar
Federico Sismondi committed
1158
        click.echo(click.style("[log][%s] %s" % (msg.component, list_to_str(msg.message)), fg=COLOR_SESSION_LOG))
1159
    else:
Federico Sismondi's avatar
Federico Sismondi committed
1160
        click.echo(click.style("[%s] %s" % ('log', list_to_str(msg)), fg=COLOR_SESSION_LOG))
1161

1162

1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# some auxiliary functions


def list_to_str(ls):
    """
    flattens a nested list up to two levels of depth

    :param ls: the list, supports str also
    :return: single string with all the items inside the list
    """

    ret = ''

Federico Sismondi's avatar
Federico Sismondi committed
1177 1178 1179
    if ls is None:
        return 'None'

1180 1181 1182
    if type(ls) is str:
        return ls

1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
    try:
        for l in ls:
            if l and isinstance(l, list):
                for sub_l in l:
                    if sub_l and not isinstance(sub_l, list):
                        ret += str(sub_l) + ' \n '
                    else:
                        # I truncate in the second level
                        pass
            else:
                ret += str(l) + ' \n '

    except TypeError as e:
        _echo_error(e)
        return str(ls)

1199 1200 1201
    return ret


1202
def _save_file_from_base64(filename, base64_encoded_file, dir=None):
1203 1204 1205 1206
    """
    Returns number of bytes saved.

    :param filename:
1207
    :param base64_encoded_file:
1208 1209 1210 1211 1212 1213 1214 1215 1216
    :return:
    """

    if dir:
        file_path = os.path.join(dir, filename)
    else:
        file_path = os.path.join(os.getcwd(), filename)

    with open(file_path, "wb") as pcap_file:
1217
        nb = pcap_file.write(base64.b64decode(base64_encoded_file))
1218 1219 1220
        return nb


1221
# # # AMQP connection, channel, publish and requests/replies handling # # #
1222

1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
def _amqp_request(request_message, component_id=COMPONENT_ID, timeout=10):
    TIME_WAIT_BETWEEN_POLLS = 0.5
    state_lock.acquire()

    if not _connection_ok():
        _echo_dispatcher('No connection established yet, setting up one..')
        _set_up_connection(create_listener=False)

    channel = state['channel']
    amqp_exchange = session_profile['amqp_exchange']

    # check first that sender didnt forget about reply to and corr id
    assert request_message.reply_to
    assert request_message.correlation_id

    if amqp_exchange is None:
        amqp_exchange = 'amq.topic'

    response = None

    reply_queue_name = 'amqp_rpc_%s@%s' % (str(uuid.uuid4())[:8], component_id)
1244 1245

    try:
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280

        result = channel.queue_declare(queue=reply_queue_name, auto_delete=True)

        callback_queue = result.method.queue

        # bind and listen to reply_to topic
        channel.queue_bind(
            exchange=amqp_exchange,
            queue=callback_queue,
            routing_key=request_message.reply_to
        )

        channel.basic_publish(
            exchange=amqp_exchange,
            routing_key=request_message.routing_key,
            properties=pika.BasicProperties(**request_message.get_properties()),
            body=request_message.to_json(),
        )

        retries_left = int(timeout / TIME_WAIT_BETWEEN_POLLS)

        while retries_left > 0:
            time.sleep(TIME_WAIT_BETWEEN_POLLS)
            method, props, body = channel.basic_get(reply_queue_name)
            if method:
                channel.basic_ack(method.delivery_tag)
                if hasattr(props, 'correlation_id') and props.correlation_id == request_message.correlation_id:
                    break
            retries_left -= 1

        if retries_left > 0:

            body_dict = json.loads(body.decode('utf-8'), object_pairs_hook=OrderedDict)
            response = MsgReply(request_message, **body_dict)

1281
        else:
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
            raise Exception(
                "Response timeout! rkey: %s , request type: %s" % (
                    request_message.routing_key,
                    type(request_message)
                )
            )

    finally:
        # clean up
        channel.queue_delete(reply_queue_name)
        state_lock.release()

    return response
1295

1296

1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
def _publish_message(message):
    if not _connection_ok():
        _echo_dispatcher('No connection established yet, setting up one..')
        _set_up_connection(create_listener=False)

    _echo_dispatcher('Sending message..')

    for i in range(1, 4):
        try:
            state_lock.acquire()
            channel = state['connection'].channel()
            channel.basic_publish(
                exchange=session_profile['amqp_exchange'],
                routing_key=message.routing_key,
                properties=pika.BasicProperties(**message.get_properties()),
                body=message.to_json(),
            )
            channel.close()
            break

        except pika.exceptions.ConnectionClosed as err:
            _echo_error(err)
            _echo_error('Unexpected connection closed, retrying %s/%s' % (i, 4))
            _set_up_connection()

        finally:
            state_lock.acquire()
Federico Sismondi's avatar
Federico Sismondi committed
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354


def main():
    try:
        session_profile.update({'amqp_exchange': str(os.environ['AMQP_EXCHANGE'])})
    except KeyError as e:
        pass  # use default

    try:
        env_url = str(os.environ['AMQP_URL'])
        if 'heartbeat_interval' not in env_url:
            url = '%s?%s&%s&%s&%s&%s' % (
                env_url,
                "heartbeat_interval=600",
                "blocked_connection_timeout=300",
                "retry_delay=1",
                "socket_timeout=1",
                "connection_attempts=3"
            )
        else:
            url = env_url

        session_profile.update({'amqp_url': url})
    except KeyError as e:
        pass  # use default

    try:
        cli()
    except ExitReplException:
        print('Bye!')
        sys.exit(0)