def __init__(self, queue_id, tas_request): self.__script_id = queue_id self.__tas_info = tas_request self.__play_id = None self.__collect_id = None self.__forward_group_id = None self.__task_id = task_context.__generate_task_id() self.__cursor = 0 self.__variables = {} block = script.load(queue_id) self.__actions = block.get_commands() self.__triggers = block.get_triggers() self.__functions = block.get_functions() self.__last_input_message = None if len(self.__actions) == 0: logging.warning( "Script-file (script id: '%s') does not have any actions for TAS.", queue_id) logging.debug( "Q Service context is generated (task id: '%s', script id: '%s').", self.__task_id, self.__script_id) logging.debug( "Q Service script '%s' info (commands: '%d', triggers: '%d', functions: '%d').", self.__script_id, len(self.__actions), len(self.__triggers), len(self.__functions))
def create(queue_id, tas_request): tas_session_id = tas_request["session_id"] with task_manager.__resource_locker: if tas_session_id in task_manager.__script_mapping: logging.debug("Notify about start message (queue ID: '%s', session ID: '%s', amount tasks: '%d').", queue_id, tas_session_id, len(task_manager.__tasks)) task_id = task_manager.__script_mapping[tas_session_id] task_manager.__tasks[task_id].notify(tas_command_type.TASK_START) else: session_instance = task(queue_id, tas_request, task_manager) if session_instance is None: return False task_id = session_instance.get_id() task_manager.__script_mapping[tas_session_id] = task_id task_manager.__tasks[task_id] = session_instance session_instance.start() logging.vip("Create new session instance (queue ID: '%s', session ID: '%s', task ID: '%s', amount tasks: '%d').", queue_id, tas_session_id, task_id, len(task_manager.__tasks)) session_instance.notify(tas_command_type.TASK_START) return True
def exist(task_id): with task_manager.__resource_locker: logging.debug("Amount of tasks '%d' (search task ID: '%s').", len(task_manager.__tasks), task_id) if task_id in task_manager.__tasks: return True return False
def notify(task_id, tas_notification_id, message_payload): with task_manager.__resource_locker: if task_manager.exist(task_id): logging.debug("Convey notification to session instance (task ID: '%s', amount tasks: '%d').", task_id, len(task_manager.__tasks)) return task_manager.__tasks[task_id].notify(tas_notification_id, message_payload) return None
def __run(self): logging.debug("(Q Service session '%s') session '%s' is started at '%s'.", self.__context.get_id(), self.__context.get_id(), time.ctime()) with self.__code_block_locker: command_container = self.__context.get_next_command() while (self.__active is True) and (command_container is not None): (command, arguments) = command_container if command == command_type.COMMAND_SEND: self.__process_send_command(arguments[0], arguments[1], arguments[2], arguments[3]) elif command == command_type.COMMAND_TIMEOUT: self.__process_timeout_command(arguments[0]) elif command == command_type.COMMAND_WAIT: self.__process_wait_command(arguments[0]) elif command == command_type.COMMAND_REPLY: self.__process_reply_command(arguments[0], arguments[1], arguments[2], arguments[3]) elif command == command_type.COMMAND_IGNORE: self.__process_ignore_command() elif command == command_type.COMMAND_ASK: self.__process_ask_command(arguments[0]) elif command == command_type.COMMAND_ASSIGN: self.__process_assign_command(arguments[0], arguments[1]) elif command == command_type.COMMAND_PRINT: self.__process_print_comand(arguments[0]) elif command == command_type.COMMAND_EXIT: logging.info("(QSim Service task '%s') exit command is detected - termination...", self.__context.get_id()) self.__active = False elif command == command_type.COMMAND_MOVE_JSON: self.__process_move_json(arguments[0]) elif command == command_type.COMMAND_IF: self.__process_conditional_block(arguments[0], arguments[1]) else: logging.error("(QSim Service task '%s') unexpected command is detected...", self.__context.get_id()) self.__previous_command = command with self.__code_block_locker: command_container = self.__context.get_next_command() self.__manager.delete(self.__context.get_id()) logging.info("(QSim Service task '%s') session is terminated at '%s'.", self.__context.get_id(), time.ctime())
def delete(task_id, internal=False): reply_code = None with task_manager.__resource_locker: if task_manager.exist(task_id): if internal is False: # is already stopped by itself reply_code = task_manager.__tasks[task_id].stop() tas_session_id = task_manager.__tasks[task_id].get_session_id() task_manager.__script_mapping.pop(tas_session_id) task_manager.__tasks.pop(task_id) logging.debug("Delete session instance (task ID: '%s', session ID: '%s' amount tasks: '%d').", task_id, tas_session_id, len(task_manager.__tasks)) return reply_code
def __process_wait_command(self, expected_message): logging.debug("(QSim Service task '%s') wait for TAS message ('%s')...", self.__context.get_id(), expected_message) while self.__active is True: response = "" with self.__tas_message_condition: while len(self.__tas_messages) == 0 and self.__active is True: self.__tas_message_condition.wait() if len(self.__tas_messages) > 0: response = self.__tas_messages.pop() if response != expected_message: logging.warning("(QSim Service task '%s') unexpected message is received from TAS: '%s' (but expected: '%s'), continue to wait.", self.__context.get_id(), response, expected_message) continue else: logging.debug("(QSim Service task '%s') expected response is received '%s', stop waiting process.", self.__context.get_id(), response) break
def __process_reply_command(self, code, message, json_body, headers): logging.debug("(QSim Service task '%s') command REPLY is executing...", self.__context.get_id()) previous_message = self.__context.get_last_input_message()[0] if previous_message is None: logging.error("(QSim Service task '%s') impossible to reply, nothing was received.", self.__context.get_id()) return if previous_message == tas_command_type.TASK_START: if (json_body is None) or (len(json_body) == 0): json_body = json_builder.start_qsim_response(self.__context.get_id()) event = event_start_response(code, message, headers, json_body) else: event = event_response(code, message, headers, json_body) queue.put(event) logging.debug("(QSim Service task '%s') Send event response to '%s' (code: '%d') to HTTP handler queue.", self.__context.get_id(), previous_message, code)
def send_request(self, http_method, http_link, json_request, general_headers): response_body = None connection = http.client.HTTPConnection(self.__address, self.__port, timeout=1) try: logging.vip("Send HTTP request to TAS (%s:%s): '%s' '%s'.", self.__address, self.__port, http_method, http_link) logging.debug("JSON payload of the HTTP request to TAS: '%s'.", json_request) headers = {"Content-Type": "application/json", "Accept": "*/*"} body = None if json_request is not None: body = json_request.encode("utf-8") headers['Content-Length'] = len(body) headers.update(general_headers) statistical.inc_qsim_requests() connection.request(http_method, http_link, body, headers) logging.debug("Check for HTTP response from TAS.") response = connection.getresponse() response_status = response.status logging.debug("Read body of the HTTP response from TAS.") response_body = response.read() statistical.inc_qsim_responses() logging.vip("HTTP response (code: %d) from TAS:", response_status) logging.debug(response_body.decode("utf-8")) except Exception as expection_object: response_status = 600 logging.error("Impossible to communicate correctly with TAS using HTTP (reason: '%s')." % expection_object) finally: connection.close() return response_status, response_body
def do_POST(self): tas_host, tas_port = self.client_address[:2] logging.vip( "Receive HTTP POST request from TAS: '%s' (address: '%s:%s').", self.path, tas_host, tas_port) request = http_parser.parse(http_method.HTTP_POST, self.path) if isinstance(request, parser_failure): self.__send_response(self.__parser_failure_to_http_code(request), "\"Impossible to process POST request.\"") return # # TASK_START # if request[struct_field.id] == tas_command_type.TASK_START: if configuration.get_failure_start_qsim_code() is not None: self.__send_response( configuration.get_failure_start_qsim_code(), None, configuration.get_failure_start_qsim_message()) return # extract TAS request for session and attach additional information tas_request = {} json_request = self.rfile.read(int( self.headers['Content-Length'])).decode('utf-8') if (json_request is not None) and (len(json_request) > 0): tas_request = json.loads(json_request) tas_request["tas_address"] = {"ip": tas_host, "port": tas_port} tas_request["account_id"] = request[struct_field.account_id] # fill by default values tas_request["session_id"] = tas_request["sessionId"] tas_request["party_id"] = tas_request["inPartyId"] tas_request["q_party_id"] = tas_request["qPartyId"] tas_request["rcaccount_id"] = tas_request["account_id"] tas_request["rcextension_id"] = tas_request["account_id"] tas_request["rcbrand_id"] = "1210" logging.debug( "QueueId (%s): Store default party ID (%s) and session ID (%s)." % (request[struct_field.script_id], tas_request["party_id"], tas_request["session_id"])) if self.__get_session_manager().create( request[struct_field.script_id], tas_request) is False: message = "Impossible to create session object due to lack of scenario file." logging.error(message) self.__send_response(http_code.HTTP_NOT_FOUND, "\"%s\"" % message) return try: response = queue.get(True, 2) except: response = None if response is None: message = "Event with response is not received." logging.error(message) self.__send_response(http_code.HTTP_INTERNAL_SERVER_ERROR, "\"%s\"" % message) return event_type = type(response) if event_type == event_start_response: self.__send_response(response.code, response.body, response.message, response.headers) elif event_type == event_ignore: pass else: message = "Unexpected event is received." logging.error(message) # # RESULT_ACTION # elif (request[struct_field.id] == tas_command_type.ON_COMMAND_UPDATE or request[struct_field.id] == tas_command_type.ON_COMMAND_ERROR): if configuration.get_failure_action_result_code() is not None: self.__send_response( configuration.get_failure_action_result_code(), None, configuration.get_failure_action_result_message()) return message_size = int(self.headers['Content-Length']) json_result = self.rfile.read(message_size).decode('utf-8') # it is represented by map because most probably other staff may be conveyed to session. json_instance = None if message_size > 0: try: json_instance = json.loads(json_result) except: logging.error( "Impossible to parse JSON - corrupted JSON payload is received." ) self.__send_response( http_code.HTTP_BAD_REQUEST, "\"Corrupted JSON payload in POST request.\"") return message_playload = {'json': json_instance} action_type = request[struct_field.id] command_id = json_instance.get("commandId", None) if command_id is None: logging.error( "Incorrect action request - commandId is not found in JSON." ) self.__send_response( http_code.HTTP_BAD_REQUEST, "\"JSON body does not contain 'commandId' field.\"") return logging.info("Received callback id: '%s':", command_id) logging.debug(json_result) session_instance = self.__get_session_manager( ).get_session_by_command_id(command_id) if session_instance is not None: # check if code is returned by trigger reply_code = session_instance.notify(action_type, message_playload) #reply_code = self.__get_session_manager().notify(session_id, command_id, message_playload) if reply_code is None: # if there is no trigger then let's take it from the queue, if there is user-specific code try: response = queue.get(True, 1) event_type = type(response) if event_type == event_ignore: logging.debug( "Ignore incoming request (do not sent response)." ) return reply_code = response.code reply_message = response.message logging.debug( "Specific reply to incoming request '%s' (code: '%s', command ID: '%s')." % (command_id, reply_code, reply_message)) except: # otherwise send default code reply_code = http_code.HTTP_OK reply_message = "\"Success.\"" logging.debug( "Default reply is used for incoming request '%s'." % action_type) else: reply_message = "\"Specified reply code is used.\"" logging.debug( "Specific reply is used for incoming request '%s' via trigger " "(code: '%s', message: '%s')." % (command_id, reply_code, reply_message)) self.__send_response(reply_code, reply_message) return self.__send_response( http_code.HTTP_NOT_FOUND, "\"Session for action '" + str(command_id) + "' is not found.\"") self.__get_session_manager().get_session_by_command_id(command_id) else: self.__send_response( http_code.HTTP_BAD_REQUEST, "\"Unknown POST type command '" + str(request[struct_field.id]) + "'.\"") return
def __process_send_command(self, action, tas_content, headers, arguments): logging.debug("(QSim Service task '%s') command SEND is executing...", self.__context.get_id()) if action == "PLAY": tas_link = self.__context.get_tas_link_start_play() tas_method = "POST" elif action == "STOP_PLAY": tas_link = self.__context.get_tas_link_stop_play() tas_method = "DELETE" elif action == "GET_PLAY": tas_link = self.__context.get_tas_link_stop_play() tas_method = "GET" elif action == "COLLECT": tas_link = self.__context.get_tas_link_start_collect() tas_method = "POST" elif action == "GET_COLLECT": tas_link = self.__context.get_tas_link_get_collect() tas_method = "GET" elif action == "STOP_COLLECT": tas_link = self.__context.get_tas_link_stop_collect() tas_method = "DELETE" elif action == "FORWARD": party_id = None if len(arguments) > 0: expression = arguments[0] analyser = expression_analyser(expression, self.__context) party_id = analyser.evaluate() arguments = [] tas_link = self.__context.get_tas_link_forward(party_id) tas_method = "POST" elif action == "FORWARD_GROUP": tas_link = self.__context.get_tas_link_add_forward_group() tas_method = "POST" elif action == "PATCH_FORWARD_GROUP": tas_link = self.__context.get_tas_link_forward_group() tas_method = "PATCH" elif action == "GET_FORWARD_GROUP": tas_link = self.__context.get_tas_link_forward_group() tas_method = "GET" elif action == "DELETE_FORWARD_GROUP": tas_link = self.__context.get_tas_link_forward_group() tas_method = "DELETE" elif action == "GET_SESSION": tas_link = self.__context.get_tas_link_session() tas_method = "GET" else: logging.error("Unknown send command '%s'.", action) return if len(arguments) > 0: tas_link_pattern = arguments[0] tas_link = self.__change_tas_link(tas_link, tas_link_pattern) tas_content = self.__translate_content(tas_content) logging.info("(QSim Service task '%s') send command request to TAS ('%s', '%s').", self.__context.get_id(), tas_method, action) custom_headers = {"rcaccountid": self.__context.get_rcaccount_id(), "rcextensionid": self.__context.get_rcextension_id(), "rcbrandid": self.__context.get_brand_id(), "origin": "127.0.0.1:" + str(configuration.get_qsim_port())} # add new and overwrite existed default custom headers in line with scenario for key, value in headers.items(): custom_headers[key.lower()] = value (status, json_response) = self.__send(tas_method, tas_link, tas_content, custom_headers) if json_response is not None: self.__context.set_last_input_message(json_response) if (status >= 200) and (status <= 299): if (tas_method == "POST") and (json_response is not None) and (len(json_response) > 0): response = json.loads(json_response.decode('utf-8')) if action == "PLAY": action_id = response['id'] self.__context.set_play_id(action_id) elif action == "COLLECT": action_id = response['id'] self.__context.set_collect_id(action_id) elif action == "FORWARD_GROUP": action_id = response['id'] self.__context.set_forward_group_id(action_id) else: action_id = None logging.info("(QSim Service task '%s') TAS accepts '%s' command '%s' and return action id: '%s'.", self.__context.get_id(), tas_method, action, action_id) else: logging.vip("(QSim Service task '%s') TAS reply to '%s' command '%s' by success status (code: '%d').", self.__context.get_id(), tas_method, action, status) else: logging.warning("(QSim Service task '%s') TAS reply to '%s' command '%s' by failure status (code: '%d', reason: '%s').", self.__context.get_id(), tas_method, action, status, json_response)
def __process_timeout_command(self, timeout): logging.debug("(QSim Service task '%s') command TIMEOUT is executing (time: '%d')...", self.__context.get_id(), timeout) time.sleep(timeout / 1000.0)
def __process_ignore_command(self): logging.debug("(QSim Service task '%s') command IGNORE is executing...", self.__context.get_id()) event = event_ignore() queue.put(event)