Example #1
0
    def process(server_obj, server_info, user_obj):
        response = BaseResponse()
        try:
            disk_info = server_info['disk']
            if not disk_info['status']:
                response.status = False
                models.ErrorLog.objects.create(asset_obj=server_obj.asset, title='disk-agent',
                                               content=disk_info['error'])
                return response

            client_disk_dict = disk_info['data']

            disk_obj_list = models.Disk.objects.filter(server_obj=server_obj)

            disk_slots = map(lambda x: x, (item.slot for item in disk_obj_list))

            update_list = agorithm.get_intersection(set(client_disk_dict.keys()), set(disk_slots))
            add_list = agorithm.get_exclude(client_disk_dict.keys(), update_list)
            del_list = agorithm.get_exclude(disk_slots, update_list)

            HandleDisk._add_disk(add_list, client_disk_dict, server_obj, user_obj)
            HandleDisk._update_disk(update_list, disk_obj_list, client_disk_dict, server_obj, user_obj)
            HandleDisk._del_disk(del_list, disk_obj_list, server_obj, user_obj)

        except Exception as e:
            response.status = False
            models.ErrorLog.objects.create(asset_obj=server_obj.asset, title='disk-run', content=traceback.format_exc())
        return response
Example #2
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
Example #3
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
Example #4
0
    def fetch_user(self, request):
        response = BaseResponse()
        try:
            ret = {}
            conditions = self.assets_condition(request)
            user_count = user_models.UserProfile.objects.filter(conditions).count()
            page_info = PageInfo(request.GET.get('pager', None), user_count)
            user_list = user_models.UserProfile.objects.filter(conditions).extra(select=self.extra_select).values(
                *self.values_list).order_by("-id")[page_info.start:page_info.end]
            ret['table_config'] = self.table_config
            ret['condition_config'] = self.condition_config
            ret['data_list'] = list(user_list)
            ret['page_info'] = {
                "page_str": page_info.pager(),
                "page_start": page_info.start,
            }
            ret['global_dict'] = {
                "group_list": self.group_list
            }

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

        return response
Example #5
0
def get_untreated_servers():
    """
    获取未采集的资产
    :return:
    """
    response = BaseResponse()

    try:
        current_date = datetime.datetime.today()
        condition = Q()

        # 今日未采集的资产
        con_date = Q()
        con_date.connector = 'OR'
        con_date.children.append(('asset__latest_date__lt',current_date))
        con_date.children.append(('asset__latest_date',None))

        # 在线状态的服务器
        con_status = Q()
        con_status.children.append(('asset__device_status_id','2'))

        condition.add(con_date,'AND')
        condition.add(con_status,'AND')

        result = models.Server.objects.filter(condition).values('hostname')

        response.data = list(result)
        response.status = True

    except Exception as e:
        response.message = str(e)
        models.ErrorLog.objects.create(asset_obj=None,title='get_untreated_servers',content=traceback.format_exc())


    return response
Example #6
0
    def fetch_data(self, request):
        response = BaseResponse()
        try:
            ret = {}
            conditions = self.assets_condition(request)
            asset_count = USER_CENTER_MODELS.Roles.objects.filter(conditions).count()
            page_info = PageInfo(request.GET.get('pager', None), asset_count)
            asset_list = USER_CENTER_MODELS.Roles.objects.filter(conditions).extra(
                select=self.extra_select).values(
                *self.values_list)[page_info.start:page_info.end]

            ret['table_config'] = self.table_config
            ret['condition_config'] = self.condition_config
            ret['data_list'] = list(asset_list)
            ret['page_info'] = {
                "page_str": page_info.pager(),
                "page_start": page_info.start,
            }
            ret['global_dict'] = {
                'url_method_list': self.url_method_list,
            }
            response.data = ret
            response.message = '获取成功'
        except Exception as e:
            response.status = False
            response.message = str(e)

        return response
Example #7
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
Example #8
0
    def fetch_assets(self, request):
        response = BaseResponse()
        try:
            ret = {}
            conditions = self.assets_condition(request)
            asset_count = models.Asset.objects.filter(conditions).count()
            page_info = PageInfo(request.GET.get('pager', None), asset_count)
            asset_list = models.Asset.objects.filter(conditions).extra(select=self.extra_select).values(
                *self.values_list)[page_info.start:page_info.end]

            ret['table_config'] = self.table_config
            ret['condition_config'] = self.condition_config
            ret['data_list'] = list(asset_list)
            ret['page_info'] = {
                "page_str": page_info.pager(),
                "page_start": page_info.start,
            }
            ret['global_dict'] = {
                'device_status_list': self.device_status_list,
                'device_type_list': self.device_type_list,
                'idc_list': self.idc_list,
                'business_unit_list': self.business_unit_list,
                'status_map': self.status_map
            }
            response.data = ret
            response.message = '获取成功'
        except Exception as e:
            response.status = False
            response.message = str(e)

        return response
Example #9
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
Example #10
0
 def get_instance_by_id(request):
     response = BaseResponse()
     instance_id = request.GET.get('instance_id')
     get_edit_instance_data = repository_models.AppInstances.objects.filter(id=instance_id).values("id", "ip", "port", "group_id__name", "group_id__id")
     response.data = list(get_edit_instance_data)
     print(response.data)
     return response.data
Example #11
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
Example #12
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
Example #13
0
    def process(server_obj, server_info, user_obj):
        response = BaseResponse()
        try:
            mem_info = server_info['memory']
            if not mem_info['status']:
                models.ErrorLog.objects.create(asset_obj=server_obj.asset, title='memory-agent',
                                               content=mem_info['error'])
                response.status = False
                return response

            client_mem_dict = mem_info['data']

            mem_obj_list = models.Memory.objects.filter(server_obj=server_obj)

            mem_slots = map(lambda x: x, (item.slot for item in mem_obj_list))

            update_list = agorithm.get_intersection(set(client_mem_dict.keys()), set(mem_slots))
            add_list = agorithm.get_exclude(client_mem_dict.keys(), update_list)
            del_list = agorithm.get_exclude(mem_slots, update_list)

            HandleMemory._add_memory(add_list, client_mem_dict, server_obj, user_obj)
            HandleMemory._update_memory(update_list, mem_obj_list, client_mem_dict, server_obj, user_obj)
            HandleMemory._del_memory(del_list, mem_obj_list, server_obj, user_obj)
        except Exception as e:
            response.status = False
            models.ErrorLog.objects.create(asset_obj=server_obj.asset, title='memory-run',
                                           content=traceback.format_exc())

        return response
Example #14
0
    def process(server_obj,server_info,user_obj):
        response = BaseResponse()
        try:
            # 获取数据库中所有网卡信息
            # server_info 服务器最新汇报的数据
            nic_info = server_info['nic']
            if not nic_info['status']:
                response.status = False
                models.ErrorLog.objects.create(asset_obj=server_obj.asset,title='nic-agent',content=nic_info['error'])
                return response

            client_nic_dict = nic_info['data']
            nic_obj_list = models.NIC.objects.filter(server_obj=server_obj)
            nic_name_list = map(lambda x:x,(item.name for item in nic_obj_list))

            update_list = agorithm.get_intersection(set(client_nic_dict.keys()),set(nic_name_list))
            add_list = agorithm.get_exclude(client_nic_dict.keys(),update_list)
            del_list = agorithm.get_exclude(nic_name_list,update_list)

            # 删除 更新 添加操作
            HandleNic._add_nic(add_list, client_nic_dict, server_obj, user_obj)
            HandleNic._update_nic(update_list, nic_obj_list, client_nic_dict, server_obj, user_obj)
            HandleNic._del_nic(del_list, nic_obj_list, server_obj, user_obj)


        except Exception as e:
            response.status = False
            response.error = str(e)
            models.ErrorLog.objects.create(asset_obj=server_obj.asset,title='nic-run',content=traceback.format_exc())

        return response
Example #15
0
 def get_group_info(request):
     response = BaseResponse()
     try:
         response.data = user_models.UserGroup.objects.all()
     except Exception as e:
         response.status = False
         response.message = str(e)
     return response
Example #16
0
 def get_project_info(request):
     response = BaseResponse()
     try:
         response.data = repository_models.ProjectInfo.objects.all()
     except Exception as e:
         response.status = False
         response.message = str(e)
     return response
Example #17
0
    def get_server_urlmaps(server_id):
        response = BaseResponse()
        try:
            response.data = models.Applications.objects.filter(id=server_id).first()

        except Exception as e:
            response.status = False
            response.message = str(e)
        return response
Example #18
0
    def get_data_by_id(url_nid):
        response = BaseResponse()
        try:
            response.data = USER_CENTER_MODELS.Permission.objects.filter(id=url_nid).first()

        except Exception as e:
            response.status = False
            response.message = str(e)
        return response
Example #19
0
    def get_buesiness_detail(business_nid):
        response = BaseResponse()
        try:
            response.data = models.BusinessUnit.objects.get(id=business_nid)

        except Exception as e:
            response.status = False
            response.message = str(e)
        return response
Example #20
0
    def get_permission_data():

        response = BaseResponse()
        try:
            response.data = USER_CENTER_MODELS.Permission.objects.all().order_by('-id')

        except Exception as e:
            response.status = False
            response.message = str(e)
        return response
Example #21
0
 def get_instance_by_groupid(request):
     response = BaseResponse()
     group_id = request.GET.get('group_id')
     group_type = request.GET.get('group_type')
     if group_type == 'docker':
         get_instance_data = CMDB_MODELS.DockerInstance.objects.filter(dockers__id=group_id).values("id", 'asset__server__ipaddress', 'port')
     else:
         get_instance_data = CMDB_MODELS.Asset.objects.filter(instances__id=group_id).values("id", "server__ipaddress")
     response.data = list(get_instance_data)
     return response
Example #22
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
Example #23
0
    def idc_config(idc_id):

        response = BaseResponse()
        try:
            response.data = CMDB_MODELS.IDC.objects.filter(id=idc_id).first()
            # response.asset_data = CMDB_MODELS.Asset.objects.all()
        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
Example #24
0
    def assets_detail(asset_id):

        response = BaseResponse()
        try:
            print(asset_id)
            response.data = models.Asset.objects.filter(id=asset_id).first()

        except Exception as e:
            response.status = False
            response.message = str(e)
        return response
Example #25
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
Example #26
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
Example #27
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
Example #28
0
 def delete_assets(request):
     response = BaseResponse()
     try:
         delete_dict = QueryDict(request.body, encoding='utf-8')
         id_list = delete_dict.getlist('id_list')
         models.Asset.objects.filter(id__in=id_list).delete()
         response.message = '删除成功'
     except Exception as e:
         response.status = False
         response.message = str(e)
     return response
Example #29
0
    def group_config(group_id):

        response = BaseResponse()
        try:
            response.data = user_models.UserGroup.objects.filter(id=group_id).first()

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
Example #30
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
Example #31
0
    def data_create(request):
        response = BaseResponse()
        try:
            post_data = QueryDict(request.body, encoding='utf-8')
            url_name = post_data.get('url_name')
            url_method = post_data.get('url_method')
            url_memo = post_data.get('url_memo')

            # 创建url permission
            data_obj = USER_CENTER_MODELS.Permission(
                url_name=url_name,
                url_method=url_method,
                memo=url_memo,
            )
            data_obj.save()

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

        return response
Example #32
0
    def get_apply_json(request, order_id):
        response = BaseResponse()

        try:
            order_obj = models.ServerApplyOrder.objects.get(id=order_id)
            get_order_detail_from_db = models.ServerApplyDetail.objects.filter(
                server_apply_order__id=order_id).values()
            for asset_obj in get_order_detail_from_db:
                business_obj = models.BusinessUnit.objects.filter(
                    id=order_obj.business)
                if business_obj:
                    asset_obj['business'] = business_node_top(business_obj[0])
                else:
                    asset_obj['business'] = '-'
            response.data = list(get_order_detail_from_db)

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

        return response
Example #33
0
 def delete_backup(request):
     # pass
     response = BaseResponse()
     # try:
     #     delete_dict = QueryDict(request.body, encoding='utf-8')
     #     id_list = delete_dict.getlist('id_list')
     #     models.MysqlInitInfo.objects.filter(id__in=id_list).delete()
     #     response.message = '删除成功'
     #     pass
     # except Exception as e:
     #     response.status = False
     #     response.message = str(e)
     return response
Example #34
0
    def get(self, request, *args, **kwargs):
        """返回结算中心页面"""
        res_obj = BaseResponse()
        user_id = request.user.id
        checkout_list_value = cache.get(f'CHECKOUT_LIST_{user_id}')
        if not checkout_list_value:
            res_obj.code = 3004
            res_obj.msg = '暂无结算信息'
            logger.warning('no checkout info.')
            return Response(res_obj.dict)
        checkout_list = json.loads(checkout_list_value)

        # 获取通用优惠券
        common_coupon_value = cache.get(f'COMMON_COUPON_LIST_{user_id}')
        common_coupon_value = json.loads(
            common_coupon_value) if common_coupon_value else []

        res_obj.data = {
            'checkout_list': checkout_list,
            'common_coupon_list': common_coupon_value
        }
        return Response(res_obj.dict)
Example #35
0
 def delete_assets(request):
     response = BaseResponse()
     try:
         delete_dict = QueryDict(request.body, encoding='utf-8')
         id_list = delete_dict.getlist('id_list')
         status = models.ReleaseTask.objects.filter(
             id=id_list[0]).first().release_status
         # if status != 4:
         #     response.status = False
         #     response.message = '非待审核状态不能删除'
         # else:
         # 不删除 标记为取消状态
         # models.ReleaseTask.objects.filter(id__in=id_list).delete()
         models.ReleaseTask.objects.filter(id__in=id_list).update(
             release_status=8)
         user = request.session['username']
         audit_log(id_list, '[ %s ] 撤销发布申请' % user)
         response.message = '删除成功'
     except Exception as e:
         response.status = True
         # response.message = str(e)
     return response
Example #36
0
    def get(self,request,*args,**kwargs):

        ret = BaseResponse()

        try:
            # luffy_payment_1_*
            redis_payment_key = settings.PAYMENT_KEY %(request.auth.user_id,"*",)

            # luffy_payment_coupon_1
            redis_global_coupon_key = settings.PAYMENT_COUPON_KEY %(request.auth.user_id,)

            # 1. 获取绑定课程信息
            course_list = []
            for key in self.conn.scan_iter(redis_payment_key):
                info = {}
                data = self.conn.hgetall(key)
                for k,v in data.items():
                    kk = k.decode('utf-8')
                    if kk == "coupon":
                        info[kk] = json.loads(v.decode('utf-8'))
                    else:
                        info[kk] = v.decode('utf-8')
                course_list.append(info)

            # 2.全站优惠券
            global_coupon_dict = {
                'coupon':json.loads(self.conn.hget(redis_global_coupon_key,'coupon').decode('utf-8')),
                'default_coupon':self.conn.hget(redis_global_coupon_key,'default_coupon').decode('utf-8')
            }

            ret.data = {
                "course_list":course_list,
                "global_coupon_dict":global_coupon_dict
            }
        except Exception as e:
            ret.code = 1001
            ret.error = "获取失败"

        return Response(ret.dict)
Example #37
0
    def post(self, request):
        """
        修改配置文件
        :param request:
        :return:
        """
        response = BaseResponse()

        # 新增配置文件
        new_file = request.POST.get('new_file', None)
        if new_file:
                business_id = request.POST.get('business_id', None)
                business_obj = models.BusinessTwo.objects.filter(id=business_id).first()
                business_name = business_obj.name
                file = '%sprod/%s/%s' % (jenkins_config.config_path, business_name, new_file)
                file_dir = os.path.dirname(file)
                if not os.path.exists(file_dir):
                    os.system('mkdir -p %s' % file_dir)
                cmd = 'touch %s' % file
                os.system(cmd)
                response.status = True

        # 修改配置文件
        business_id = request.POST.get('business_id', None)
        file_name = request.POST.get('file_name', None)
        file_content = request.POST.get('file_content', None)

        if business_id and file_name and file_content:
            business_obj = models.BusinessTwo.objects.filter(id=business_id).first()
            business_name = business_obj.name
            file = '%sprod/%s/%s' % (jenkins_config.config_path, business_name, file_name)
            if os.path.isfile(file):
                os.system('chmod 777 %s' % file)
                with open(file, "w+") as f:
                    f.write(file_content)
                f.close()
                response.status = True

        return JsonResponse(response.__dict__)
Example #38
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
Example #39
0
    def get_server_groups_json(request, server_id):
        response = BaseResponse()

        try:
            get_public_group_tag = request.GET.get('public_group')
            # from django.db.models import Count
            if get_public_group_tag:
                get_group_from_db = models.AppGroups.objects.filter(
                    group_type=1).values('id', 'name', 'app_id__name',
                                         'app_id__project_id__name',
                                         'group_type').order_by("-id")
            else:
                get_group_from_db = models.AppGroups.objects.filter(
                    app_id__id=server_id).values('id', 'name', 'app_id__name',
                                                 'app_id__project_id__name',
                                                 'group_type').order_by("-id")
            response.data = list(get_group_from_db)
        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
Example #40
0
    def chart():
        response = BaseResponse()
        try:
            sql = """
                SELECT
                    id,
                    name,
                    (select count(id) from asset as A where B.id=A.business_unit_id and A.device_type_id=1) as server_count,
                    (select count(id) from asset as A where B.id=A.business_unit_id and A.device_type_id=2) as switch_count,
                    (select count(id) from asset as A where B.id=A.business_unit_id and A.device_type_id=3) as firewall_count
                from businessunit as B"""
            result = models.BusinessUnit.objects.raw(sql)
            ret = {
                'categories': [],
                'series': [
                    {
                        "name": '服务器',
                        "data": []
                    },
                    {
                        "name": '交换机',
                        "data": []
                    }, {
                        "name": '防火墙',
                        "data": []
                    }
                ]
            }
            for row in result:
                ret['categories'].append(row.name)
                ret['series'][0]['data'].append(row.server_count)
                ret['series'][1]['data'].append(row.switch_count)
                ret['series'][2]['data'].append(row.firewall_count)
            response.data = ret
        except Exception as e:
            response.status = False
            response.message = str(e)

        return response
Example #41
0
    def add_urlmaps(request):
        response = BaseResponse()
        try:
            response.error = {}
            post_dict = QueryDict(request.body, encoding='utf-8')

            urlmaps_url = post_dict.get('urlmaps_url')
            urlmaps_group_id = post_dict.get('urlmaps_group_id')
            urlmaps_memo = post_dict.get('urlmaps_memo')

            add_to_db = repository_models.UrlConfigHandler(
                group_id_id = urlmaps_group_id,
                url = urlmaps_url,
                memo = urlmaps_memo
            )
            add_to_db.save()

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

            instance_group_id = post_dict.get('instance_group_id')
            new_instance_id = post_dict.get('new_instance_id')
            old_instance_id = post_dict.get('old_instance_id')

            get_group_from_db = repository_models.AppGroups.objects.get(
                id=instance_group_id)
            get_group_from_db.instance.remove(
                CMDB_MODELS.Asset.objects.get(id=old_instance_id))
            get_group_from_db.instance.add(
                CMDB_MODELS.Asset.objects.get(id=new_instance_id))

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
Example #43
0
    def server_config(server_id):

        response = BaseResponse()
        try:
            response.data = models.Applications.objects.filter(id=server_id).first()
            response.asset_data = CMDB_MODELS.Asset.objects.all()
            response.urlmaps_data = models.UrlConfigHandler.objects.filter(group_id__app_id=server_id).first()
        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
Example #44
0
    def process(server_obj, server_info, user_obj):
        response = BaseResponse()
        try:
            # 获取对应的信息,status,error,data,message
            nic_info = server_info['nic']
            if not nic_info['status']:
                response.status = False
                models.ErrorLog.objects.create(asset_obj=server_obj.asset,
                                               title='nic-agent',
                                               content=nic_info['error'])
                return response
            # 汇报的最新数据
            client_nic_dict = nic_info['data']
            # 数据库中已存在的网卡所有信息拿出来
            nic_obj_list = models.NIC.objects.filter(server_obj=server_obj)
            nic_name_list = map(lambda x: x,
                                (item.name for item in nic_obj_list))
            # 交集,数据库有,汇报也有的数据名。更新
            update_list = agorithm.get_intersection(
                set(client_nic_dict.keys()), set(nic_name_list))
            # 汇报有,数据库没有
            add_list = agorithm.get_exclude(client_nic_dict.keys(),
                                            update_list)
            # 汇报没有,数据库有
            del_list = agorithm.get_exclude(nic_name_list, update_list)

            HandleNic._add_nic(add_list, client_nic_dict, server_obj, user_obj)
            HandleNic._update_nic(update_list, nic_obj_list, client_nic_dict,
                                  server_obj, user_obj)
            HandleNic._del_nic(del_list, nic_obj_list, server_obj, user_obj)

        except Exception as e:
            response.status = False
            models.ErrorLog.objects.create(asset_obj=server_obj.asset,
                                           title='nic-run',
                                           content=traceback.format_exc())

        return response
Example #45
0
    def process(server_obj, server_info, user_obj):
        response = BaseResponse()
        try:
            # 获取数据库中所有网卡信息
            # server_info 服务器最新汇报的数据
            nic_info = server_info['nic']
            if not nic_info['status']:
                response.status = False
                models.ErrorLog.objects.create(asset_obj=server_obj.asset,
                                               title='nic-agent',
                                               content=nic_info['error'])
                return response

            client_nic_dict = nic_info['data']
            nic_obj_list = models.NIC.objects.filter(server_obj=server_obj)
            nic_name_list = map(lambda x: x,
                                (item.name for item in nic_obj_list))

            update_list = agorithm.get_intersection(
                set(client_nic_dict.keys()), set(nic_name_list))
            add_list = agorithm.get_exclude(client_nic_dict.keys(),
                                            update_list)
            del_list = agorithm.get_exclude(nic_name_list, update_list)

            # 删除 更新 添加操作
            HandleNic._add_nic(add_list, client_nic_dict, server_obj, user_obj)
            HandleNic._update_nic(update_list, nic_obj_list, client_nic_dict,
                                  server_obj, user_obj)
            HandleNic._del_nic(del_list, nic_obj_list, server_obj, user_obj)

        except Exception as e:
            response.status = False
            response.error = str(e)
            models.ErrorLog.objects.create(asset_obj=server_obj.asset,
                                           title='nic-run',
                                           content=traceback.format_exc())

        return response
Example #46
0
    def add_data(request):
        response = BaseResponse()
        try:
            response.error = []
            post_dict = QueryDict(request.body, encoding='utf-8')
            data_values = {k: v for k, v in post_dict.items()}
            repository_models.Applications.objects.create(**data_values)

            # app_name = post_dict.get('app_name')
            # project_id = post_dict.get('project_id')
            # app_type = post_dict.get('app_type')
            #
            # add_to_db = repository_models.Applications(
            #     name = app_name,
            #     app_type = app_type,
            #     project_id = repository_models.ProjectInfo.objects.get(id=project_id),
            # )
            #
            # add_to_db.save()

            # # create groups include production and cstest.
            # from urllib import parse, request
            # import json
            # import urllib
            # groups_list = ['CSTest', 'Production']
            # header_dict = {"Content-Type": "application/x-www-form-urlencoded"}
            # url = 'http://127.0.0.1:%s/update-server-group.html' % settings.project_port
            # for group in groups_list:
            #     textmod = {"add_group_app_id": add_to_db.id, "add_group_name": group, "add_group_yaml_path": 1}
            #     textmod = parse.urlencode(textmod).encode(encoding='utf-8')
            #     request = urllib.request.Request(url=url, data=textmod, headers=header_dict)
            #     response = urllib.request.urlopen(request)

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
Example #47
0
 def get(self, request, *args, **kwargs):
     response = BaseResponse()
     service = request.session.get('service')
     project_obj = models.ServiceToSlb.objects.all()
     if service == '全 部':
         service_obj = models.SlbInfo.objects.all()
     else:
         slb_obj = models.ServiceToSlb.objects.filter(service_name=service).all().first()
         if slb_obj:
             service_obj = models.SlbInfo.objects.filter(vg_id=slb_obj.vg_id).all()
             for s in service_obj:
                 s_id = s.vg_id
                 tag_obj = models.ServiceToSlb.objects.filter(vg_id=s_id).all().first()
                 if tag_obj:
                     tag = tag_obj.tag
                     s_name = tag_obj.service_name
                 else:
                     tag = ''
                     s_name = ''
                     print('error:', s_id)
                 s.tag = tag
                 s.s_name = s_name
         else:
             service_obj = models.SlbInfo.objects.all()
             for s in service_obj:
                 s_id = s.vg_id
                 tag_obj = models.ServiceToSlb.objects.filter(vg_id=s_id).all().first()
                 if tag_obj:
                     tag = tag_obj.tag
                     s_name = tag_obj.service_name
                 else:
                     tag = ''
                     s_name = ''
                     print('error:', s_id)
                 s.tag = tag
                 s.s_name = s_name
     response.data = service_obj
     return render(request, 'member-list.html', {'response': response, 'service': service, 'project_obj': project_obj})
Example #48
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
Example #49
0
    def put_idc(request):
        response = BaseResponse()
        try:
            response.error = []
            put_dict = QueryDict(request.body, encoding='utf-8')
            idc_id = put_dict.get('idc_id')
            idc_name = put_dict.get('idc_name')
            idc_floor = put_dict.get('idc_floor')
            idc_phone = put_dict.get('idc_phone')
            idc_address = put_dict.get('idc_address')

            update_data = CMDB_MODELS.IDC.objects.get(id=idc_id)
            update_data.name = idc_name
            update_data.floor = idc_floor
            update_data.phone = idc_phone
            update_data.idc_address = idc_address
            update_data.save()

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
Example #50
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
Example #51
0
    def update_urlmaps(request):
        response = BaseResponse()
        try:
            response.error = {}
            post_dict = QueryDict(request.body, encoding='utf-8')

            print(post_dict)
            urlmaps_id = post_dict.get('urlmaps_id')
            urlmaps_url = post_dict.get('urlmaps_url')
            urlmaps_group_id = post_dict.get('urlmaps_group_id')
            urlmaps_memo = post_dict.get('urlmaps_memo')

            get_data_from_db = repository_models.UrlConfigHandler.objects.get(id=urlmaps_id)
            get_data_from_db.group_id_id = urlmaps_group_id
            get_data_from_db.url = urlmaps_url
            get_data_from_db.memo = urlmaps_memo
            get_data_from_db.save()

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
Example #52
0
    def delete(self, request, *args, **kwargs):
        """
        购物车中删除课程
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        ret = BaseResponse()
        try:
            course_id_list = request.data.get('courseids')
            key_list = [
                settings.SHOPPING_CAR_KEY % (
                    request.auth.user_id,
                    course_id,
                ) for course_id in course_id_list
            ]
            self.conn.delete(*key_list)
        except Exception as e:
            ret.code = 1002
            ret.error = "删除失败"

        return Response(ret.dict)
Example #53
0
    def update_domain(request):
        response = BaseResponse()
        try:
            response.error = {}
            post_dict = QueryDict(request.body, encoding='utf-8')

            print(post_dict)

            domain_id = post_dict.get('domain_id')
            domain_url = post_dict.get('domain_url')
            domain_memo = post_dict.get('domain_memo')

            get_data_from_db = repository_models.WebConfigDomains.objects.get(
                id=domain_id)
            get_data_from_db.domain = domain_url
            get_data_from_db.memo = domain_memo
            get_data_from_db.save()

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
Example #54
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')
            add_group_type = post_dict.get('add_group_type')

            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.group_type = add_group_type
            get_group_from_db.save()

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
Example #55
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_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))
            add_to_db.save()

        except Exception as e:
            print(Exception, e)
            response.status = False
            response.message = str(e)
        return response
Example #56
0
    def process(server_obj, server_info, user_obj):
        response = BaseResponse()
        try:
            database_info = server_info['database']
            print(database_info)

            if not database_info['status']:
                response.status = False
                models.ErrorLog.objects.create(asset_obj=server_obj.asset,
                                               title='nic-agent',
                                               content=database_info['error'])
                return response

            client_mysql_dict = database_info['data']
            print(client_mysql_dict)
            mysql_obj_list = models.MysqlInfo.objects.filter(
                server_obj=server_obj)
            mysql_name_list = map(lambda x: x,
                                  (item.hostname for item in mysql_obj_list))

            update_list = agorithm.get_intersection(
                set(client_mysql_dict.keys()), set(mysql_name_list))
            add_list = agorithm.get_exclude(client_mysql_dict.keys(),
                                            update_list)
            del_list = agorithm.get_exclude(mysql_name_list, update_list)

            # 后面进行 接收数据模块 开发
            # HandleMysql._add_nic(add_list, client_mysql_dict, server_obj, user_obj)
            # HandleMysql._update_nic(update_list, mysql_obj_list, client_mysql_dict, server_obj, user_obj)
            # HandleMysql._del_nic(del_list, mysql_name_list, server_obj, user_obj)

        except Exception as e:
            response.status = False
            models.ErrorLog.objects.create(obj=server_obj.hostname,
                                           title='mysql-run',
                                           content=traceback.format_exc())
        return response
Example #57
0
    def process(server_obj, server_info, user_obj):
        response = BaseResponse()
        try:
            mem_info = server_info['memory']
            print(mem_info['status'])
            if not mem_info['status']:
                models.ErrorLog.objects.create(asset_obj=server_obj.asset,
                                               title='memory-agent',
                                               content=mem_info['error'])
                response.status = False
                return response

            client_mem_dict = mem_info['data']

            mem_obj_list = models.Memory.objects.filter(server_obj=server_obj)

            mem_slots = map(lambda x: x, (item.slot for item in mem_obj_list))

            update_list = agorithm.get_intersection(
                set(client_mem_dict.keys()), set(mem_slots))
            add_list = agorithm.get_exclude(client_mem_dict.keys(),
                                            update_list)
            del_list = agorithm.get_exclude(mem_slots, update_list)

            HandleMemory._add_memory(add_list, client_mem_dict, server_obj,
                                     user_obj)
            HandleMemory._update_memory(update_list, mem_obj_list,
                                        client_mem_dict, server_obj, user_obj)
            HandleMemory._del_memory(del_list, mem_obj_list, server_obj,
                                     user_obj)
        except Exception as e:
            response.status = False
            models.ErrorLog.objects.create(asset_obj=server_obj.asset,
                                           title='memory-run',
                                           content=traceback.format_exc())

        return response
Example #58
0
    def process(server_obj, server_info, user_obj):
        response = BaseResponse()
        try:
            disk_info = server_info['disk']
            if not disk_info['status']:
                response.status = False
                models.ErrorLog.objects.create(asset_obj=server_obj.asset,
                                               title='disk-agent',
                                               content=disk_info['error'])
                return response

            client_disk_dict = disk_info['data']

            disk_obj_list = models.Disk.objects.filter(server_obj=server_obj)

            disk_slots = map(lambda x: x,
                             (item.slot for item in disk_obj_list))

            update_list = agorithm.get_intersection(
                set(client_disk_dict.keys()), set(disk_slots))
            add_list = agorithm.get_exclude(client_disk_dict.keys(),
                                            update_list)
            del_list = agorithm.get_exclude(disk_slots, update_list)

            HandleDisk._add_disk(add_list, client_disk_dict, server_obj,
                                 user_obj)
            HandleDisk._update_disk(update_list, disk_obj_list,
                                    client_disk_dict, server_obj, user_obj)
            HandleDisk._del_disk(del_list, disk_obj_list, server_obj, user_obj)

        except Exception as e:
            response.status = False
            models.ErrorLog.objects.create(asset_obj=server_obj.asset,
                                           title='disk-run',
                                           content=traceback.format_exc())
        return response
Example #59
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
Example #60
0
 def post(self, request):
     res = BaseResponse()
     gt = GeetestLib(pc_geetest_id, pc_geetest_key)
     username = request.data.get("username", "")
     pwd = request.data.get("pwd", "")
     challenge = request.data.get("geetest_challenge", '')
     validate = request.data.get("geetest_validate", '')
     seccode = request.data.get("geetest_seccode", '')
     # status = request.session.get(gt.GT_STATUS_SESSION_KEY)
     status = 1
     # user_id = request.session.get("user_id")
     user_id = "test"
     if status:
         result = gt.success_validate(challenge, validate, seccode, user_id)
     else:
         result = gt.failback_validate(challenge, validate, seccode)
     if result:
         user = Account.objects.filter(username=username, pwd=pwd).first()
         if not user:
             res.code = 1030
             res.error = "用户名或密码错误"
         else:
             token = str(uuid.uuid4()).replace("-", "")
             try:
                 conn = redis.Redis(connection_pool=POOL)
                 # conn.set(token, user.id, ex=36000)
                 conn.set(token, user.id)
                 res.code = 1000
                 res.data = {"username": user.username, "token": token, "avatar": user.head_img}
             except Exception as e:
                 res.code = 1033
                 res.error = "创建token失败,reason:" + str(e)
     else:
         res.code = 1001
         res.error = "二次验证失败"
     return Response(res.dict)