ioppytest_cli.py 40.1 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 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
    # TODO group cmds
    @cli.command()
    @click.option('-s', '--step-id', default='TD_COAP_CORE_01_step_01', help="step id of the STIMULI")
    @click.option('-ta', '--target-address', default=None, help="taget address")
    @click.option('-n', '--node', default='coap_client', help="Node id (related to the IUT role)")
    def _execute_stimuli_step(step_id, target_address, node):
        """
        Stimuli to be executed by IUT1, targeting IUT2
        """
        _echo_input("Executing debug message %s" % sys._getframe().f_code.co_name)
        msg = MsgStepStimuliExecute(
            node=node,
            step_id=step_id,
            target_address=target_address,
            description="",
            step_type="stimuli",
            step_info=[""],
            testcase_id="",
            testcase_ref="",

        )
        _publish_message(msg)

487 488
    # TODO group cmds
    @cli.command()
489
    @click.option('-tc', '--testcase-id', default=None, help="testcase id")
490
    def _sniffer_start(testcase_id):
491 492 493
        """
        Sniffer start
        """
494 495 496 497 498 499 500
        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')
501
        _publish_message(msg)
502 503

    @cli.command()
504
    def _sniffer_stop():
505 506 507
        """
        Sniffer stop
        """
508 509
        _echo_input("Executing debug message %s" % sys._getframe().f_code.co_name)
        msg = MsgSniffingStop()
510
        _publish_message(msg)
511 512

    @cli.command()
513
    def _sniffer_get_last_capture():
514 515 516
        """
        Sniffer get last capture
        """
517 518
        _echo_input("Executing debug message %s" % sys._getframe().f_code.co_name)
        msg = MsgSniffingGetCaptureLast()
519
        _publish_message(msg)
520

521 522 523 524 525
    @cli.command()
    def _configure_perf_tt():
        """
        Send example configuration message for perf TT
        """
526 527 528
        _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
529
        _publish_message(message)
530

531 532 533 534 535
    @cli.command()
    def _configure_comi_tt():
        """
        Send example configuration message for CoMI TT
        """
536 537 538
        _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
539
        _publish_message(message)
540

541 542 543 544 545 546 547 548
    @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
549
        _publish_message(message)
550

551 552 553 554 555 556 557 558
    @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)
559
        _publish_message(message)
560

561 562 563 564 565
    @cli.command()
    def _configure_coap_tt():
        """
        Send example configuration message for CoAP TT
        """
566 567 568
        _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
569
        _publish_message(message)
570

571 572 573 574 575
    @cli.command()
    def _get_session_configuration_from_ui():
        """
        Get session config from UI
        """
576 577
        _echo_input("Executing debug message %s" % sys._getframe().f_code.co_name)
        req = MsgUiRequestSessionConfiguration()
578
        _publish_message(req)
579

580 581
    @cli.command()
    @click.argument('testcase_id')
582
    def _testcase_skip(testcase_id):
583
        """
584
        Skip a particular testcase
585
        """
586 587 588 589 590
        _echo_input("Executing debug message %s" % sys._getframe().f_code.co_name)

        msg = MsgTestCaseSkip(
            testcase_id=testcase_id
        )
591
        _publish_message(msg)
592 593 594

    @cli.command()
    @click.argument('text')
595
    def _ui_display_markdown_text(text):
596
        """
597
        Send message to GUI
598
        """
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
        _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

614
        _publish_message(msg)
615

616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
    @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
        }]

634
        _publish_message(msg)
635

636 637 638 639 640 641 642 643 644 645 646 647 648 649
    @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)
650
        _publish_message(msg)
651

652 653 654 655 656 657 658 659 660 661 662 663 664 665
    @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)
666
        _publish_message(msg)
667

668
    _echo_session_helper("Entering debugger context, added extra CMDs, please type --help for more info")
669 670


671 672 673 674
@cli.command()
@click.argument('message', nargs=-1)
def chat(message):
    """
675
    Send chat message, useful for user-to-user test sessions
676 677 678 679 680 681 682 683 684 685
    """

    m = ''

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

    c = MsgSessionChat(description=m,
                       user_name=session_profile['user_name'],
                       iut_node=session_profile['node'])
686
    _publish_message(c)
687 688 689 690 691


@cli.command()
def check_connection():
    """
Federico Sismondi's avatar
Federico Sismondi committed
692
    (REPL only) Check if AMQP connection is active
693 694 695 696 697
    """
    conn_ok = _connection_ok()
    _echo_dispatcher('connection is %s' % 'OK' if conn_ok else 'not OK')
    return conn_ok

698

699 700 701 702 703 704 705 706 707 708 709
@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:
710
            status_resp = _amqp_request(request_message, COMPONENT_ID)
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
        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')

735 736

@cli.command()
737
def get_session_parameters():
738 739 740 741 742 743 744 745 746 747
    """
    Print session state and parameters
    """

    _echo_context()


def _connection_ok():
    conn_ok = False
    try:
748
        conn_ok = state['connection'] is not None and state['connection'].is_open
749 750 751 752 753 754 755 756 757 758
    except AttributeError as ae:
        pass
    except TypeError as ae:
        pass

    return conn_ok


def _echo_context():
    table = []
759 760 761 762 763
    d = {}
    d.update(session_profile)
    d.update(state)
    for key, val in d.items():
        table.append((key, list_to_str(str(val))))
764 765 766
    _echo_list_as_table(table)


767
def _set_up_connection(create_listener=True, lazy_listener=False):
768 769
    # conn for repl publisher
    try:
Federico Sismondi's avatar
Federico Sismondi committed
770
        retries_left = CONNECTION_SETUP_RETRIES
771
        state_lock.acquire()
Federico Sismondi's avatar
Federico Sismondi committed
772 773
        while retries_left > 0:
            try:
774

Federico Sismondi's avatar
Federico Sismondi committed
775 776 777 778 779
                state['connection'] = pika.BlockingConnection(pika.URLParameters(session_profile['amqp_url']))
                state['channel'] = state['connection'].channel()
                break
            except pika.exceptions.ConnectionClosed:
                retries_left -= 1
780 781
                _echo_session_helper("Couldnt establish connection, retrying .. %s/%s " % (
                    CONNECTION_SETUP_RETRIES - retries_left, CONNECTION_SETUP_RETRIES))
Federico Sismondi's avatar
Federico Sismondi committed
782

783 784 785 786 787 788
    except pika.exceptions.ProbableAccessDeniedError:
        _echo_error('Probable access denied error. Is provided AMQP_URL correct?')
        state['connection'] = None
        state['channel'] = None
        return

789 790 791
    finally:
        state_lock.release()

792 793 794 795 796 797 798 799 800 801
    # 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()

802 803 804 805 806
    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

807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
    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
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 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
    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
901 902 903
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# UI echo functions

904 905 906
def _echo_welcome_message():
    m = """
    Welcome to F-Interop platform!
Federico Sismondi's avatar
Federico Sismondi committed
907 908 909 910 911 912
    The Test assistant will help you go through the interoperability session (messages in cyan).

    """
    _echo_session_helper(m)

    m = """
913 914 915 916
    *************************************************************************************
    *   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  *
    *************************************************************************************
917 918 919 920 921 922 923 924 925 926 927 928 929 930
    """
    _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
931 932
    elif isinstance(msg, MsgPacketSniffedRaw):
        _echo_data_message(msg)
933 934
    elif isinstance(msg, MsgSessionChat):
        _echo_chat_message(msg)
935 936 937
    elif isinstance(msg, MsgSessionConfiguration):
        # fixme hanlde extremly long fields in a more generic way
        msg.configuration = ['...ommited fields...']  # this fields is normally monstrously big
938 939 940
        _echo_backend_message(msg)
    elif isinstance(msg, dict):
        click.echo(click.style(repr(msg), fg=COLOR_DEFAULT))
941 942 943 944 945 946
    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)
947 948 949 950 951 952 953 954 955 956 957 958
    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:
959
        m = "\n[Event bus message] [%s] " % type(msg)
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
        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):
976 977 978 979 980 981 982
        verdict = msg.to_dict()
        partial_verdict = verdict.pop('partial_verdicts')

        _echo_dict_as_table(verdict)
        click.echo()

        if partial_verdict:
983 984 985 986 987
            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):
988
        _echo_report_as_table(msg.tc_results)
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
        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
1019

Federico Sismondi's avatar
Federico Sismondi committed
1020 1021 1022 1023
def _echo_list_of_dicts_as_table(l):
    try:

        assert type(l) is list
1024

Federico Sismondi's avatar
Federico Sismondi committed
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
        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()))

1035
        _echo_list_as_table(table, first_row_is_header=True)
1036

Federico Sismondi's avatar
Federico Sismondi committed
1037 1038
    except Exception as e:
        _echo_error('wrong frame format passed?')
Federico Sismondi's avatar
Federico Sismondi committed
1039 1040
        if l:
            _echo_error(l)
Federico Sismondi's avatar
Federico Sismondi committed
1041 1042
        _echo_error(e)
        _echo_error(traceback.format_exc())
1043

Federico Sismondi's avatar
Federico Sismondi committed
1044

1045
def _echo_report_as_table(tc_report_list):
1046 1047
    try:

1048
        assert type(tc_report_list) is list
1049

1050
        # testcases = [(k, v) for k, v in report_dict.items() if k.lower().startswith('td')]
1051
        testcases = tc_report_list
1052

1053
        for tc_report in testcases:
1054
            table = []
1055 1056
            table.append(("Testcase ID", 'Final verdict', 'Description'))

1057 1058 1059 1060 1061
            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))
1062 1063 1064
            # testcase report
            click.echo()
            click.echo(click.style(tabulate(table, headers="firstrow"), fg=COLOR_TEST_SESSION_HELPER_MESSAGE))
1065 1066 1067
            if 'partial_verdicts' in tc_report:
                click.echo()
                _echo_testcase_partial_verdicts_as_table(tc_report['partial_verdicts'])
1068
            click.echo()
1069 1070 1071 1072 1073

    except Exception as e:
        _echo_error('wrong frame format passed?')
        _echo_error(e)
        _echo_error(traceback.format_exc())
1074
        _echo_error(json.dumps(tc_report_list))
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108


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
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
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
1122
    click.echo()  # new line
1123 1124 1125 1126 1127


def _echo_dict_as_table(d: dict):
    table = []
    for key, value in d.items():
Federico Sismondi's avatar
Federico Sismondi committed
1128 1129 1130 1131
        if type(value) is list:
            temp = [key, list_to_str(value)]
        else:
            temp = [key, value]
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
        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
1158 1159 1160 1161 1162 1163 1164 1165
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)
    )


1166 1167
def _echo_gui_message(msg):
    click.echo(
1168 1169 1170 1171 1172 1173
        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,
1174
                        msg.correlation_id if hasattr(msg, 'correlation_id') else ''
1175 1176
                    ),
                    fg=COLOR_SESSION_LOG))
1177 1178


1179 1180
def _echo_log_message(msg):
    if isinstance(msg, MsgSessionLog):
Federico Sismondi's avatar
Federico Sismondi committed
1181
        click.echo(click.style("[log][%s] %s" % (msg.component, list_to_str(msg.message)), fg=COLOR_SESSION_LOG))
1182
    else:
Federico Sismondi's avatar
Federico Sismondi committed
1183
        click.echo(click.style("[%s] %s" % ('log', list_to_str(msg)), fg=COLOR_SESSION_LOG))
1184

1185

1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# 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
1200 1201 1202
    if ls is None:
        return 'None'

1203 1204 1205
    if type(ls) is str:
        return ls

1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
    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)

1222 1223 1224
    return ret


1225
def _save_file_from_base64(filename, base64_encoded_file, dir=None):
1226 1227 1228 1229
    """
    Returns number of bytes saved.

    :param filename:
1230
    :param base64_encoded_file:
1231 1232 1233 1234 1235 1236 1237 1238 1239
    :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:
1240
        nb = pcap_file.write(base64.b64decode(base64_encoded_file))
1241 1242 1243
        return nb


1244
# # # AMQP connection, channel, publish and requests/replies handling # # #
1245

1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
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)
1267 1268

    try:
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303

        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)

1304
        else:
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
            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
1318

1319

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
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
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377


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)