ioppytest_cli.py 46.2 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
import logging
8
import datetime
9 10
import threading
import traceback
11

12
from collections import OrderedDict
13

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

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

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

31 32 33
COMPONENT_ID = 'ioppytest-cli'

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

35 36 37 38 39 40 41 42 43 44
# 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'

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

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

MESSAGE_TYPES_NOT_ECHOED = [
]

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

58 59 60 61 62 63 64 65 66 67
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",
    }
)

68
state_lock = threading.RLock()
69 70 71 72 73 74 75 76 77
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
78 79
    'protocol': ['coap', '6lowpan', 'onem2m'],
    'node': ['coap_client', 'coap_server']
80 81
}

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


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


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


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

    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

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

    _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)


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


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

    """
    _exit()

154

155 156 157 158 159 160 161 162 163 164 165 166 167 168
@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)
169
            response = _amqp_request(msg, COMPONENT_ID)
170 171

            if response.ok:
172
                _save_file_from_base64(response.filename, response.value, TEMP_DIR)
173 174 175 176 177 178 179 180
                _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)

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
        msg_request.reply_to = "ui.user.{}.reply".format(user_id)
204

Federico Sismondi's avatar
Federico Sismondi committed
205
    _echo_input("sending request to {}".format(msg_request.routing_key))
206 207 208 209 210 211 212 213 214 215
    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))


216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
@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_send_file_to_download(path_to_file, text_message, user_id):
    """
    Sends file to user's GUI. Useful for example to enable users to download reports, pcap files, etc..
    """
    global state

    msg_request = MsgUiSendFileToDownload()

    with open(path_to_file, "rb") as file:
        enc = base64.b64encode(file.read())

    msg_request.fields = [
        {
            "name": text_message,
            "type": "data",
            "value": enc.decode("utf-8"),
        }
    ]

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

    _echo_input("sending file to {}".format(msg_request.routing_key))
    _publish_message(msg_request)


Federico Sismondi's avatar
Federico Sismondi committed
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
@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))


271 272 273 274 275 276 277 278 279
@cli.command()
def clear():
    """
    Clear screen
    """

    click.clear()


Federico Sismondi's avatar
Federico Sismondi committed
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
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']
    )

302
    _publish_message(msg)
Federico Sismondi's avatar
Federico Sismondi committed
303 304 305


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

308
    request_message = MsgTestSuiteGetTestCases()
Federico Sismondi's avatar
Federico Sismondi committed
309

310 311 312 313 314 315
    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
316

317 318 319 320 321
    try:
        state['tc_list'] = testcases_list_reponse.tc_list
    except Exception as e:
        _echo_error(e)
        return
Federico Sismondi's avatar
Federico Sismondi committed
322

323
    _echo_list_of_dicts_as_table(state['tc_list'])
Federico Sismondi's avatar
Federico Sismondi committed
324

325

326 327 328
def _handle_action_testsuite_start():
    if click.confirm('Do you want START test suite?'):
        msg = MsgTestSuiteStart()
329
        _publish_message(msg)
330 331 332 333


def _handle_action_testcase_start():
    if click.confirm('Do you want START test case?'):
334
        msg = MsgTestCaseStart()  # TODO no testcase id input?
335
        _publish_message(msg)
336 337 338 339 340


def _handle_action_testsuite_abort():
    if click.confirm('Do you want ABORT test suite?'):
        msg = MsgTestSuiteAbort()
341
        _publish_message(msg)
342 343 344 345 346


def _handle_action_testcase_skip():
    if click.confirm('Do you want SKIP current test case?'):
        msg = MsgTestCaseSkip()
347
        _publish_message(msg)
348 349 350 351 352


def _handle_action_testcase_restart():
    if click.confirm('Do you want RESTART current test case?'):
        msg = MsgTestCaseRestart()
353
        _publish_message(msg)
354 355 356 357 358 359 360 361 362 363 364 365 366


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"
        )
367
        _publish_message(msg)
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385

    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"
    )

386
    _publish_message(msg)
387 388 389 390 391 392 393


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
394 395
                           'tc_list': _handle_get_testcase_list,
                           'tc_select': _handle_testcase_select,
396 397 398 399 400 401 402 403 404 405
                           '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):
    """
406
    Execute interop test action
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
    """

    _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)


429 430 431 432 433 434 435 436 437 438 439
ignorable_message_types = {
    'dissections': [MsgDissectionAutoDissect],
    'packets': [MsgPacketSniffedRaw, MsgPacketInjectRaw],
    'ui': [MsgUiRequestTextInput,
           MsgUiRequestConfirmationButton,
           MsgUiDisplay,
           MsgUiDisplayMarkdownText,
           MsgUiReply]
}


440
@cli.command()
441
@click.argument('message_type', type=click.Choice(list(ignorable_message_types.keys())))
442 443
def ignore(message_type):
    """
Federico Sismondi's avatar
Federico Sismondi committed
444
    (REPL only) Do not notify any more on message type
445
    """
446 447
    try:
        for item in ignorable_message_types[message_type]:
448 449
            _add_to_ignore_message_list(item)
            _echo_dispatcher('Ignore message category %s: (%s)' % (message_type, str(item)))
450 451 452
    except KeyError as ke:
        _echo_error('Couldnt add to ignored list..')
        _echo_error(ke)
453 454


455 456 457
@cli.command()
def enter_debug_context():
    """
Federico Sismondi's avatar
Federico Sismondi committed
458
    (REPL only) Provides user with some extra debugging commands
459 460 461 462

    """
    global message_handles_options

463 464 465 466 467 468 469 470 471 472 473 474
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    #  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))
475
            _publish_message(message_t)
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495

        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)
        # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
    @cli.command()
    def _results_store_insert_result():
        tc_results_example = [
            {'verdict': 'pass',
             'description': 'No interoperability error was detected.',
             'testcase_id': 'TD_COAP_CORE_01',
             'partial_verdicts': [
                 ['TD_COAP_CORE_01_step_02', None, 'CHECK step: postponed', ''],
                 ['TD_COAP_CORE_01_step_03', None, 'CHECK step: postponed', ''],
                 ['TD_COAP_CORE_01_step_04', 'pass',
                  'VERIFY step: User informed that the information was displayed correclty on his/her IUT',
                  ''],
                 ['tat_check_1', 'pass',
                  '<Frame   1: [bbbb::1 -> bbbb::2] CoAP [CON 861] GET /test> Match: CoAP(type=0, code=1)'],
                 ['tat_check_2', 'pass',
                  '<Frame   2: [bbbb::2 -> bbbb::1] CoAP [ACK 861] 2.05 Content > Match: CoAP(opt=Opt(CoAPOptionContentFormat()))']]},
            {'verdict': 'pass',
             'description': 'No interoperability error was detected.',
             'testcase_id': 'TD_COAP_CORE_02',
             'partial_verdicts': [
                 ['TD_COAP_CORE_02_step_02', None, 'CHECK step: postponed', ''],
                 ['TD_COAP_CORE_02_step_03', None, 'CHECK step: postponed', ''],
                 ['TD_COAP_CORE_02_step_04', 'pass',
                  'VERIFY step: User informed that the information was displayed correclty on his/her IUT', ''],
                 ['tat_check_1', 'pass',
                  '<Frame   1: [bbbb::1 -> bbbb::2] CoAP [CON 808] DELETE /test> Match: CoAP(type=0, code=4)'],
                 ['tat_check_2', 'pass',
                  "<Frame   2: [bbbb::2 -> bbbb::1] CoAP [ACK 808] 2.02 Deleted > Match: CoAP(code=66, mid=0x0328, tok=b'')"]]},
            {'verdict': 'None', 'description': 'Testcase TD_COAP_CORE_04 was skipped.',
             'testcase_id': 'TD_COAP_CORE_04', 'partial_verdicts': []},
        ]
        m = MsgInsertResultRequest(
            data=tc_results_example
        )
        _publish_message(m)

    @cli.command()
    def _results_store_get_result():
        m = MsgGetResultRequest(
        )
        _publish_message(m)

538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
    @cli.command()
    def _agent_serial_message_inject():
        data = [65, 216, 206, 205, 171, 255, 255, 156, 237, 51, 4, 0, 75, 18, 0, 65, 96, 0, 0, 0, 0, 6, 58, 64, 254,
                128, 0,
                0, 0, 0, 0, 0, 2, 18, 75, 0, 4, 51, 237, 156, 255, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 26, 155, 0,
                40,
                63, 0, 0]
        data_slip = [192, 65, 216, 206, 205, 171, 255, 255, 156, 237, 51, 4, 0, 75, 18, 0, 65, 96, 0, 0, 0, 0, 6, 58,
                     64,
                     254, 128, 0, 0, 0, 0, 0, 0, 2, 18, 75, 0, 4, 51, 237, 156, 255, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                     0,
                     0, 26, 155, 0, 40, 63, 0, 0, 192]
        agent_name = click.prompt('enter agent name (e.g. eut2)', type=str)
        m = MsgPacketInjectRaw(
            timestamp=1488586183.45,
            interface_name='/dev/tun/uruguay_noma',
            data=data,
            data_slip=data_slip
        )
        m.routing_key = m.routing_key.replace('.*.ip.tun.', ".{}.{}.{}.".format(agent_name, '802154', 'serial'))
        _publish_message(m)

560 561 562 563 564 565 566 567 568
    # 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
        """
569
        _echo_session_helper("Executing test message function %s" % sys._getframe().f_code.co_name)
570 571 572 573 574 575 576 577 578 579 580 581 582
        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)

583 584 585 586 587 588 589
    @cli.command()
    @click.option('-s', '--step-id', default='TD_COAP_CORE_01_step_04', help="step id of the VERIFY")
    @click.option('-n', '--node', default='coap_client', help="Node id (related to the IUT role)")
    def _execute_verify_step(step_id, node):
        """
        Request IUT to verify a step, normally they respond with a dummy verify ok
        """
590
        _echo_session_helper("Executing test message function %s" % sys._getframe().f_code.co_name)
591 592 593 594 595 596 597 598 599 600 601 602
        msg = MsgStepVerifyExecute(
            node=node,
            step_id=step_id,
            description="",
            step_type="verify",
            step_info=[""],
            testcase_id="",
            testcase_ref="",

        )
        _publish_message(msg)

603
    @cli.command()
604
    @click.option('-tc', '--testcase-id', default=None, help="testcase id")
605
    def _sniffer_start(testcase_id):
606 607 608
        """
        Sniffer start
        """
609 610 611
        if testcase_id is None:
            testcase_id = 'PCAP_TEST'

612
        _echo_session_helper("Executing test message function %s" % sys._getframe().f_code.co_name)
613 614 615
        msg = MsgSniffingStart(capture_id=testcase_id,
                               filter_if='tun0',
                               filter_proto='udp')
616
        _publish_message(msg)
617 618

    @cli.command()
619
    def _sniffer_stop():
620 621 622
        """
        Sniffer stop
        """
623
        _echo_session_helper("Executing test message function %s" % sys._getframe().f_code.co_name)
624
        msg = MsgSniffingStop()
625
        _publish_message(msg)
626 627

    @cli.command()
628
    def _sniffer_get_last_capture():
629 630 631
        """
        Sniffer get last capture
        """
632
        _echo_session_helper("Executing test message function %s" % sys._getframe().f_code.co_name)
633
        msg = MsgSniffingGetCaptureLast()
634
        _publish_message(msg)
635

636 637 638 639 640
    @cli.command()
    def _configure_perf_tt():
        """
        Send example configuration message for perf TT
        """
641
        _echo_session_helper("Executing test message function %s" % sys._getframe().f_code.co_name)
642 643
        from message_examples import PERF_TT_CONFIGURATION
        message = MsgSessionConfiguration(**PERF_TT_CONFIGURATION)  # builds a config for the perf TT
644
        _publish_message(message)
645

646 647 648 649 650
    @cli.command()
    def _configure_comi_tt():
        """
        Send example configuration message for CoMI TT
        """
651
        _echo_session_helper("Executing test message function %s" % sys._getframe().f_code.co_name)
652 653
        from message_examples import COMI_TT_CONFIGURATION
        message = MsgSessionConfiguration(**COMI_TT_CONFIGURATION)  # builds a config message
654
        _publish_message(message)
655

656 657 658 659 660
    @cli.command()
    def _configure_6lowpan_tt():
        """
        Send example configuration message for SIXLOWPAN TT
        """
661
        _echo_session_helper("Executing test message function %s" % sys._getframe().f_code.co_name)
662 663
        from message_examples import SIXLOWPAN_TT_CONFIGURATION
        message = MsgSessionConfiguration(**SIXLOWPAN_TT_CONFIGURATION)  # builds a config message
664
        _publish_message(message)
665

666 667 668 669 670
    @cli.command()
    def _test_tat_analyze_6lowpan():
        """
        Send example 6lowpan tat analysis request
        """
671
        _echo_session_helper("Executing test message function %s" % sys._getframe().f_code.co_name)
672 673
        from message_examples import SIXLOWPAN_TAT_ANALYZE
        message = MsgInteropTestCaseAnalyze(**SIXLOWPAN_TAT_ANALYZE)
674
        _publish_message(message)
675

676 677 678 679 680
    @cli.command()
    def _configure_coap_tt():
        """
        Send example configuration message for CoAP TT
        """
681
        _echo_session_helper("Executing test message function %s" % sys._getframe().f_code.co_name)
682 683
        from message_examples import COAP_TT_CONFIGURATION
        message = MsgSessionConfiguration(**COAP_TT_CONFIGURATION)  # builds a config message
684
        _publish_message(message)
685

686 687 688 689 690
    @cli.command()
    def _get_session_configuration_from_ui():
        """
        Get session config from UI
        """
691
        _echo_session_helper("Executing test message function %s" % sys._getframe().f_code.co_name)
692
        req = MsgUiRequestSessionConfiguration()
693
        _publish_message(req)
694

695 696
    @cli.command()
    @click.argument('testcase_id')
697
    def _testcase_skip(testcase_id):
698
        """
699
        Skip a particular testcase
700
        """
701
        _echo_session_helper("Executing test message function %s" % sys._getframe().f_code.co_name)
702 703 704 705

        msg = MsgTestCaseSkip(
            testcase_id=testcase_id
        )
706
        _publish_message(msg)
707 708 709

    @cli.command()
    @click.argument('text')
710
    def _ui_display_markdown_text(text):
711
        """
712
        Send message to GUI
713
        """
714
        _echo_session_helper("Executing test message function %s" % sys._getframe().f_code.co_name)
715 716 717 718 719 720 721 722 723 724 725 726 727 728

        msg = MsgUiDisplayMarkdownText()

        _echo_input(text)

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

729
        _publish_message(msg)
730

731 732 733 734 735 736
    @cli.command()
    @click.argument('text')
    def _ui_send_confirmation_button(text):
        """
        Send button to GUI
        """
737
        _echo_session_helper("Executing test message function %s" % sys._getframe().f_code.co_name)
738 739 740 741 742 743 744 745 746 747 748

        msg = MsgUiRequestConfirmationButton()

        _echo_input(text)

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

749
        _publish_message(msg)
750

751 752 753 754 755 756
    @cli.command()
    @click.argument('text')
    def _ui_send_confirmation_button(text):
        """
        Send button to GUI
        """
757
        _echo_session_helper("Executing test message function %s" % sys._getframe().f_code.co_name)
758 759 760 761 762 763 764

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

        _echo_input(text)
765
        _publish_message(msg)
766

767 768 769 770 771 772
    @cli.command()
    @click.argument('text')
    def _ui_send_confirmation_button(text):
        """
        Send button to GUI
        """
773
        _echo_session_helper("Executing test message function %s" % sys._getframe().f_code.co_name)
774 775 776 777 778 779 780

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

        _echo_input(text)
781
        _publish_message(msg)
782

783
    _echo_session_helper("Entering debugger context, added extra CMDs, please type --help for more info")
784 785


786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
@cli.command()
@click.option('--target-host', default='bbbb::2', help="ICMPv6 destination address")
@click.option('--origin-node', default='coap_client', help="Origin Node id (related to the automated IUT role)")
def _test_automated_iut_reaches_another_other_implementation(target_host, origin_node):
    """
    Request automated IUT to send a ping request to a certain ip destination
    """
    _echo_session_helper("Executing test message function %s" % sys._getframe().f_code.co_name)
    msg = MsgAutomatedIutTestPing(
        node=origin_node,
        target_address=target_host

    )
    resp = _amqp_request(msg, COMPONENT_ID, 15)

    assert resp.ok, '%s cannot reach destination %s' % (origin_node, target_host)


804 805 806 807
@cli.command()
@click.argument('message', nargs=-1)
def chat(message):
    """
808
    Send chat message, useful for user-to-user test sessions
809 810 811 812 813 814 815 816 817 818
    """

    m = ''

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

    c = MsgSessionChat(description=m,
                       user_name=session_profile['user_name'],
                       iut_node=session_profile['node'])
819
    _publish_message(c)
820 821 822 823 824


@cli.command()
def check_connection():
    """
Federico Sismondi's avatar
Federico Sismondi committed
825
    (REPL only) Check if AMQP connection is active
826 827 828 829 830
    """
    conn_ok = _connection_ok()
    _echo_dispatcher('connection is %s' % 'OK' if conn_ok else 'not OK')
    return conn_ok

831

832 833 834 835 836 837 838 839 840 841 842
@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:
843
            status_resp = _amqp_request(request_message, COMPONENT_ID)
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
        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')

868 869

@cli.command()
870
def get_session_parameters():
871 872 873 874 875 876 877 878 879 880
    """
    Print session state and parameters
    """

    _echo_context()


def _connection_ok():
    conn_ok = False
    try:
881
        conn_ok = state['connection'] is not None and state['connection'].is_open
882 883 884 885 886 887 888 889 890 891
    except AttributeError as ae:
        pass
    except TypeError as ae:
        pass

    return conn_ok


def _echo_context():
    table = []
892 893 894 895 896
    d = {}
    d.update(session_profile)
    d.update(state)
    for key, val in d.items():
        table.append((key, list_to_str(str(val))))
897 898 899
    _echo_list_as_table(table)


900
def _set_up_connection(create_listener=True, lazy_listener=False):
901 902
    # conn for repl publisher
    try:
Federico Sismondi's avatar
Federico Sismondi committed
903
        retries_left = CONNECTION_SETUP_RETRIES
904
        state_lock.acquire()
Federico Sismondi's avatar
Federico Sismondi committed
905 906
        while retries_left > 0:
            try:
907
                _echo_session_helper("Connecting to %s" % session_profile['amqp_url'])
908

Federico Sismondi's avatar
Federico Sismondi committed
909 910 911 912 913
                state['connection'] = pika.BlockingConnection(pika.URLParameters(session_profile['amqp_url']))
                state['channel'] = state['connection'].channel()
                break
            except pika.exceptions.ConnectionClosed:
                retries_left -= 1
914 915
                _echo_session_helper("Couldnt establish connection, retrying .. %s/%s " % (
                    CONNECTION_SETUP_RETRIES - retries_left, CONNECTION_SETUP_RETRIES))
Federico Sismondi's avatar
Federico Sismondi committed
916

917 918 919 920 921 922
    except pika.exceptions.ProbableAccessDeniedError:
        _echo_error('Probable access denied error. Is provided AMQP_URL correct?')
        state['connection'] = None
        state['channel'] = None
        return

923 924 925
    finally:
        state_lock.release()

926 927 928 929 930 931 932 933 934 935
    # 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()

936 937 938 939 940
    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

941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
    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
957

958 959 960 961 962 963 964 965 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 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
    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
1035 1036 1037
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# UI echo functions

1038 1039 1040
def _echo_welcome_message():
    m = """
    Welcome to F-Interop platform!
Federico Sismondi's avatar
Federico Sismondi committed
1041 1042 1043 1044 1045 1046
    The Test assistant will help you go through the interoperability session (messages in cyan).

    """
    _echo_session_helper(m)

    m = """
1047 1048 1049 1050
    *************************************************************************************
    *   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  *
    *************************************************************************************
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
    """
    _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
1065 1066
    elif isinstance(msg, MsgPacketSniffedRaw):
        _echo_data_message(msg)
1067 1068
    elif isinstance(msg, MsgSessionChat):
        _echo_chat_message(msg)
1069 1070 1071
    elif isinstance(msg, MsgSessionConfiguration):
        # fixme hanlde extremly long fields in a more generic way
        msg.configuration = ['...ommited fields...']  # this fields is normally monstrously big
1072 1073 1074
        _echo_backend_message(msg)
    elif isinstance(msg, dict):
        click.echo(click.style(repr(msg), fg=COLOR_DEFAULT))
1075 1076 1077 1078 1079 1080
    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)
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
    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:
1093
        m = "\n[Event bus message] [%s] " % type(msg)
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
        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):
1110 1111 1112 1113 1114 1115 1116
        verdict = msg.to_dict()
        partial_verdict = verdict.pop('partial_verdicts')

        _echo_dict_as_table(verdict)
        click.echo()

        if partial_verdict:
1117 1118 1119 1120 1121
            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):
1122
        _echo_report_as_table(msg.tc_results)
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
        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
1153

Federico Sismondi's avatar
Federico Sismondi committed
1154 1155 1156 1157
def _echo_list_of_dicts_as_table(l):
    try:

        assert type(l) is list
1158

Federico Sismondi's avatar
Federico Sismondi committed
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
        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()))

1169
        _echo_list_as_table(table, first_row_is_header=True)
1170

Federico Sismondi's avatar
Federico Sismondi committed
1171 1172
    except Exception as e:
        _echo_error('wrong frame format passed?')
Federico Sismondi's avatar
Federico Sismondi committed
1173 1174
        if l:
            _echo_error(l)
Federico Sismondi's avatar
Federico Sismondi committed
1175 1176
        _echo_error(e)
        _echo_error(traceback.format_exc())
1177

Federico Sismondi's avatar
Federico Sismondi committed
1178

1179
def _echo_report_as_table(tc_report_list):
1180 1181
    try:

1182
        assert type(tc_report_list) is list
1183

1184
        # testcases = [(k, v) for k, v in report_dict.items() if k.lower().startswith('td')]
1185
        testcases = tc_report_list
1186

1187
        for tc_report in testcases:
1188
            table = []
1189 1190
            table.append(("Testcase ID", 'Final verdict', 'Description'))

1191 1192 1193 1194 1195
            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))
1196 1197 1198
            # testcase report
            click.echo()
            click.echo(click.style(tabulate(table, headers="firstrow"), fg=COLOR_TEST_SESSION_HELPER_MESSAGE))
1199 1200 1201
            if 'partial_verdicts' in tc_report:
                click.echo()
                _echo_testcase_partial_verdicts_as_table(tc_report['partial_verdicts'])
1202
            click.echo()
1203 1204 1205 1206 1207

    except Exception as e:
        _echo_error('wrong frame format passed?')
        _echo_error(e)
        _echo_error(traceback.format_exc())
1208
        _echo_error(json.dumps(tc_report_list))
1209 1210 1211 1212 1213 1214 1215 1216 1217


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

    try:
        for frame in frames:
            table = []
            assert type(frame) is dict
1218
            timestamp = datetime.datetime.fromtimestamp(int(frame['timestamp'])).strftime('%Y-%m-%d %H:%M:%S')
1219
            table.append(('frame id', frame['id']))
1220
            table.append(('frame timestamp', timestamp))
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
            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
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
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
1257
    click.echo()  # new line
1258 1259 1260 1261 1262


def _echo_dict_as_table(d: dict):
    table = []
    for key, value in d.items():
Federico Sismondi's avatar
Federico Sismondi committed
1263 1264 1265 1266
        if type(value) is list:
            temp = [key, list_to_str(value)]
        else:
            temp = [key, value]
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
        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
1293 1294 1295 1296 1297 1298 1299 1300
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)
    )


1301 1302
def _echo_gui_message(msg):
    click.echo(
1303 1304 1305 1306 1307 1308
        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,
1309
                        msg.correlation_id if hasattr(msg, 'correlation_id') else ''
1310 1311
                    ),
                    fg=COLOR_SESSION_LOG))
1312 1313


1314 1315
def _echo_log_message(msg):
    if isinstance(msg, MsgSessionLog):
Federico Sismondi's avatar
Federico Sismondi committed
1316
        click.echo(click.style("[log][%s] %s" % (msg.component, list_to_str(msg.message)), fg=COLOR_SESSION_LOG))
1317
    else:
Federico Sismondi's avatar
Federico Sismondi committed
1318
        click.echo(click.style("[%s] %s" % ('log', list_to_str(msg)), fg=COLOR_SESSION_LOG))
1319

1320

1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# 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
1335 1336 1337
    if ls is None:
        return 'None'

1338 1339 1340
    if type(ls) is str:
        return ls

1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
    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)

1357 1358 1359
    return ret


1360
def _save_file_from_base64(filename, base64_encoded_file, dir=None):
1361 1362 1363 1364
    """
    Returns number of bytes saved.

    :param filename:
1365
    :param base64_encoded_file:
1366 1367 1368 1369 1370 1371 1372 1373 1374
    :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:
1375
        nb = pcap_file.write(base64.b64decode(base64_encoded_file))
1376 1377 1378
        return nb


1379
# # # AMQP connection, channel, publish and requests/replies handling # # #
1380

1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
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)
1402 1403

    try:
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438

        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)

1439
        else:
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
            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
1453

1454

1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
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
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491


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'])
1492
        if 'heartbeat' not in env_url:
Federico Sismondi's avatar
Federico Sismondi committed
1493 1494
            url = '%s?%s&%s&%s&%s&%s' % (
                env_url,
1495
                "heartbeat=600",
Federico Sismondi's avatar
Federico Sismondi committed
1496 1497 1498 1499 1500