def stop(self): with self.__code_block_locker: self.__context.insert_code_block([(command_type.COMMAND_EXIT, "")]) reply_code = self.notify(tas_command_type.TASK_STOP) logging.info("Stop command from session manager is received (reply code: '%s').", str(reply_code)) return reply_code
def do_GET(self): tas_host, tas_port = self.client_address[:2] logging.info( "Receive HTTP GET request from TAS: '%s' (address: '%s:%s').", self.path, tas_host, tas_port) request = http_parser.parse(http_method.HTTP_GET, self.path) if isinstance(request, parser_failure): self.__send_response(self.__parser_failure_to_http_code(request), "\"Impossible to process GET request.\"") return # # EXECUTION_STATUS # if request[struct_field.id] == tas_command_type.EXECUTION_STATUS: if configuration.get_failure_execution_status_code() is not None: self.__send_response( configuration.get_failure_execution_status_code(), None, configuration.get_failure_execution_status_message()) return session_id = request[struct_field.session_id] #script_id = request[struct_field.script_id]; if self.__get_session_manager().exist(session_id): json_response = json_builder.execution_status_response("Ok") self.__send_response(http_code.HTTP_OK, json_response) else: self.__send_response( http_code.HTTP_NOT_FOUND, "\"Session '" + str(session_id) + "' is not found.\"") # # SERVICE_STATUS # elif request[struct_field.id] == tas_command_type.SERVICE_STATUS: if (configuration.get_failure_service_status_code() is not None): self.__send_response( configuration.get_failure_service_status_code(), None, configuration.get_failure_service_status_message()) return json_response = json_builder.service_status_response( "Ok", {"amount_sessions": task_manager.get_amount_sessions()}) self.__send_response(http_code.HTTP_OK, json_response) else: self.__send_response( http_code.HTTP_BAD_REQUEST, "\"Unknown GET type command '" + str(request[struct_field.id]) + "'.\"")
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 __run(self): while self.__stop_flag is not True: with self.__stop_condition: self.__stop_condition.wait(self.__logging_period_seconds) logging.info( "QSim Simulator statistics:\n\n" "\tTAS REQs (in): %4d, TAS RESPs (in): %4d\n" "\tQSim REQs (out): %4d, QSim RESPs (out): %4d\n\n", statistical.get_tas_requests(), statistical.get_tas_responses(), statistical.get_qsim_requests(), statistical.get_qsim_responses())
def notify(self, tas_notification_id, message_payload=None): reply_code = None string_message_id = tas_notification_id with self.__code_block_locker: trigger = self.__context.get_trigger(tas_notification_id) if trigger is not None: self.__context.insert_code_block(trigger.commands) reply_code = trigger.reply_code logging.info("Code block for the message '%s' is found (reply code: '%s').", string_message_id, str(reply_code)) with self.__tas_message_condition: self.__context.set_last_input_message((tas_notification_id, message_payload)) self.__tas_messages.append(string_message_id) self.__tas_message_condition.notify_all() return reply_code
def __send_response(self, http_code, json_data=None, http_message=None, headers=None): time.sleep(configuration.get_response_delay() / 1000.0) self.send_response(http_code, http_message) self.send_header('Content-Type', 'application/json') body = None if json_data is not None: body = json_data.encode("utf-8") self.send_header('Content-Length', len(body)) if headers is not None: for key, value in headers.items(): self.send_header(key, value) try: self.end_headers() if body is not None: self.wfile.write(body) statistical.inc_qsim_responses() logging.info("Send response to TAS (code '%d (%s)', body '%s')", http_code, str(http_message), body) except ConnectionResetError: logging.error( "Impossible to send request to TAS due to reset connection.") except Exception as expection_object: logging.error( "Impossible to send request to TAS due to unknown reason ('%s')." % expection_object)
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 do_DELETE(self): tas_host, tas_port = self.client_address[:2] logging.info( "Receive HTTP DELETE request from TAS: '%s' (address: '%s:%s').", self.path, tas_host, tas_port) request = http_parser.parse(http_method.HTTP_DELETE, self.path) if isinstance(request, parser_failure): self.__send_response(self.__parser_failure_to_http_code(request), "\"Impossible to process DELETE request.\"") return # # TASK_STOP # if request[struct_field.id] != tas_command_type.TASK_STOP: self.__send_response( http_code.HTTP_BAD_REQUEST, "\"Unknown DELETE type command '" + str(request[struct_field.id]) + "'.\"") return if configuration.get_failure_stop_qsim_code() is not None: self.__send_response(configuration.get_failure_stop_qsim_code(), None, configuration.get_failure_stop_qsim_message()) return session_id = request[struct_field.session_id] if self.__get_session_manager().exist(session_id) is True: # notify to check whether scenario contains something specific about termination self.__get_session_manager().notify(session_id, tas_command_type.TASK_STOP, None) try: response = queue.get(True, 1) except: response = None if response is None: # scenario does not have anything specific about termination reply_code = self.__get_session_manager().delete(session_id) if reply_code is None: reply_code = http_code.HTTP_OK_NO_CONTENT logging.info( "Reply is not provided for TASK_STOP, use simulator response code (%d).", reply_code) self.__send_response(reply_code) else: event_type = type(response) if event_type == event_ignore: pass elif event_type == event_response: logging.info( "Reply to TASK_STOP is provided by scenario (code: %d).", response.code) self.__send_response(response.code, response.body, response.message, response.headers) else: message = "Unexpected event is received." logging.error(message) else: self.__send_response( http_code.HTTP_NOT_FOUND, "\"Session '" + str(session_id) + "' is not found.\"")
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 launch(task_id): with task_manager.__resource_locker: logging.info("Launch session instance (task ID: '%s').", task_id) task_manager.__tasks[task_id].start()