Commit 50c49d00 authored by Federico Sismondi's avatar Federico Sismondi

fixes for reply generation, added example on how to use syncrhonous rquest reply to UI

parent b5c67d81
...@@ -19,7 +19,6 @@ class AmqpSynchCallTimeoutError(Exception): ...@@ -19,7 +19,6 @@ class AmqpSynchCallTimeoutError(Exception):
class AmqpListener(threading.Thread): class AmqpListener(threading.Thread):
DEFAULT_TOPIC_SUSBCRIPTIONS = ['#'] DEFAULT_TOPIC_SUSBCRIPTIONS = ['#']
DEFAULT_EXCHAGE = 'amq.topic' DEFAULT_EXCHAGE = 'amq.topic'
DEFAULT_AMQP_URL = 'amqp://guest:guest@locahost/' DEFAULT_AMQP_URL = 'amqp://guest:guest@locahost/'
...@@ -58,9 +57,9 @@ class AmqpListener(threading.Thread): ...@@ -58,9 +57,9 @@ class AmqpListener(threading.Thread):
self.amqp_connect() self.amqp_connect()
@classmethod @classmethod
def default_message_handler(cls,message_as_dict): def default_message_handler(cls, message_as_dict):
clean_dict = dict((k, v) for k, v in message_as_dict.items() if v) clean_dict = dict((k, v) for k, v in message_as_dict.items() if v)
print(json.dumps(clean_dict,indent=4)) print(json.dumps(clean_dict, indent=4))
def amqp_connect(self): def amqp_connect(self):
self.connection = pika.BlockingConnection(pika.URLParameters(self.amqp_url)) self.connection = pika.BlockingConnection(pika.URLParameters(self.amqp_url))
...@@ -119,7 +118,7 @@ class AmqpListener(threading.Thread): ...@@ -119,7 +118,7 @@ class AmqpListener(threading.Thread):
raise Exception("Couldnt build message from json %s, amqp props: %s " % (body, props_dict)) raise Exception("Couldnt build message from json %s, amqp props: %s " % (body, props_dict))
m.update_properties(**props_dict) m.update_properties(**props_dict)
m.routing_key = method.routing_key m.routing_key = method.routing_key
logging.debug('Message in bus: %s'%repr(m)) logging.debug('Message in bus: %s' % repr(m))
self.message_dispatcher(m) self.message_dispatcher(m)
except NonCompliantMessageFormatError as e: except NonCompliantMessageFormatError as e:
...@@ -136,7 +135,7 @@ class AmqpListener(threading.Thread): ...@@ -136,7 +135,7 @@ class AmqpListener(threading.Thread):
body_dict = json.loads(body.decode('utf-8'), object_pairs_hook=OrderedDict) body_dict = json.loads(body.decode('utf-8'), object_pairs_hook=OrderedDict)
ch.basic_ack(delivery_tag=method.delivery_tag) ch.basic_ack(delivery_tag=method.delivery_tag)
text_based_message_representation = OrderedDict() text_based_message_representation = OrderedDict()
text_based_message_representation.update({'routing_key':method.routing_key}) text_based_message_representation.update({'routing_key': method.routing_key})
text_based_message_representation.update(props_dict) text_based_message_representation.update(props_dict)
text_based_message_representation.update(body_dict) text_based_message_representation.update(body_dict)
self.message_dispatcher(text_based_message_representation) self.message_dispatcher(text_based_message_representation)
...@@ -184,7 +183,7 @@ def publish_message(connection, message): ...@@ -184,7 +183,7 @@ def publish_message(connection, message):
channel.close() channel.close()
def amqp_request(connection, request_message, component_id, retries = 10): def amqp_request(connection, request_message, component_id, retries=10):
""" """
Publishes message into the correct topic (uses Message object metadata) Publishes message into the correct topic (uses Message object metadata)
Returns reply message. Returns reply message.
...@@ -322,5 +321,6 @@ if __name__ == '__main__': ...@@ -322,5 +321,6 @@ if __name__ == '__main__':
channel = con.channel() channel = con.channel()
ui_request = MsgUiRequestConfirmationButton() ui_request = MsgUiRequestConfirmationButton()
ui_reply = amqp_request(con,ui_request,'dummy_component') print("publishing .. %s" % repr(ui_request))
print(repr(ui_reply)) ui_reply = amqp_request(con, ui_request, 'dummy_component')
\ No newline at end of file print(repr(ui_reply))
...@@ -438,21 +438,30 @@ def action(api_call): ...@@ -438,21 +438,30 @@ def action(api_call):
_echo_dispatcher('Command <action %s> not accepted' % api_call) _echo_dispatcher('Command <action %s> not accepted' % api_call)
ignorable_message_types = {
'dissections': [MsgDissectionAutoDissect],
'packets': [MsgPacketSniffedRaw, MsgPacketInjectRaw],
'ui': [MsgUiRequestTextInput,
MsgUiRequestConfirmationButton,
MsgUiDisplay,
MsgUiDisplayMarkdownText,
MsgUiReply]
}
@cli.command() @cli.command()
@click.argument('message_type', type=click.Choice(['dissections'])) @click.argument('message_type', type=click.Choice(list(ignorable_message_types.keys())))
def ignore(message_type): def ignore(message_type):
""" """
Do not notify any more on message type Do not notify any more on message type
""" """
message_types = { try:
'dissections': [MsgDissectionAutoDissect], for item in ignorable_message_types[message_type]:
'packets': [MsgPacketSniffedRaw, MsgPacketInjectRaw]
}
if message_type in message_types:
for item in message_types[message_type]:
_add_to_ignore_message_list(item) _add_to_ignore_message_list(item)
_echo_dispatcher('Ignore message category %s: (%s)' % (message_type, str(item))) _echo_dispatcher('Ignore message category %s: (%s)' % (message_type, str(item)))
except KeyError as ke:
_echo_error('Couldnt add to ignored list..')
_echo_error(ke)
@cli.command() @cli.command()
...@@ -463,9 +472,42 @@ def enter_debug_context(): ...@@ -463,9 +472,42 @@ def enter_debug_context():
""" """
global message_handles_options global message_handles_options
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# 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))
publish_message(message_t)
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)
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# TODO group cmds # TODO group cmds
@cli.command() @cli.command()
@click.option('-tc','--testcase-id',default=None, help="testcase id") @click.option('-tc', '--testcase-id', default=None, help="testcase id")
def _sniffer_start(testcase_id): def _sniffer_start(testcase_id):
""" """
Sniffer start Sniffer start
...@@ -608,6 +650,22 @@ def enter_debug_context(): ...@@ -608,6 +650,22 @@ def enter_debug_context():
_echo_input(text) _echo_input(text)
publish_message(msg) publish_message(msg)
@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)
publish_message(msg)
_echo_session_helper("Entering debugger context, added extra CMDs, please type --help for more info") _echo_session_helper("Entering debugger context, added extra CMDs, please type --help for more info")
...@@ -1121,6 +1179,7 @@ def _echo_log_message(msg): ...@@ -1121,6 +1179,7 @@ def _echo_log_message(msg):
else: else:
click.echo(click.style("[%s] %s" % ('log', list_to_str(msg)), fg=COLOR_SESSION_LOG)) click.echo(click.style("[%s] %s" % ('log', list_to_str(msg)), fg=COLOR_SESSION_LOG))
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# some auxiliary functions # some auxiliary functions
......
...@@ -239,8 +239,8 @@ class MsgReply(Message): ...@@ -239,8 +239,8 @@ class MsgReply(Message):
logging.warning('(!) messages library | deprecate .service in favour of .request') logging.warning('(!) messages library | deprecate .service in favour of .request')
self.routing_key = request_message.routing_key + ".reply" self.routing_key = request_message.routing_key + ".reply"
elif self.routing_key.endswith(".request"): elif request_message.routing_key.endswith(".request"):
self.routing_key = self.routing_key.replace(".request", ".reply") self.routing_key = request_message.routing_key.replace(".request", ".reply")
# if not data template, then let's build one for a reply # if not data template, then let's build one for a reply
# (possible when creating a MsgReply directly and not by using subclass) # (possible when creating a MsgReply directly and not by using subclass)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment