Esempio n. 1
0
    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
Esempio n. 2
0
    def stop(self):
        logging.vip("HTTP server is being closing (port: '%d').", self.__port)
        if self.__statistical_logger is not None:
            self.__statistical_logger.stop()

        self.__logger_server.stop()

        self.__server.shutdown()
        self.__server.server_close()
Esempio n. 3
0
    def start(self):
        logging.vip("HTTP server is being starting (port: '%d').", self.__port)
        try:
            if self.__statistical_logger is not None:
                self.__statistical_logger.start()

            self.__server.serve_forever()

        except KeyboardInterrupt:
            self.stop()
Esempio n. 4
0
    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
Esempio n. 5
0
    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
Esempio n. 6
0
    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)
Esempio n. 7
0
 def __process_assign_command(self, variable_name, variable_value):
     logging.vip("(QSim Service task '%s') command to assign value '%s' to variable: '%s'.", self.__context.get_id(), variable_value, variable_name)
     self.__assign_variable_value(variable_name, variable_value)
Esempio n. 8
0
    def __process_ask_command(self, variable_name):
        logging.vip("(QSim Service task '%s') command to ask user value of variable: '%s'.", self.__context.get_id(), variable_name)

        variable_value = input("Please enter value for variable '%s': " % variable_name)
        self.__assign_variable_value(variable_name, variable_value)