示例#1
0
    def update_urlmaps_groups(request):
        response = BaseResponse()
        try:
            response.error = {}
            post_dict = QueryDict(request.body, encoding='utf-8')
            urlmaps_id = post_dict.get('urlmaps_id')
            instance_list = post_dict.getlist('instance_list')
            group_type = post_dict.get('group_type')

            urlmaps_obj = repository_models.UrlConfigHandler.objects.get(
                id=urlmaps_id)

            if group_type == 'cloud':
                urlmaps_obj.cloud.clear()
                for instance_id in instance_list:
                    urlmaps_obj.cloud.add(
                        CMDB_MODELS.Asset.objects.get(id=instance_id))
            elif group_type == 'forward':
                urlmaps_obj.forward.clear()
                for instance_id in instance_list:
                    urlmaps_obj.forward.add(
                        CMDB_MODELS.Asset.objects.get(id=instance_id))
            elif group_type == 'docker':
                urlmaps_obj.docker.clear()
                for instance_id in instance_list:
                    urlmaps_obj.docker.add(
                        CMDB_MODELS.DockerInstance.objects.get(id=instance_id))

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
示例#2
0
文件: exec.py 项目: aixan/aixan
    def connect(self):
        self.accept()
        self.user = self.scope["user"]
        print(self.scope)
        query_string = self.scope.get("query_string")
        print(query_string)
        ssh_args = QueryDict(query_string=query_string, encoding='utf-8')

        host = ssh_args.get('hostname')
        host = Host.objects.get(hostname=host, deleted_by_id__isnull=True)
        exec = ssh_args.get("exec").replace(',', "\n")

        ssh_connect_dict = {
            'host': host.hostname,
            'user': host.username,
            'port': int(host.port),
            'exec': exec,
        }

        if host.pkey == '':
            private_key = AppSetting.get('private_key')
            ssh_connect_dict['ssh_key'] = private_key
        else:
            ssh_connect_dict['ssh_key'] = host.pkey

        self.ssh = SSHExecutor(websocker=self, **ssh_connect_dict)
        threading.Thread(target=self.ssh.run()).start()
示例#3
0
    def connect(self):
        """
        打开 websocket 连接, 通过前端传入的参数尝试连接 telnet 主机
        :return:
        """
        self.accept()
        query_string = self.scope.get('query_string')
        telnet_args = QueryDict(query_string=query_string, encoding='utf-8')

        port = telnet_args.get('port')
        port = int(port)

        ssh_key_name = telnet_args.get('ssh_key')
        passwd = telnet_args.get('password')

        host = telnet_args.get('host')
        user = telnet_args.get('user')

        if passwd:
            passwd = base64.b64decode(passwd).decode('utf-8')
        else:
            passwd = None

        self.telnet = Telnet(websocker=self, message=self.message)

        telnet_connect_dict = {
            'host': host,
            'user': user,
            'port': port,
            'password': passwd,
            'timeout': 30,
        }

        self.telnet.connect(**telnet_connect_dict)
示例#4
0
    def add_server_group(request):
        response = BaseResponse()
        try:
            response.error = {}
            print(request.body)
            post_dict = QueryDict(request.body, encoding='utf-8')

            add_group_app_id = post_dict.get('add_group_app_id')
            add_group_name = post_dict.get('add_group_name')
            add_group_yaml_path = post_dict.get('add_group_yaml_path')
            add_group_type = post_dict.get('add_group_type')

            add_to_db = repository_models.AppGroups(
                name=add_group_name,
                yaml_path=add_group_yaml_path,
                # app_id = repository_models.Applications.objects.get(id=add_group_app_id)
                group_type=add_group_type,
            )

            add_to_db.save()
            add_to_db.app_id.add(repository_models.Applications.objects.get(id=add_group_app_id))

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
示例#5
0
    def update_urlmaps_groups(request):
        response = BaseResponse()
        try:
            response.error = {}
            post_dict = QueryDict(request.body, encoding='utf-8')
            urlmaps_id = post_dict.get('urlmaps_id')
            instance_list = post_dict.getlist('instance_list')
            group_type = post_dict.get('group_type')

            urlmaps_obj = repository_models.UrlConfigHandler.objects.get(id=urlmaps_id)

            if group_type == 'cloud':
                urlmaps_obj.cloud.clear()
                for instance_id in instance_list:
                    urlmaps_obj.cloud.add(CMDB_MODELS.Asset.objects.get(id=instance_id))
            elif group_type == 'forward':
                urlmaps_obj.forward.clear()
                for instance_id in instance_list:
                    urlmaps_obj.forward.add(CMDB_MODELS.Asset.objects.get(id=instance_id))
            elif group_type == 'docker':
                urlmaps_obj.docker.clear()
                for instance_id in instance_list:
                    urlmaps_obj.docker.add(CMDB_MODELS.DockerInstance.objects.get(id=instance_id))

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
示例#6
0
    def add_server_group(request):
        response = BaseResponse()
        try:
            response.error = {}
            print(request.body)
            post_dict = QueryDict(request.body, encoding='utf-8')

            add_group_app_id = post_dict.get('add_group_app_id')
            add_group_name = post_dict.get('add_group_name')
            add_group_yaml_path = post_dict.get('add_group_yaml_path')
            add_group_type = post_dict.get('add_group_type')

            add_to_db = repository_models.AppGroups(
                name=add_group_name,
                yaml_path=add_group_yaml_path,
                # app_id = repository_models.Applications.objects.get(id=add_group_app_id)
                group_type=add_group_type,
            )

            add_to_db.save()
            add_to_db.app_id.add(
                repository_models.Applications.objects.get(
                    id=add_group_app_id))

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
示例#7
0
    def add_data(self, request):
        response = BaseResponse()
        try:
            post_dict = QueryDict(request.body, encoding='utf-8')

            add_business_parent_id = post_dict.get('add_business_parent_id', None)
            add_business_name = post_dict.get('add_business_name')
            add_business_admin_list = post_dict.getlist('add_business_admin_list', [])
            add_business_contact_list = post_dict.getlist('add_business_contact_list', [])
            add_business_memo = post_dict.get('add_business_memo')

            add_data_to_db = models.BusinessUnit(
                parent_unit_id=add_business_parent_id,
                name=add_business_name,
                memo=add_business_memo
            )

            add_data_to_db.save()

            for obj_id in add_business_admin_list:
                add_data_to_db.manager.add(user_center_models.UserGroup.objects.get(id=obj_id))
            for obj_id in add_business_contact_list:
                add_data_to_db.contact.add(user_center_models.UserGroup.objects.get(id=obj_id))

        except Exception as e:
            response.status = False
            response.message = str(e)
        return response
示例#8
0
 def connect(self):
     """
     打开 websocket 连接, 通过前端传入的参数尝试连接 ssh 主机
     :return:
     """
     self.accept()
     query_string = self.scope.get('query_string')
     ssh_args = QueryDict(query_string=query_string, encoding='utf-8')
     server_id = ssh_args.get('server_id')
     user_id = ssh_args.get('user_id')
     server = Server.objects.get(id=server_id)
     user = SSHUser.objects.get(id=user_id)
     private_key = settings.KEY_FILE
     self.ssh = SSH(websocket=self, message=self.message)
     ssh_connect_dict = {
         'host': server.ssh_ip,
         'port': server.ssh_port,
         'user': user.name,
         'password': user.password,
         'timeout': 30,
         'pty_width': 500,
         'pty_height': 200,
         'private_key': private_key
     }
     self.ssh.connect(**ssh_connect_dict)
示例#9
0
    def get_feedback_filter_params(self):
        # We need to be careful here because some of the filter_form params
        # are for FRs not the nested Feedback. If we include those and then
        # we edit the FR in a way where it no longer matches the params we'll
        # get a 404 as we'll exclude ourself. Given that we only want to pass
        # along params that are for Feedback.
        params_to_exclude = (
            "search",
            "state",
            "theme",
            "priority",
            "effort",
            "shipped_start_date",
            "shipped_end_date",
            "shipped_date_range",
        )
        filter_dict = self.get_filter_form().data
        qd = QueryDict(mutable=True)
        qd.update(filter_dict)
        for param_name in params_to_exclude:
            if param_name in qd:
                qd.pop(param_name)

        # HACK: there is surely a better way but the form returns empty values
        # here as None but when we urlencode that we get 'None'. DateField
        # doesn't like 'None' b/c it's not a valid date. So... here we just
        # turn None into '' which the form is happy with.
        if qd.get("feedback_date_range", None) is None:
            qd["feedback_date_range"] = ""
        if qd.get("feedback_start_date", None) is None:
            qd["feedback_start_date"] = ""
        if qd.get("feedback_end_date", None) is None:
            qd["feedback_end_date"] = ""

        return qd
示例#10
0
文件: websocket.py 项目: aixan/aixan
    def connect(self):
        """
        打开 websocket 连接, 通过前端传入的参数尝试连接 ssh 主机
        :return:
        """
        self.accept()

        query_string = self.scope.get('query_string')
        ssh_args = QueryDict(query_string=query_string, encoding='utf-8')

        width = int(ssh_args.get('width'))
        height = int(ssh_args.get('height'))

        id = ssh_args.get('id')
        host = Host.objects.get(id=id)

        self.ssh = SSH(websocker=self, message=self.message)

        ssh_connect_dict = {
            'host': host.hostname,
            'user': host.username,
            'port': host.port,
            'timeout': 30,
            'pty_width': width,
            'pty_height': height,
        }

        if host.pkey == '':
            private_key = AppSetting.get('private_key')
            ssh_connect_dict['ssh_key'] = private_key
        else:
            ssh_connect_dict['ssh_key'] = host.pkey

        self.ssh.connect(**ssh_connect_dict)
示例#11
0
    def update_apply_items(request, order_id):
        response = BaseResponse()
        update_data = QueryDict(request.body, encoding='utf-8')
        obj_id = update_data.get('obj_id')
        ipaddress = update_data.get('ipaddress')

        try:
            # 检查更新ip地址是否存在
            check_exist_server = models.Server.objects.filter(
                ipaddress=ipaddress)
            if not check_exist_server:
                get_item_from_db = models.ServerApplyDetail.objects.get(
                    id=obj_id)
                get_item_from_db.ipaddress = ipaddress
                get_item_from_db.approved = 2
                get_item_from_db.save()
            else:
                response.status = False
                response.message = 'This IP has already exist in CMDB, Please check again.'

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)

        return response
示例#12
0
 def connect(self):
     try:
         self.accept()
         query_string = self.scope['query_string']
         connet_argv = QueryDict(query_string=query_string,
                                 encoding='utf-8')
         webuser = connet_argv.get('user')
         id = connet_argv.get('id')
         host = PassWord.objects.get(uid=int(id))
         width = connet_argv.get('width')
         height = connet_argv.get('height')
         width = int(width)
         height = int(height)
         self.ssh = webssh_socket(websocker=self,
                                  message=self.message,
                                  webuser=webuser,
                                  host=host,
                                  width=width,
                                  height=height)
     except Exception as e:
         self.message['status'] = 1
         self.message['message'] = str(e)
         message = json.dumps(self.message)
         self.send(message)
         self.close()
示例#13
0
    def add_data(request):
        response = BaseResponse()
        try:
            response.error = []
            post_dict = QueryDict(request.body, encoding='utf-8')

            idc_name = post_dict.get('idc_name')
            idc_floor = post_dict.get('idc_floor')
            idc_phone = post_dict.get('idc_phone')
            idc_address = post_dict.get('idc_address')

            add_to_db = CMDB_MODELS.IDC(
                name=idc_name,
                floor=idc_floor,
                phone=idc_phone,
                idc_address = idc_address,

            )
            add_to_db.save()

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
示例#14
0
    def put_data(request):
        response = BaseResponse()
        try:
            post_dict = QueryDict(request.body, encoding='utf-8')

            obj_id = post_dict.get('obj_id', None)
            add_business_parent_id = post_dict.get('add_business_parent_id', None)
            add_business_name = post_dict.get('add_business_name')
            add_business_admin_list = post_dict.getlist('add_business_admin_list', [])
            add_business_contact_list = post_dict.getlist('add_business_contact_list', [])
            add_business_memo = post_dict.get('add_business_memo')

            edit_data_to_db = models.BusinessUnit.objects.get(id=obj_id)

            # 如果业务线包含子类,不允许更换至其他父级分组
            if not edit_data_to_db.parent_level.all():
                edit_data_to_db.parent_unit_id = add_business_parent_id
            else:
                response.message = "this is text."
            edit_data_to_db.name = add_business_name
            edit_data_to_db.memo = add_business_memo
            edit_data_to_db.save()

            edit_data_to_db.manager.clear()
            edit_data_to_db.contact.clear()

            for obj_id in add_business_admin_list:
                edit_data_to_db.manager.add(user_center_models.UserGroup.objects.get(id=obj_id))
            for obj_id in add_business_contact_list:
                edit_data_to_db.contact.add(user_center_models.UserGroup.objects.get(id=obj_id))

        except Exception as e:
            response.status = False
            response.message = str(e)
        return response
示例#15
0
    def add_data(self, request):
        response = BaseResponse()
        try:
            post_dict = QueryDict(request.body, encoding='utf-8')

            add_business_parent_id = post_dict.get('add_business_parent_id',
                                                   None)
            add_business_name = post_dict.get('add_business_name')
            add_business_admin_list = post_dict.getlist(
                'add_business_admin_list', [])
            add_business_contact_list = post_dict.getlist(
                'add_business_contact_list', [])
            add_business_memo = post_dict.get('add_business_memo')

            add_data_to_db = models.BusinessUnit(
                parent_unit_id=add_business_parent_id,
                name=add_business_name,
                memo=add_business_memo)

            add_data_to_db.save()

            for obj_id in add_business_admin_list:
                add_data_to_db.manager.add(
                    user_center_models.UserGroup.objects.get(id=obj_id))
            for obj_id in add_business_contact_list:
                add_data_to_db.contact.add(
                    user_center_models.UserGroup.objects.get(id=obj_id))

        except Exception as e:
            response.status = False
            response.message = str(e)
        return response
示例#16
0
    def connect(self):
        try:
            self.accept()
            query_string = self.scope['query_string']
            connet_argv = QueryDict(query_string=query_string,
                                    encoding='utf-8')
            unique = connet_argv.get('unique')
            width = connet_argv.get('width')
            height = connet_argv.get('height')

            width = int(width)
            height = int(height)

            connect_info = models.HostTmp.objects.get(unique=unique)

            host = connect_info.host
            port = connect_info.port
            user = connect_info.user
            auth = connect_info.auth
            pwd = connect_info.password
            pkey = connect_info.pkey

            connect_info.delete()

            if pwd:
                password = base64.b64decode(pwd).decode('utf-8')
            else:
                password = None

            self.ssh = SSH(websocker=self, message=self.message)

            if auth == 'key':
                pkey = pkey
                obj = StringIO()
                obj.write(pkey)
                obj.flush()
                obj.seek(0)
                self.pkey = obj

                self.ssh.connect(host=host,
                                 user=user,
                                 password=password,
                                 pkey=self.pkey,
                                 port=port,
                                 pty_width=width,
                                 pty_height=height)
            else:
                self.ssh.connect(host=host,
                                 user=user,
                                 password=password,
                                 port=port,
                                 pty_width=width,
                                 pty_height=height)
        except Exception as e:
            self.message['status'] = 1
            self.message['message'] = str(e)
            message = json.dumps(self.message)
            self.send(message)
            self.close()
示例#17
0
 def test_info_wizard_query_string_handling(self, event, client, track):
     # build query string
     params_dict = QueryDict(f"track={track.pk}&submission_type=academic_talk")
     current_url = "/test/submit/?{params_dict}"
     # Start wizard
     _, current_url = self.get_response_and_url(client, current_url, method="GET")
     # get query string from current URL
     url_parts = urlparse(current_url)
     q = QueryDict(url_parts.query)
     assert url_parts.path.endswith("/info/") is True
     assert q.get("track") == params_dict.get("academic")
     assert q.get("submission_type") == params_dict.get("academic_talk")
示例#18
0
    def init_from_get_params(self, get_params: QueryDict):
        try:
            date_from_str = get_params.get(self.GET_DATE_FROM, None)
            date_to_str = get_params.get(self.GET_DATE_TO, None)
            self.date_from = datetime.strptime(date_from_str, '%Y-%m-%d')
            self.date_to = datetime.strptime(date_to_str, '%Y-%m-%d')
        except (ValueError, TypeError):
            return False
        else:
            self._active = True

        return True
示例#19
0
    def delete_file(request, server_id):
        response = BaseResponse()

        post_dict = QueryDict(request.body, encoding='utf-8')
        delete_object_path = post_dict.get('delete_object_path')
        version = post_dict.get('version')

        file_handler = FileHandler.Manager(server_id, 'nginx', version)
        exec_status = file_handler.delete_items(delete_object_path)

        response.status = exec_status['status']
        response.message = exec_status['msg']
        return response
示例#20
0
 def connect(self):
     self.accept()
     query_string = self.scope.get('query_string')
     ssh_args = QueryDict(query_string=query_string, encoding='utf-8')
     encoded = ssh_args.get('identity', None)
     try:
         if not encoded:
             raise TypeError
         decoded = base64.b64decode(encoded)
         LOGGER.error(decoded)
         decoded = json.loads(decoded)
         username = decoded.get('username', None)
         uuid = decoded.get('uuid', None)
         token = decoded.get('token', None)
         if username is None or uuid is None or token is None:
             raise TypeError
         cols = ssh_args.get('cols', 80)
         rows = ssh_args.get('rows', 24)
         user = UserModel.objects.get(username=username)
         self.user = user
         settings = TaskSettings.objects.get(uuid=uuid)
     except (UserModel.DoesNotExist, TaskSettings.DoesNotExist):
         self.send("\nFailed to process.")
         self.close(code=4000)
         return
     except (TypeError, ValueError):
         self.send("\nInvalid request.")
         LOGGER.warning("Invalid request")
         self.close(code=4000)
         return
     real_token = TokenManager.get_token(user)
     if token == real_token:
         TokenManager.update_token(user)
     # try to fetch pod
     try:
         conn = connect('localhost', IPC_PORT)
         pod_name = conn.root.get_user_space_pod(uuid, user.uuid)
         username = '******'.format(user.username, settings.id)
         self.ssh = SSH(websocket=self,
                        cols=cols,
                        rows=rows,
                        need_auth=False)
         self.ssh.connect(
             pod_name,
             '/bin/bash',
             KUBERNETES_NAMESPACE,
             args=['-c', 'ulimit -u 35; su - {}'.format(username)])
     except Exception as ex:
         LOGGER.error(ex)
         self.send('Internal server error occurred.\n')
         self.close(code=4000)
示例#21
0
    def push_file(request, server_id):
        response = BaseResponse()
        current_version = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
        try:
            post_dict = QueryDict(request.body, encoding='utf-8')
            push_group_id = post_dict.get('push_group_id')
            push_memo = post_dict.get('push_memo')
            __push_version = 'last_version'
            __push_target_path = settings.web_config_nginx_path
            get_asset_from_select_group = CMDB_MODELS.Asset.objects.filter(
                instances__id=push_group_id).values('server__ipaddress')
            asset_list = list(get_asset_from_select_group)

            # 创建日志记录
            app_obj = repository_models.Applications.objects.get(id=server_id)
            mission_obj = repository_models.WebConfigLogs(
                app_id=app_obj,
                version=current_version,
                user=request.user,
                memo=push_memo)
            mission_obj.save()

            # 创建ip状态数据
            asset_obj_list = []  # 包含任务详情数据,一起传递给任务执行模块
            for ip_obj in asset_list:
                instance_obj = repository_models.WebConfigInstance(
                    mission_id_id=mission_obj.id,
                    ip=ip_obj.get('server__ipaddress'),
                )
                instance_obj.save()
                asset_obj_list.append(instance_obj)

            file_handler = FileHandler.Manager(server_id, 'nginx',
                                               __push_version)
            exec_status = file_handler.push_version(__push_target_path,
                                                    asset_obj_list)

            if exec_status['status']:
                # 发布完成后,将last_version拷贝至新的版本目录中
                file_handler.set_to_current_version(current_version)
                # 将version id 返回至前台,用于刷新右侧版本状态列表
                response.data = {
                    'version_id': mission_obj.id,
                    'version_name': current_version
                }

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
示例#22
0
    def add_mission(request):
        response = BaseResponse()
        post_dict = QueryDict(request.body, encoding='utf-8')
        mission_name = post_dict.get('mission_name')
        mission_type = post_dict.get('mission_type')
        project_name = post_dict.get('project_name')
        app_list = post_dict.getlist('app_list')

        print(post_dict)

        try:
            # create mission project.
            mission_project = repository_models.MissionProject(
                name = project_name
            )
            mission_project.save()

            # create mission app
            for app_id in app_list:

                mission_app = repository_models.MissionApp(
                    name=repository_models.Applications.objects.get(id=app_id).name
                )
                mission_app.save()

                # create app ip first.
                get_app_instances = repository_models.AppInstances.objects.filter(group_id__name='production', group_id__app_id__id=app_id, group_id__app_id__project_id__name=project_name).values()
                for instance_obj in get_app_instances:
                    mission_appinstance = repository_models.MissionAppInstance(
                        ip = instance_obj.get('ip')
                    )
                    mission_appinstance.save()
                    mission_app.ip.add(mission_appinstance)

                mission_project.app.add(mission_app)

            # create mission
            mission_create = repository_models.Mission(
                name = mission_name,
                mission_type = mission_type,
            )
            mission_create.save()
            mission_create.project.add(mission_project)

            response.data = {'mission_id': mission_create.id}
        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
示例#23
0
 def test_info_wizard_query_string_handling(self, event, client):
     # build query string
     params_dict = QueryDict('track=academic&submission_type=academic_talk')
     current_url = '/test/submit/?{params_dict}'
     # Start wizard
     _, current_url = self.get_response_and_url(client,
                                                current_url,
                                                method='GET')
     # get query string from current URL
     url_parts = urlparse(current_url)
     q = QueryDict(url_parts.query)
     assert url_parts.path.endswith('/info/') is True
     assert q.get('track') == params_dict.get('academic')
     assert q.get('submission_type') == params_dict.get('academic_talk')
示例#24
0
 def create_file(request, server_id):
     response = BaseResponse()
     try:
         post_dict = QueryDict(request.body, encoding='utf-8')
         obj_name = post_dict.get('create_object_name')
         obj_type = post_dict.get('create_object_type')
         obj_path = post_dict.get('create_object_path')
         version = post_dict.get('version')
         file_handler = FileHandler.Manager(server_id, 'nginx', version)
         exec_status = file_handler.create_items(obj_name, obj_path,
                                                 obj_type)
     except Exception as e:
         response.status = False
         response.message = str(e)
     return response
示例#25
0
def test_event_cfp_query_string_handling(client, event):
    """The link to the submission form should contain the query parameters
    given in the request URL."""
    params_dict = QueryDict("track=academic&submission_type=academic_talk")
    response = client.get(f"/{event.slug}/cfp?{params_dict}", )
    assert response.status_code == 200
    doc = bs4.BeautifulSoup(response.rendered_content, "lxml")
    info_btn = doc.select("a.btn-success")[0]
    href = info_btn.get("href")
    assert href is not None
    url_parts = urlparse(href)
    q = QueryDict(url_parts.query)
    assert url_parts.path.endswith("/submit/") is True
    assert q.get("track") == params_dict.get("academic")
    assert q.get("submission_type") == params_dict.get("academic_talk")
示例#26
0
    def get(self, request, *args, **kwargs):
        args_dict = request.GET.copy()
        args_dict.update({
            "test_suite_pk": kwargs["pk"],
            "measure_name": kwargs["mname"]
        })

        cmd = [
            settings.PYTHON_EXE,
            os.path.join(settings.BASE_DIR, "bin", "plot_png.py"),
            args_dict.urlencode(safe='/%')
        ]

        print "Plot png: %s" % cmd[-1]

        result = subprocess.check_output(cmd, env=os.environ.copy()).strip()

        qdict = QueryDict(result)
        fname = qdict.get("fname")
        alarm = qdict.get("alarm")

        if fname and fname != "":
            f = open(fname, 'rb')
            response = HttpResponse(f.read(), 'image/png')
            f.close()
            m_path = reverse('appmonitor:measure',
                             args=[kwargs["pk"], kwargs["mname"]])
            response.set_cookie("alarm_state", alarm, path=m_path)
            return response
        else:
            f = open('appmonitor/static/appmonitor/nodata.png', 'rb')
            response = HttpResponse(f.read(), 'image/png')
            f.close()
            return response
示例#27
0
 def set_last_version(request, server_id):
     response = BaseResponse()
     post_dict = QueryDict(request.body, encoding='utf-8')
     version = post_dict.get('version')
     file_handler = FileHandler.Manager(server_id, 'nginx', version)
     file_handler.set_to_last_version()
     return response
示例#28
0
def get_filters(data: QueryDict) -> Dict:
    return {
        "user_id":
        data.get("user_id"),
        "team":
        data.get("team_id"),
        "user_type":
        UserType(data["user_type"]) if data.get("user_type") else None,
        "audit_type":
        AuditType(data["activity_type"])
        if data.get("activity_type") else None,
        "date_from":
        make_date_from_params("from", data),
        "date_to":
        make_date_from_params("to", data),
    }
示例#29
0
文件: views.py 项目: qiangayz/HiCmdb
 def put(self, request, *args, **kwargs):
     content = request.body.decode()
     put_dict = QueryDict(request.body, encoding='utf-8')
     update_list = json.loads(put_dict.get('post_list'))
     print(update_list)
     ret = {'status': False, 'message': '123123123'}
     return HttpResponse(json.dumps(ret))
示例#30
0
    def put_assets(request):
        response = BaseResponse()
        print('save')
        try:
            put_dict = QueryDict(request.body,encoding='utf-8')
            print(put_dict)
            update_list = json.loads(put_dict.get('update_list'))
            error_count = 0
            print(update_list)
            for row_dict in update_list:

                nid = row_dict.pop('nid')
                num = row_dict.pop('num')
                print(row_dict)
                try:
                    print(models.Asset.objects.filter(ni=nid).values())
                    models.Asset.objects.filter(ni=nid).update(**row_dict)
                except Exception as e:
                    response.error.append({'num':num,'message':str(e)})
                    response.status = False
                    error_count +=1
                if error_count:
                    response.message = '共%s条,失败%s条' % (len(update_list), error_count,)
                else:
                    response.message = '更新成功'
            print(update_list)
        except Exception as e:
            response.status =False
            response.message = str(e)

        return response
示例#31
0
 def put_queryset(self, request):
     response = BaseResponse()
     try:
         response.error = []
         put_dict = QueryDict(request.body, encoding='utf-8')
         update_list = json.loads(put_dict.get('update_list'))
         error_count = 0
         for row_dict in update_list:
             nid = row_dict.pop('nid')
             num = row_dict.pop('num')
             try:
                 self.queryset.filter(id=nid).update(**row_dict)
             except Exception as e:
                 response.error.append({'num': num, 'message': str(e)})
                 response.status = False
                 error_count += 1
         if error_count:
             response.message = '共%s条,失败%s条' % (
                 len(update_list), error_count,)
         else:
             response.message = '更新成功'
     except Exception as e:
         response.status = False
         response.message = str(e)
     return response
示例#32
0
    def get(self, request, *args, **kwargs):
        args_dict = request.GET.copy()
        args_dict.update({
            "test_suite_pk": kwargs["pk"],
            "measure_name": kwargs["mname"]
        })

        cmd = [
            settings.PYTHON_EXE,
            os.path.join(settings.BASE_DIR, "bin", "plot_png.py"),
            args_dict.urlencode(safe='/%')
        ]

        print "Plot png: %s" % cmd[-1]

        result = subprocess.check_output(cmd, env=os.environ.copy()).strip()

        qdict = QueryDict(result)
        fname = qdict.get("fname")
        alarm = qdict.get("alarm")

        if fname and fname != "":
            f = open(fname, 'rb')
            response = HttpResponse(f.read(), 'image/png')
            f.close()
            m_path = reverse(
                'appmonitor:measure', args=[kwargs["pk"], kwargs["mname"]]
            )
            response.set_cookie("alarm_state", alarm, path=m_path)
            return response
        else:
            f = open('appmonitor/static/appmonitor/nodata.png', 'rb')
            response = HttpResponse(f.read(), 'image/png')
            f.close()
            return response
示例#33
0
    def data_create(request):
        response = BaseResponse()
        try:
            post_data = QueryDict(request.body, encoding='utf-8')
            role_name = post_data.get('role_name')
            role_memo = post_data.get('role_memo')
            permission_list = post_data.getlist('permission_list')

            # 创建role
            data_obj = USER_CENTER_MODELS.Roles(
                name=role_name,
                memo=role_memo,
            )
            data_obj.save()

            # 关联permission
            for obj_id in permission_list:
                data_obj.permissions.add(obj_id)

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)

        return response
示例#34
0
    def data_create(request):
        response = BaseResponse()
        try:
            post_data = QueryDict(request.body, encoding='utf-8')
            role_name = post_data.get('role_name')
            role_memo = post_data.get('role_memo')
            permission_list = post_data.getlist('permission_list')

            # 创建role
            data_obj = USER_CENTER_MODELS.Roles(
                name=role_name,
                memo=role_memo,
            )
            data_obj.save()

            # 关联permission
            for obj_id in permission_list:
                data_obj.permissions.add(obj_id)

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)

        return response
示例#35
0
    def connect(self):
        self.accept()
        self.session = self.scope.get('session', None)
        if not self.session.get('islogin', None):  # 未登录直接断开 websocket 连接
            self.message['status'] = 2
            self.message['message'] = 'You are not login in...'
            message = json.dumps(self.message)
            self.send(message)
            self.close()
        query_string = self.scope.get('query_string').decode()
        args = QueryDict(query_string=query_string, encoding='utf-8')
        self.group = args.get('group')

        try:
            TerminalSession.objects.get(group=self.group)
        except Exception:
            print(traceback.format_exc())
            self.message['status'] = 2
            self.message['message'] = 'session group is not exist...'
            message = json.dumps(self.message)
            self.send(message)
            self.close()
        async_to_sync(self.channel_layer.group_add)(self.group,
                                                    self.channel_name)  # 加入组
        message = dict()
        message['status'] = 4
        message['message'] = self.channel_name
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(self.group, {
            "type": "chat.message",
            "text": json.dumps(message),
        })
示例#36
0
    def delete_server_instance(request):
        response = BaseResponse()
        try:
            response.error = {}
            post_dict = QueryDict(request.body, encoding='utf-8')

            group_id = post_dict.get('group_id')
            docker_id = post_dict.get('docker_id')

            add_to_db = repository_models.AppGroups.objects.get(id=group_id)
            add_to_db.docker.remove(CMDB_MODELS.DockerInstance.objects.get(id=docker_id))

        except Exception as e:
            response.status = False
            response.message = str(e)
        return response
示例#37
0
    def asset_data_create(request):
        response = BaseResponse()
        try:
            asset_data = QueryDict(request.body, encoding='utf-8')
            new_asset_num = asset_num.asset_num_builder()
            asset_sn = asset_data.get('sn')

            try:
                Memory = int(asset_data.get('Memory'))
            except:
                Memory = None
            try:
                DeviceSize = int(asset_data.get('DeviceSize'))
            except:
                DeviceSize = None
            try:
                cpu_count = int(asset_data.get('cpu_count'))
            except:
                cpu_count = None

            if not asset_sn:
                asset_sn = new_asset_num

            # 创建asset obj
            asset_obj = models.Asset(
                device_type_id = asset_data.get('device_type_id'),
                asset_num = new_asset_num,
                sn = asset_sn,
                idc_id = asset_data.get('idc_id'),
                business_unit_id = asset_data.get('business_unit_id'),
            )
            asset_obj.save()

            # 创建server obj
            server_obj = models.Server(
                asset_id = asset_obj.id,
                hostname = asset_data.get('hostname'),
                ipaddress = asset_data.get('ipaddress'),
                manage_ip = asset_data.get('manage_ip'),
                Memory = Memory,
                DeviceSize = DeviceSize,
                cpu_count = cpu_count,
            )
            server_obj.save()

            response.message = '获取成功'
        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)

        return response
示例#38
0
    def asset_data_create(request):
        response = BaseResponse()
        try:
            asset_data = QueryDict(request.body, encoding='utf-8')
            new_asset_num = asset_num.asset_num_builder()
            asset_sn = asset_data.get('sn')

            try:
                Memory = int(asset_data.get('Memory'))
            except:
                Memory = None
            try:
                DeviceSize = int(asset_data.get('DeviceSize'))
            except:
                DeviceSize = None
            try:
                cpu_count = int(asset_data.get('cpu_count'))
            except:
                cpu_count = None

            if not asset_sn:
                asset_sn = new_asset_num

            # 创建asset obj
            asset_obj = models.Asset(
                device_type_id=asset_data.get('device_type_id'),
                asset_num=new_asset_num,
                sn=asset_sn,
                idc_id=asset_data.get('idc_id'),
                business_unit_id=asset_data.get('business_unit_id'),
            )
            asset_obj.save()

            # 创建server obj
            server_obj = models.Server(
                asset_id=asset_obj.id,
                hostname=asset_data.get('hostname'),
                ipaddress=asset_data.get('ipaddress'),
                manage_ip=asset_data.get('manage_ip'),
                Memory=Memory,
                DeviceSize=DeviceSize,
                cpu_count=cpu_count,
            )
            server_obj.save()

            response.message = '获取成功'
        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)

        return response
示例#39
0
文件: consumers.py 项目: nav/presence
def ws_connect(message):
    query = QueryDict(message.content['query_string'])
    page = query.get('page')
    email_hash = get_email_hash(query.get('user'))

    Group("presence").add(message.reply_channel)

    presence = cache.get(PRESENCE_CACHE_KEY, dict())
    if page in presence:
        presence[page].append(email_hash)
    else:
        presence[page] = [email_hash]
    cache.set(PRESENCE_CACHE_KEY, presence, PRESENCE_CACHE_TIMEOUT)

    Group("presence").send({
        "text": json.dumps(presence),
    })
示例#40
0
    def update_yaml_conf(self, request):
        response = BaseResponse()
        try:
            response.error = {}
            post_dict = QueryDict(request.body, encoding='utf-8')

            update_group_id = post_dict.get('group_id')
            yaml_conf_data = post_dict.get('yaml_conf_data')

            get_yaml_from_db = repository_models.DockerYamlConf.objects.get(group_id__id=update_group_id)
            get_yaml_from_db.yaml_data = json.dumps(self.__yaml_to_json(yaml_conf_data))
            get_yaml_from_db.save()

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
示例#41
0
    def put_data(request):
        response = BaseResponse()
        try:
            response.error = []
            put_dict = QueryDict(request.body, encoding='utf-8')
            user_id = put_dict.get('group_id')
            group_name = put_dict.get('group_name')

            update_data = user_models.UserGroup.objects.get(id=user_id)

            update_data.name = group_name
            update_data.save()

        except Exception as e:
            print(Exception,e)
            response.status = False
            response.message = str(e)
        return response
示例#42
0
    def add_server_instance(request):
        response = BaseResponse()
        try:
            response.error = {}
            post_dict = QueryDict(request.body, encoding='utf-8')
            print(post_dict)

            add_instance_group_id = post_dict.get('add_instance_group_id')
            add_instance_id = post_dict.get('add_instance_id')

            add_to_db = repository_models.AppGroups.objects.get(id=add_instance_group_id)
            add_to_db.instance.add(CMDB_MODELS.Asset.objects.get(id=add_instance_id))

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
示例#43
0
    def data_update(request):
        response = BaseResponse()
        try:
            put_data = QueryDict(request.body, encoding='utf-8')
            obj_id = put_data.get('obj_id')
            url_name = put_data.get('url_name')
            url_method = put_data.get('url_method')
            memo = put_data.get('memo')

            update_data = USER_CENTER_MODELS.Permission.objects.get(id=obj_id)
            update_data.url_name = url_name
            update_data.url_method = url_method
            update_data.memo = memo
            update_data.save()

        except Exception as e:
            response.status = False
            response.message = str(e)
        return response
示例#44
0
    def put_assets(request):
        response = BaseResponse()
        try:
            response.error = []
            put_dict = QueryDict(request.body, encoding='utf-8')
            project_id = put_dict.get('project_id')
            project_name = put_dict.get('project_name')
            business_unit_id = put_dict.get('business_unit_id')

            update_data = repository_models.ProjectInfo.objects.get(id=project_id)
            update_data.name = project_name
            update_data.business_unit = CMDB_MODELS.BusinessUnit.objects.get(id=business_unit_id)
            update_data.save()

        except Exception as e:
            print(Exception,e)
            response.status = False
            response.message = str(e)
        return response
示例#45
0
    def update_server_instance(request):
        response = BaseResponse()
        try:
            response.error = {}
            post_dict = QueryDict(request.body, encoding='utf-8')

            docker_group_id = post_dict.get('docker_group_id')
            new_docker_id = post_dict.get('new_docker_id')
            old_docker_id = post_dict.get('old_docker_id')

            get_group_from_db = repository_models.AppGroups.objects.get(id=docker_group_id)
            get_group_from_db.docker.remove(CMDB_MODELS.DockerInstance.objects.get(id=old_docker_id))
            get_group_from_db.docker.add(CMDB_MODELS.DockerInstance.objects.get(id=new_docker_id))

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
示例#46
0
    def update_server_logs(request):
        response = BaseResponse()
        try:
            response.error = {}
            post_dict = QueryDict(request.body, encoding='utf-8')

            log_id = post_dict.get('log_id')
            add_server_log_url = post_dict.get('add_server_log_url')
            add_server_log_memo = post_dict.get('add_server_log_memo')

            get_logs_from_db = repository_models.WebConfigLogsCenter.objects.get(id=log_id)
            get_logs_from_db.url = add_server_log_url
            get_logs_from_db.memo = add_server_log_memo
            get_logs_from_db.save()

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
示例#47
0
 def delete_data(request):
     response = BaseResponse()
     try:
         recv_data = QueryDict(request.body, encoding='utf-8')
         idc_id = recv_data.get("idc_id")
         CMDB_MODELS.IDC.objects.get(id=idc_id).delete()
         response.message = '删除成功'
     except Exception as e:
         response.status = False
         response.message = str(e)
     return response
示例#48
0
 def delete_data(request):
     response = BaseResponse()
     try:
         recv_data = QueryDict(request.body, encoding='utf-8')
         user_id = recv_data.get("user_id")
         user_models.UserProfile.objects.get(id=user_id).delete()
         response.message = '删除成功'
     except Exception as e:
         response.status = False
         response.message = str(e)
     return response
示例#49
0
    def update_server_group(request):
        response = BaseResponse()
        try:
            response.error = {}
            post_dict = QueryDict(request.body, encoding='utf-8')

            update_group_id = post_dict.get('group_id')
            add_group_name = post_dict.get('add_group_name')
            add_group_yaml_path = post_dict.get('add_group_yaml_path')

            get_group_from_db = repository_models.AppGroups.objects.get(id=update_group_id)
            get_group_from_db.name = add_group_name
            get_group_from_db.yaml_path = add_group_yaml_path
            get_group_from_db.save()

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
示例#50
0
    def bond_public_group(request):
        response = BaseResponse()

        try:
            post_dict = QueryDict(request.body, encoding='utf-8')

            add_group_app_id = post_dict.get('add_group_app_id')
            public_group_id = post_dict.get('public_group_id')

            print(public_group_id)

            get_group_from_db = models.AppGroups.objects.get(id=public_group_id)
            print(get_group_from_db)
            get_group_from_db.app_id.add(repository_models.Applications.objects.get(id=add_group_app_id))

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
示例#51
0
 def delete_data(request):
     response = BaseResponse()
     try:
         delete_dict = QueryDict(request.body, encoding='utf-8')
         obj_id = delete_dict.get('obj_id')
         models.BusinessUnit.objects.filter(id=obj_id).delete()
         response.message = '删除成功'
     except Exception as e:
         response.status = False
         response.message = str(e)
     return response
示例#52
0
 def delete_data(request):
     response = BaseResponse()
     try:
         recv_data = QueryDict(request.body, encoding='utf-8')
         project_id = recv_data.get("project_id")
         repository_models.ProjectInfo.objects.get(id=project_id).delete()
         response.message = '删除成功'
     except Exception as e:
         response.status = False
         response.message = str(e)
     return response
示例#53
0
 def data_delete(request):
     response = BaseResponse()
     try:
         delete_data = QueryDict(request.body, encoding='utf-8')
         obj_id = delete_data.get('obj_id')
         USER_CENTER_MODELS.Roles.objects.get(id=obj_id).delete()
         response.message = '删除成功'
     except Exception as e:
         response.status = False
         response.message = str(e)
     return response
示例#54
0
    def put_assets(request):
        response = BaseResponse()
        try:
            response.error = []
            put_dict = QueryDict(request.body, encoding='utf-8')
            server_id = put_dict.get('server_id')
            app_name = put_dict.get('app_name')
            project_id = put_dict.get('project_id')
            app_type = put_dict.get('app_type')

            update_data = repository_models.Applications.objects.get(id=server_id)
            update_data.name = app_name
            update_data.project_id = repository_models.ProjectInfo.objects.get(id=project_id)
            update_data.app_type = app_type
            update_data.save()

        except Exception as e:
            print(Exception,e)
            response.status = False
            response.message = str(e)
        return response
示例#55
0
    def get_app_by_project(request):
        response = BaseResponse()
        post_dict = QueryDict(request.body, encoding='utf-8')
        project_id = post_dict.get('project_id')
        try:
            data_list = repository_models.Applications.objects.filter(project_id__id=project_id).values()
            response.data = list(data_list)

        except Exception as e:
            response.status = False
            response.message = str(e)
        return response
示例#56
0
    def update_server_instance(request):
        response = BaseResponse()
        try:
            response.error = {}
            post_dict = QueryDict(request.body, encoding='utf-8')

            instance_id = post_dict.get('instance_id')
            add_instance_group_id = post_dict.get('add_instance_group_id')
            add_instance_ip = post_dict.get('add_instance_ip')
            add_instance_port = post_dict.get('add_instance_port')

            get_instance_from_db = repository_models.AppInstances.objects.get(id=instance_id)
            get_instance_from_db.group_id = repository_models.AppGroups.objects.get(id=add_instance_group_id)
            get_instance_from_db.ip = add_instance_ip
            get_instance_from_db.port = add_instance_port
            get_instance_from_db.save()

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
示例#57
0
    def add_data(request):
        response = BaseResponse()
        try:
            response.error = []
            post_dict = QueryDict(request.body, encoding='utf-8')

            print(post_dict)
            project_name = post_dict.get('project_name')
            business_unit_id = post_dict.get('business_unit_id')

            add_to_db = repository_models.ProjectInfo(
                name=project_name,
                business_unit=CMDB_MODELS.BusinessUnit.objects.get(id=business_unit_id),

            )
            add_to_db.save()

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
示例#58
0
    def add_server_logs(request):
        response = BaseResponse()
        try:
            response.error = {}
            post_dict = QueryDict(request.body, encoding='utf-8')

            add_logs_group_id = post_dict.get('add_logs_group_id')
            add_server_log_url = post_dict.get('add_server_log_url')
            add_server_log_memo = post_dict.get('add_server_log_memo')

            add_to_db = repository_models.WebConfigLogsCenter(
                group_id_id = add_logs_group_id,
                url = add_server_log_url,
                memo = add_server_log_memo
            )
            add_to_db.save()

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response