Example #1
0
def get_untreated_servers():
    # print('22222222')
    response = BaseResponse()
    try:
        current_date = datetime.date.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')

        print('condition', condition)
        result = models.Server.objects.filter(condition).values('manage_ip')
        response.data = list(result)
        # print(response.data) #################### print ##########
        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 #2
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 #3
0
 def put_users(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:
                 models.UserProfile.objects.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
Example #4
0
    def update_last_time(server_obj, user_obj):
        response = BaseResponse()
        try:
            current_date = datetime.date.today()
            server_obj.asset.latest_date = current_date
            server_obj.asset.save()
            models.AssetRecord.objects.create(asset_obj=server_obj.asset,
                                              creator=user_obj,
                                              content='资产汇报')
        except Exception as e:
            response.status = False
            models.ErrorLog.objects.create(asset_obj=server_obj.asset,
                                           title='basic-run',
                                           content=traceback.format_exc())

        return response
Example #5
0
    def process(server_obj, server_info, user_obj):
        response = BaseResponse()
        try:
            # 获取数据库中的所有网卡信息
            # server_info,服务器最新汇报的数据 server_info['nic']
            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)

            print('nic--最新网卡信息:%s,数据库网卡信息:%s, 并集update_list:%s' %
                  (client_nic_dict.keys(), 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 #6
0
    def fetch_users(self, request):
        response = BaseResponse()
        try:
            ret = {}
            conditions = self.assets_condition(request)

            asset_count = models.UserProfile.objects.filter(conditions).count()
            page_info = PageInfo(request.GET.get('pager', None), asset_count)

            asset_list = models.UserProfile.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'] = {}
            response.data = ret
            response.message = '获取成功'
        except Exception as e:
            response.status = False
            response.message = str(e)

        return response
Example #7
0
    def chart():
        response = BaseResponse()
        try:
            sql = """
                SELECT
                    id,
                    name,
                    (select count(id) from cmdb_asset as A where B.id=A.business_unit_id and A.device_type_id=1) as server_count,
                    (select count(id) from cmdb_asset as A where B.id=A.business_unit_id and A.device_type_id=2) as switch_count,
                    (select count(id) from cmdb_asset as A where B.id=A.business_unit_id and A.device_type_id=3) as firewall_count
                from cmdb_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 #8
0
    def process(server_obj, server_info, user_obj):
        response = BaseResponse()
        try:
            disk_info = server_info['disk']
            print('disk_info', disk_info
                  )  ####################### print #######################
            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 #9
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 #10
0
    def assets_detail(device_type_id, asset_id):

        response = BaseResponse()
        try:
            if device_type_id == '1':
                response.data = models.Server.objects.filter(
                    asset_id=asset_id).select_related('asset').first()
            else:
                response.data = models.NetworkDevice.objects.filter(
                    asset_id=asset_id).select_related('asset').first()

        except Exception as e:
            response.status = False
            response.message = str(e)
        return response
Example #11
0
    def chart(last_id):

        response = BaseResponse()
        try:
            import time
            import random

            last_id = int(last_id)
            if last_id == 0:
                end = 100
            else:
                end = random.randint(1, 10)
            ret = []
            for i in range(0, end):
                temp = {'x': time.time() * 1000, 'y': random.randint(1, 1000)}
                ret.append(temp)
            last_id += 10
            response.data = ret
            response.last_id = last_id
        except Exception as e:
            response.status = False
            response.message = str(e)

        return response
Example #12
0
    def process(server_obj, server_info, user_obj):
        response = BaseResponse()
        try:
            log_list = []
            main_board = server_info['main_board']['data']  #最新主板信息
            cpu = server_info['cpu']['data']  #最新cpu信息
            if server_obj.os_platform != server_info['os_platform']:
                log_list.append('系统由%s变更为%s' % (
                    server_obj.os_platform,
                    server_info['os_platform'],
                ))
                server_obj.os_platform = server_info['os_platform']

            if server_obj.os_version != server_info['os_version']:
                log_list.append(u'系统版本由%s变更为%s' % (
                    server_obj.os_version,
                    server_info['os_version'],
                ))
                server_obj.os_version = server_info['os_version']

            if server_obj.sn != main_board['sn']:
                log_list.append(u'主板SN号由%s变更为%s' % (
                    server_obj.sn,
                    main_board['sn'],
                ))
                server_obj.sn = main_board['sn']

            if server_obj.manufacturer != main_board['manufacturer']:
                log_list.append(u'主板厂商由%s变更为%s' % (
                    server_obj.manufacturer,
                    main_board['manufacturer'],
                ))
                server_obj.manufacturer = main_board['manufacturer']

            if server_obj.model != main_board['model']:
                log_list.append(u'主板型号由%s变更为%s' % (
                    server_obj.model,
                    main_board['model'],
                ))
                server_obj.model = main_board['model']

            if server_obj.cpu_count != cpu['cpu_count']:
                log_list.append(u'CPU逻辑核数由%s变更为%s' % (
                    server_obj.cpu_count,
                    cpu['cpu_count'],
                ))
                server_obj.cpu_count = cpu['cpu_count']

            if server_obj.cpu_physical_count != cpu['cpu_physical_count']:
                log_list.append(u'CPU物理核数由%s变更为%s' % (
                    server_obj.cpu_physical_count,
                    cpu['cpu_physical_count'],
                ))
                server_obj.cpu_physical_count = cpu['cpu_physical_count']

            if server_obj.cpu_model != cpu['cpu_model']:
                log_list.append(u'CPU型号由%s变更为%s' % (
                    server_obj.cpu_model,
                    cpu['cpu_model'],
                ))
                server_obj.cpu_model = cpu['cpu_model']

            server_obj.save()
            if log_list:
                models.AssetRecord.objects.create(asset_obj=server_obj.asset,
                                                  creator=user_obj,
                                                  content=';'.join(log_list))
        except Exception as e:
            response.status = False
            models.ErrorLog.objects.create(asset_obj=server_obj.asset,
                                           title='basic-run',
                                           content=traceback.format_exc())
        return response