示例#1
0
    def create_uninstall_task(products: ProductCollection):
        """
        фабричный метод: создать такс с переданными параметрами, с типом COMMAND_UNINSTALL
        сохранить в базе данных
        зхапустить воркер

        :param requested_products:
        :param products:
        :param parameter_manager:
        :return:
        """

        job_array = []
        settings = json_encode(Core.get_instance().settings.get_state())

        task_object = TaskDataModel(command="uninstall", settings=settings)
        for product in products:
            state = {
                'products': [product.name],
            }
            job = JobDataModel(
                command=JobDataModel.COMMAND_UNINSTALL,
                title=product.title,
                params=json_encode(state),
                settings=settings)
            job_array.append(job)

        task = Task(task_model=task_object, jobs=job_array)
        return task
示例#2
0
    def create_uninstall_task(products: ProductCollection):
        """
        фабричный метод: создать такс с переданными параметрами, с типом COMMAND_UNINSTALL
        сохранить в базе данных
        зхапустить воркер

        :param requested_products:
        :param products:
        :param parameter_manager:
        :return:
        """

        job_array = []
        settings = json_encode(Core.get_instance().settings.get_state())

        task_object = TaskDataModel(command="uninstall", settings=settings)
        for product in products:
            state = {
                'products': [product.name],
            }
            job = JobDataModel(command=JobDataModel.COMMAND_UNINSTALL,
                               title=product.title,
                               params=json_encode(state),
                               settings=settings)
            job_array.append(job)

        task = Task(task_model=task_object, jobs=job_array)
        return task
示例#3
0
    def create_install_task(products: ProductCollection,
                            parameter_manager: ParametersManager):
        """
        фабричный метод: создать такс с переданными параметрами, с типом COMMAND_INSTALL
        сохранить в базе данных
        зхапустить воркер
        :param products:  продукты для установки (продукты которые выбрал пользователь + зависимости)
        :param parameter_manager:
        :return: номер таска
        """
        settings = json_encode(Core.get_instance().settings.get_state())
        job_array = []
        task_object = TaskDataModel(command="install", settings=settings)
        for product in products:
            title = product.title

            state = {
                'products': [product.to_dict()],
                'parameters': parameter_manager.get_state()
            }
            state2save = json_encode(state)

            job = JobDataModel(command=JobDataModel.COMMAND_INSTALL,
                               title=title,
                               params=state2save,
                               task=task_object,
                               settings=settings)
            job_array.append(job)
        task = Task(task_model=task_object, jobs=job_array)
        return task
示例#4
0
    def create_install_task(products: ProductCollection,
                            parameter_manager: ParametersManager):
        """
        фабричный метод: создать такс с переданными параметрами, с типом COMMAND_INSTALL
        сохранить в базе данных
        зхапустить воркер
        :param products:  продукты для установки (продукты которые выбрал пользователь + зависимости)
        :param parameter_manager:
        :return: номер таска
        """
        settings = json_encode(Core.get_instance().settings.get_state())
        job_array = []
        task_object = TaskDataModel(command="install", settings=settings)
        for product in products:
            title = product.title

            state = {
                'products': [product.to_dict()],
                'parameters': parameter_manager.get_state()
            }
            state2save = json_encode(state)

            job = JobDataModel(
                command=JobDataModel.COMMAND_INSTALL,
                title=title,
                params=state2save,
                task=task_object,
                settings=settings
            )
            job_array.append(job)
        task = Task(task_model=task_object, jobs=job_array)
        return task
示例#5
0
    def create_upgrade_task(products: ProductCollection, parameter_manager: ParametersManager):
        """
        фабричный метод: создать такс с переданными параметрами, с типом COMMAND_UPGRADE
        сохранить в базе данных
        зхапустить воркер

        :param products:
        :param parameter_manager:
        :return:
        """
        settings = json_encode(Core.get_instance().settings.get_state())
        job_array = []
        task_object = TaskDataModel(command="upgrade", settings=settings)
        for product in products:
            title = product.title

            state = {
                'products': [product.to_dict()],
                'parameters': parameter_manager.get_state()
            }
            state2save = json_encode(state)

            job = JobDataModel(
                command=JobDataModel.COMMAND_UPGRADE,
                title=title,
                params=state2save,
                task=task_object,
                settings=settings
            )
            job_array.append(job)
        task = Task(task_model=task_object, jobs=job_array)
        return task
示例#6
0
    def create_upgrade_task(products: ProductCollection,
                            parameter_manager: ParametersManager):
        """
        фабричный метод: создать такс с переданными параметрами, с типом COMMAND_UPGRADE
        сохранить в базе данных
        зхапустить воркер

        :param products:
        :param parameter_manager:
        :return:
        """
        settings = json_encode(Core.get_instance().settings.get_state())
        job_array = []
        task_object = TaskDataModel(command="upgrade", settings=settings)
        for product in products:
            title = product.title

            state = {
                'products': [product.to_dict()],
                'parameters': parameter_manager.get_state()
            }
            state2save = json_encode(state)

            job = JobDataModel(command=JobDataModel.COMMAND_UPGRADE,
                               title=title,
                               params=state2save,
                               task=task_object,
                               settings=settings)
            job_array.append(job)
        task = Task(task_model=task_object, jobs=job_array)
        return task
示例#7
0
    def writing_logs(self, obj):
        # if requested task logs is not equal to current task than this task is pending
        if obj["msg"] == "hello":
            # connect task manager task_id and web socket task_id
            self.write_message(json_encode({"status": False, "data": {}}))
            return

        # process socket connection if depends
        task_id = int(obj["task_id"])
        if task_id in self.configs["buffer"]:
            messages = []
            now_time = time.time()
            # get dict repr for json
            desc = None
            state = None
            status = False
            for item in self.configs["buffer"][task_id]:
                job_id = ""
                if item.job_object:
                    job_id = item.job_object.id
                messages.append({
                    "created": now_time,
                    "message": item.message,
                    'level': item.level,
                    'job_id': job_id
                })
                status = True
                if item.job_process is not None:
                    # main question
                    desc = item.job_process.dict_repr()
                    state = item.task_state

            self.configs["buffer"][task_id] = []

            if len(messages) > 0:
                result = {
                    "status": status,
                    "state": state,
                    "data": {
                        "task": desc,
                        "log_messages": messages
                    }
                }

                self.write_message(json_encode(result))
            else:
                self.write_message(json_encode({"status": False}))
            return

        else:
            self.write_message(
                json_encode({
                    "status": False,
                    "state": "pending",
                    "data": {}
                }))
            return
示例#8
0
 def command_install(self):
     state = json_decode(self.params)
     result = core.core.Core.get_instance().install(state['products'], state['parameters'],
                                                    False, True)
     state["parameters"] = result['parameters']
     self.params = json_encode(state)
     self.save()
示例#9
0
    def decorator(request, *args, **kwargs):
        http_status = 200
        headers = [("Content-Type", 'text/javascript'),
                   ('Cache-Control', 'no-cache,no-store,must-revalidate,max-age=0')]
        try:
            result = func(request, *args, **kwargs)
            # it's means that result is http response object or derived from it
            if hasattr(result, "status_code"):
                return result
            result = {'data': result}

        except Exception as ex:
            result = {
                'data': None,
                'error': {
                    'print_traceback': not hasattr(ex, 'do_not_print'),
                    'class': ex.__class__.__name__,
                    'args': '{0}'.format(ex),
                    'traceback': traceback.format_exc()
                }
            }
            http_status = 500
            traceback.print_exc()

        try:
            data = json_encode(result)
            if 'callback' in request.REQUEST:
                # a jsonp response!
                data = '%s(%s);' % (request.REQUEST['callback'], data)
                response = HttpResponse(body=data, headers=headers, status_code=http_status)
                return response
        except Exception:
            raise
        response = HttpResponse(body=data, headers=headers, status_code=http_status)
        return response
示例#10
0
    def writing_output(self, obj):
        try:
            # process socket connection if depends
            path = obj["path"]
            console_obj = WebConsole.get_console(path)
            messages = []
            now_time = time.time()
            # get dict repr for json

            for item in console_obj.buffer:
                messages.append({
                    "created": now_time,
                    "message": item['msg'],
                    "type": item['type']
                })

            console_obj.buffer = []
            if len(messages) > 0:
                result = {"status": True, "messages": messages}
                self.write_message(json_encode(result))
            else:
                self.write_empty_pong()

        except tornado.websocket.WebSocketClosedError:
            logging.debug("connection is closed")

        return
示例#11
0
 def writing_error(self, error):
     try:
         messages = []
         now_time = time.time()
         messages.append({"created": now_time, "message": error, "type": "stderr"})
         result = {"status": True, "messages": messages}
         self.write_message(json_encode(result))
     except tornado.websocket.WebSocketClosedError:
         logging.debug("connection is closed")
示例#12
0
 def writing_console_down(self, obj):
     try:
         messages = []
         now_time = time.time()
         messages.append({"created": now_time, "message": "\n{0}\n".format(obj["command"]), "type": "stdout"})
         messages.append({"created": now_time, "message": "Zoo Web Console is Down\n Try recreate it", "type": "stderr"})
         result = {"status": True, "messages": messages}
         self.write_message(json_encode(result))
     except tornado.websocket.WebSocketClosedError:
         logging.debug("connection is closed")
示例#13
0
 def writing_error(self, error):
     try:
         messages = []
         now_time = time.time()
         messages.append({
             "created": now_time,
             "message": error,
             "type": "stderr"
         })
         result = {"status": True, "messages": messages}
         self.write_message(json_encode(result))
     except tornado.websocket.WebSocketClosedError:
         logging.debug("connection is closed")
示例#14
0
    def on_message(self, message):
        """
        when we receive some message we want some message handler..
        for this example i will just print message to console
        """
        try:
            request = json_decode(message)
            if "create" in request:
                Result = self.create_console(request)
                self.write_message(json_encode({"status": Result}))
                return

            if "cancel" in request:
                logging.debug("cancel console")
                if self.background_object:
                    self.background_object.close()
                    self.close()
                return

            if "ping" in request:
                if "path" in request:
                    path = request["path"]
                    console_obj = WebConsole.get_console(path)
                    if console_obj:
                        self.writing_output(request)
                    else:
                        self.write_empty_pong()

                return

            if "ctrl_c" in request:
                console_instance = WebConsole.get_console(request["path"])
                if console_instance:
                    self.background_object.close()
                    self.close()
                return

            if "command" in request:
                console_instance = WebConsole.get_console(request["path"])
                if console_instance:
                    console_instance.execute(request['command'])
                    self.writing_output(request)
                else:
                    self.writing_console_down(request)
                return

        except Exception as e:
            error = traceback.format_exc()
            self.writing_error(error)
示例#15
0
    def on_message(self, message):
        """
        when we receive some message we want some message handler..
        for this example i will just print message to console
        """
        try:
            request = json_decode(message)
            if "create" in request:
                Result = self.create_console(request)
                self.write_message(json_encode({"status": Result}))
                return

            if "cancel" in request:
                logging.debug("cancel console")
                if self.background_object:
                    self.background_object.close()
                    self.close()
                return

            if "ping" in request:
                if "path" in request:
                    path = request["path"]
                    console_obj = WebConsole.get_console(path)
                    if console_obj:
                        self.writing_output(request)
                    else:
                        self.write_empty_pong()

                return

            if "ctrl_c" in request:
                console_instance = WebConsole.get_console(request["path"])
                if console_instance:
                    self.background_object.close()
                    self.close()
                return

            if "command" in request:
                console_instance = WebConsole.get_console(request["path"])
                if console_instance:
                    console_instance.execute(request['command'])
                    self.writing_output(request)
                else:
                    self.writing_console_down(request)
                return

        except Exception as e:
            error = traceback.format_exc()
            self.writing_error(error)
示例#16
0
 def writing_console_down(self, obj):
     try:
         messages = []
         now_time = time.time()
         messages.append({
             "created": now_time,
             "message": "\n{0}\n".format(obj["command"]),
             "type": "stdout"
         })
         messages.append({
             "created": now_time,
             "message": "Zoo Web Console is Down\n Try recreate it",
             "type": "stderr"
         })
         result = {"status": True, "messages": messages}
         self.write_message(json_encode(result))
     except tornado.websocket.WebSocketClosedError:
         logging.debug("connection is closed")
示例#17
0
    def writing_output(self, obj):
        try:
            # process socket connection if depends
            path = obj["path"]
            console_obj  = WebConsole.get_console(path)
            messages = []
            now_time = time.time()
            # get dict repr for json

            for item in console_obj.buffer:
                messages.append({"created": now_time, "message": item['msg'], "type": item['type']})

            console_obj.buffer = []
            if len(messages) > 0:
                result = {"status": True,
                          "messages": messages}
                self.write_message(json_encode(result))
            else:
                self.write_empty_pong()

        except tornado.websocket.WebSocketClosedError:
            logging.debug("connection is closed")

        return
示例#18
0
def gen_command(cmd: dict) -> str:
    command_object = json_encode(cmd)
    command_object = command_object.replace("\n", "")
    return "\n%s%s%s\n" % (command_delimiter, command_object,
                           command_delimiter)
示例#19
0
 def command_upgrade(self):
     state = json_decode(self.params)
     result = core.core.Core.get_instance().upgrade(state['products'], state.get('parameters'))
     state["parameters"] = result['parameters']
     self.params = json_encode(state)
     self.save()
示例#20
0
 def write_empty_pong(self):
     try:
         self.write_message(json_encode({"status": False}))
     except tornado.websocket.WebSocketClosedError:
         logging.debug("connection is closed")
示例#21
0
 def write_empty_pong(self):
     try:
         self.write_message(json_encode({"status": False}))
     except tornado.websocket.WebSocketClosedError:
         logging.debug("connection is closed")
示例#22
0
文件: core.py 项目: helicontech/zoo
def gen_command(cmd: dict)-> str:
    command_object = json_encode(cmd)
    command_object = command_object.replace("\n", "")
    return "\n%s%s%s\n" % (command_delimiter, command_object, command_delimiter)