def regex_task_add(request): if request.method == "GET": regexgrouplist = check_group_mge.objects.all() return render(request, 'baseline/RegexTaskAdd.html', {"regexgrouplist": regexgrouplist}) elif request.method == "POST": if request.POST.get('op') == 'get_dev': try: assets = confmanageserializers.AssetsSerializer( Assets.objects.all(), many=True).data except Exception as e: logger.warn(e) return JsonResponse({"msg": "插入成功", "code": 400, 'assets': assets})
def regex_rule_detail(request): if request.method == "GET": pass return render(request, 'baseline/RegexGroupDetail.html') elif request.method == "POST": rule_id = int(request.POST.get('rule_id')) try: rulecontentlist = [] rule = baselineserializers.RuleManageSerializer( check_rule_manage.objects.get(rule_id=rule_id)).data rulecontent = check_rule_content.objects.filter(rule_id=rule_id) for i in rulecontent: data = baselineserializers.RuleContentSerializer(i) rulecontentlist.append(data.data) return JsonResponse({ 'code': 400, 'rule': rule, 'rulecontent': rulecontentlist }) except Exception as e: logger.warn("查询失败失败原因:%s", e)
def assets_server(request): if request.method == "POST": if request.POST.get('query') in ['service', 'project', 'group']: dataList = [] if request.POST.get('query') == 'service': for ser in Assets.objects.filter( business=request.POST.get('id')): # ,assets_type__in=['server','vmser','switch','route']): try: project = Project_Assets.objects.get(id=ser.project).project_name except Exception as ex: project = '未知' logger.warn(msg="查询主机产品线信息失败: {ex}".format(ex=str(ex))) try: service = Service_Assets.objects.get(id=ser.business).service_name except Exception as ex: service = '未知' logger.warn(msg="查询主机业务类型失败: {ex}".format(ex=str(ex))) if ser.assets_type in ['server', 'vmser']: dataList.append({"id": ser.server_assets.id, "ip": ser.server_assets.ip, "project": project, "service": service}) elif ser.assets_type in ['switch', 'route']: dataList.append({"id": ser.network_assets.id, "ip": ser.network_assets.ip, "project": project, "service": service}) elif request.POST.get('query') == 'group': for ser in Assets.objects.filter( group=request.POST.get('id')): # assets_type__in=['server','vmser','switch','route']): try: project = Project_Assets.objects.get(id=ser.project).project_name except Exception as ex: project = '未知' logger.warn(msg="查询主机产品线信息失败: {ex}".format(ex=str(ex))) try: service = Service_Assets.objects.get(id=ser.business).service_name except Exception as ex: service = '未知' logger.warn(msg="查询主机业务类型失败: {ex}".format(ex=str(ex))) if ser.assets_type in ['server', 'vmser']: dataList.append({"id": ser.server_assets.id, "ip": ser.server_assets.ip, "project": project, "service": service}) elif ser.assets_type in ['switch', 'route']: dataList.append({"id": ser.network_assets.id, "ip": ser.network_assets.ip, "project": project, "service": service}) return JsonResponse({'msg': "主机查询成功", "code": 200, 'data': dataList}) else: JsonResponse({'msg': "不支持的操作", "code": 500, 'data': []}) else: return JsonResponse({'msg': "操作失败", "code": 500, 'data': "不支持的操作"})
def regularcheck(checkfirewall): policymiclist = checkfirewall.policymiclist.copy() regularpolicylist = [] for i in RegularList.regularlist: srcnet = iplocate(i['srcaddr']) dstnet = iplocate(i['dstaddr']) try: routelist = networkx.shortest_path(Topo.nxtopology, source=srcnet, target=dstnet) except: logger.warn(srcnet.name + " to " + dstnet.name + "路径不完整") continue srceth = '' dsteth = '' for k in range(len(routelist)): if routelist[k] == checkfirewall: for port in checkfirewall.portlink: if routelist[k - 1].name in port: srceth = port.split('-')[0] if routelist[k + 1].name in port: dsteth = port.split('-')[0] if not srceth or not dsteth: continue else: for j in policymiclist: if j.srceth == srceth and j.dsteth == dsteth: if IPy.IP(i['srcaddr']) == IPy.IP(j.srcaddr) and IPy.IP( i['dstaddr']).overlaps(j.dstaddr) == 1: if i['protocol'] == j.service['protocol'] and i[ 'port'] == j.service['port']: policymiclist.remove(j) return policymiclist
def assets_dumps(request): if request.method == "POST": dRbt = CellWriter('assets_dumps.xls') serSheet = dRbt.workbook.add_sheet('服务器资产', cell_overwrite_ok=True) netSheet = dRbt.workbook.add_sheet('网络设备资产', cell_overwrite_ok=True) bList = ['设备类型', '资产编号', '设备序列号', '生产制造商', '设备型号', '主机地址', '主机名字'] nList = ['设备类型', '资产编号', '设备序列号', '购买人', '管理IP', '生产制造商', '设备型号', '设备状态', '主机地址', '设备名称', '端口数', '配置说明', '管理用户', '端口'] dRbt.writeBanner(sheetName=serSheet, bList=bList) dRbt.writeBanner(sheetName=netSheet, bList=nList) count = 1 for ast in request.POST.get('assetsIds').split(','): try: assets = Assets.objects.select_related().get(id=int(ast)) except Exception as ex: logger.warn(msg=ex) continue if assets.assets_type in ['vmser', 'server']: sheet = serSheet sheet.write(count, 15, assets.server_assets.ip, dRbt.bodySttle()) sheet.write(count, 18, assets.server_assets.hostname, dRbt.bodySttle()) else: sheet = netSheet sheet.write(count, 7, assets.network_assets.ip, dRbt.bodySttle()) sheet.write(count, 8, assets.network_assets.hostname, dRbt.bodySttle()) sheet.write(count, 9, assets.network_assets.port_number, dRbt.bodySttle()) sheet.write(count, 10, assets.network_assets.username, dRbt.bodySttle()) sheet.write(count, 11, assets.network_assets.port, dRbt.bodySttle()) sheet.write(count, 12, assets.network_assets.passwd, dRbt.bodySttle()) sheet.write(count, 13, assets.network_assets.configure_detail, dRbt.bodySttle()) sheet.write(count, 14, assets.network_assets.port_number, dRbt.bodySttle()) sheet.write(count, 15, assets.network_assets.is_master, dRbt.bodySttle()) if assets.assets_type == 'vmser': sheet.write(count, 0, '虚拟机', dRbt.bodySttle()) elif assets.assets_type == 'server': sheet.write(count, 0, '服务器', dRbt.bodySttle()) elif assets.assets_type == 'switch': sheet.write(count, 0, '交换机', dRbt.bodySttle()) elif assets.assets_type == 'route': sheet.write(count, 0, '路由器', dRbt.bodySttle()) elif assets.assets_type == 'firewall': sheet.write(count, 0, '防火墙', dRbt.bodySttle()) elif assets.assets_type == 'storage': sheet.write(count, 0, '存储设备', dRbt.bodySttle()) sheet.write(count, 1, assets.name, dRbt.bodySttle()) sheet.write(count, 2, assets.sn, dRbt.bodySttle()) try: sheet.write(count, 3, User.objects.get(id=assets.buy_user).username, dRbt.bodySttle()) except: sheet.write(count, 3, assets.buy_user, dRbt.bodySttle()) sheet.write(count, 4, assets.management_ip, dRbt.bodySttle()) sheet.write(count, 5, assets.manufacturer, dRbt.bodySttle()) sheet.write(count, 6, assets.model, dRbt.bodySttle()) count = count + 1 dRbt.save() response = StreamingHttpResponse(base.file_iterator('assets_dumps.xls')) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment; filename="{file_name}'.format(file_name='assets_dumps.xls') return response
def assets_update(request): if request.method == "POST": fList = [] sList = [] resource = [] serList = [] # if request.POST.get('model') == 'update': for ast in request.POST.getlist('assetsIds[]'): try: assets = Assets.objects.get(id=int(ast)) except Exception as ex: logger.warn(msg="批量更新获取资产失败: {ex}".format(ex=str(ex))) continue if assets.assets_type in ['vmser', 'server']: try: server_assets = Server_Assets.objects.get(assets=assets) except Exception as ex: logger.warn(msg="批量更新获取服务器资产失败: {ex}".format(ex=str(ex))) if server_assets.ip not in fList: fList.append(server_assets.ip) continue serList.append(server_assets.ip) if server_assets.keyfile == 1: resource.append( {"ip": server_assets.ip, "port": int(server_assets.port), "username": server_assets.username, "sudo_passwd": server_assets.sudo_passwd}) else: resource.append( {"ip": server_assets.ip, "port": int(server_assets.port), "username": server_assets.username, "password": server_assets.passwd, "sudo_passwd": server_assets.sudo_passwd}) ANS = ANSRunner(resource) ANS.run_model(host_list=serList, module_name='setup', module_args="") data = ANS.handle_cmdb_data(ANS.get_model_result()) if data: for ds in data: status = ds.get('status') sip = ds.get('ip') if status == 0: assets = Server_Assets.objects.get(ip=ds.get('ip')).assets assets.model = ds.get('model') assets.save() try: Server_Assets.objects.filter(ip=ds.get('ip')).update(cpu_number=ds.get('cpu_number'), kernel=ds.get('kernel'), selinux=ds.get('selinux'), hostname=ds.get('hostname'), system=ds.get('system'), cpu=ds.get('cpu'), disk_total=ds.get('disk_total'), cpu_core=ds.get('cpu_core'), swap=ds.get('swap'), ram_total=ds.get('ram_total'), vcpu_number=ds.get('vcpu_number') ) if sip not in sList: sList.append(sip) except Exception: if sip not in fList: fList.append(sip) for nk in ds.get('nks'): macaddress = nk.get('macaddress') count = NetworkCard_Assets.objects.filter(assets=assets, macaddress=macaddress).count() if count > 0: try: NetworkCard_Assets.objects.filter(assets=assets, macaddress=macaddress).update( assets=assets, device=nk.get('device'), ip=nk.get('address'), module=nk.get('module'), mtu=nk.get('mtu'), active=nk.get('active')) except Exception as ex: logger.warn(msg="批量更新更新服务器网卡资产失败: {ex}".format(ex=str(ex))) else: try: NetworkCard_Assets.objects.create(assets=assets, device=nk.get('device'), macaddress=nk.get('macaddress'), ip=nk.get('address'), module=nk.get('module'), mtu=nk.get('mtu'), active=nk.get('active')) except Exception as ex: logger.warn(msg="批量更新写入服务器网卡资产失败: {ex}".format(ex=str(ex))) else: if sip not in fList: fList.append(sip) if sList: return JsonResponse({'msg': "数据更新成功", "code": 200, 'data': {"success": sList, "failed": fList}}) else: return JsonResponse({'msg': "数据更新失败", "code": 500, 'data': {"success": sList, "failed": fList}})
def assets_import(request): if request.method == "POST": f = request.FILES.get('import_file') filename = os.path.join(os.getcwd() + '/upload/', f.name) if os.path.isdir(os.path.dirname(filename)) is not True: os.makedirs(os.path.dirname(filename)) fobj = open(filename, 'wb') for chrunk in f.chunks(): fobj.write(chrunk) fobj.close() # 读取上传的execl文件内容方法 def getAssetsData(fname=filename): bk = xlrd.open_workbook(fname) dataList = [] try: server = bk.sheet_by_name("server") net = bk.sheet_by_name("net") for i in range(1, server.nrows): dataList.append(server.row_values(i)) for i in range(1, net.nrows): dataList.append(net.row_values(i)) except Exception as e: return [] return dataList dataList = getAssetsData(fname=filename) # 获取服务器列表 for data in dataList: assets = { 'assets_type': data[0], 'name': data[1], 'sn': data[2], 'buy_user': int(data[5]), 'management_ip': data[6], 'manufacturer': data[7], 'model': data[8], 'provider': data[9], 'status': int(data[10]), 'put_zone': int(data[11]), 'group': int(data[12]), 'project': int(data[13]), 'business': int(data[14]), } if data[3]: assets['buy_time'] = xlrd.xldate.xldate_as_datetime(data[3], 0) if data[4]: assets['expire_date'] = xlrd.xldate.xldate_as_datetime(data[4], 0) if assets.get('assets_type') in ['vmser', 'server']: server_assets = { 'ip': data[15], 'keyfile': data[16], 'username': data[17], 'passwd': data[18], 'hostname': data[19], 'port': data[20], 'raid': data[21], 'line': data[22], } else: net_assets = { 'ip': data[15], 'bandwidth': data[16], 'port_number': data[17], 'firmware': data[18], 'cpu': data[19], 'stone': data[20], 'configure_detail': data[21] } count = Assets.objects.filter(name=assets.get('name')).count() if count == 1: assetsObj = Assets.objects.get(name=assets.get('name')) Assets.objects.filter(name=assets.get('name')).update(**assets) try: if assets.get('assets_type') in ['vmser', 'server']: Server_Assets.objects.filter(assets=assetsObj).update(**server_assets) elif assets.get('assets_type') in ['switch', 'route', 'printer', 'scanner', 'firewall', 'storage', 'wifi']: Network_Assets.objects.filter(assets=assetsObj).update(**net_assets) except Exception as ex: logger.warn(msg="批量更新资产失败: {ex}".format(ex=str(ex))) else: try: assetsObj = Assets.objects.create(**assets) except Exception as ex: logger.warn(msg="批量写入资产失败: {ex}".format(ex=str(ex))) if assetsObj: try: if assets.get('assets_type') in ['vmser', 'server']: Server_Assets.objects.create(assets=assetsObj, **server_assets) elif assets.get('assets_type') in ['switch', 'route', 'printer', 'scanner', 'firewall', 'storage', 'wifi']: Network_Assets.objects.create(assets=assetsObj, **net_assets) except Exception as ex: logger.warn(msg="批量更新资产失败: {ex}".format(ex=str(ex))) assetsObj.delete() return HttpResponseRedirect('/assets_list')
def assets_facts(request, args=None): if request.method == "POST" and request.user.has_perm('OpsManage.change_server_assets'): server_id = request.POST.get('server_id') genre = request.POST.get('type') if genre == 'setup': try: server_assets = Server_Assets.objects.get(id=request.POST.get('server_id')) if server_assets.keyfile == 1: resource = [ {"ip": server_assets.ip, "port": int(server_assets.port), "username": server_assets.username, "sudo_passwd": server_assets.sudo_passwd}] else: resource = [{"ip": server_assets.ip, "port": server_assets.port, "username": server_assets.username, "password": server_assets.passwd, "sudo_passwd": server_assets.sudo_passwd}] except Exception as ex: logger.error(msg="更新资产失败: {ex}".format(ex=str(ex))) return JsonResponse({'msg': "数据更新失败-查询不到该主机资料~", "code": 502}) ANS = ANSRunner(resource) ANS.run_model(host_list=[server_assets.ip], module_name='setup', module_args="") data = ANS.handle_cmdb_data(ANS.get_model_result()) if data: for ds in data: status = ds.get('status') if status == 0: try: assets = Assets.objects.get(id=server_assets.assets_id) Assets.objects.filter(id=server_assets.assets_id).update(sn=ds.get('serial'), model=ds.get('model'), manufacturer=ds.get( 'manufacturer')) except Exception as ex: logger.error(msg="获取服务器信息失败: {ex}".format(ex=str(ex))) return JsonResponse({'msg': "数据更新失败-查询不到该主机的资产信息", "code": 403}) try: Server_Assets.objects.filter(id=server_id).update(cpu_number=ds.get('cpu_number'), kernel=ds.get('kernel'), selinux=ds.get('selinux'), hostname=ds.get('hostname'), system=ds.get('system'), cpu=ds.get('cpu'), disk_total=ds.get('disk_total'), cpu_core=ds.get('cpu_core'), swap=ds.get('swap'), ram_total=ds.get('ram_total'), vcpu_number=ds.get('vcpu_number') ) recordAssets.delay(user=str(request.user), content="修改服务器资产:{ip}".format(ip=server_assets.ip), type="server", id=server_assets.id) except Exception as ex: logger.error(msg="更新服务器信息失败: {ex}".format(ex=str(ex))) return JsonResponse({'msg': "数据更新失败-写入数据失败", "code": 400}) for nk in ds.get('nks'): macaddress = nk.get('macaddress') count = NetworkCard_Assets.objects.filter(assets=assets, macaddress=macaddress).count() if count > 0: try: NetworkCard_Assets.objects.filter(assets=assets, macaddress=macaddress).update( assets=assets, device=nk.get('device'), ip=nk.get('address'), module=nk.get('module'), mtu=nk.get('mtu'), active=nk.get('active')) except Exception as ex: logger.warn(msg="更新服务器网卡信息失败: {ex}".format(ex=str(ex))) else: try: NetworkCard_Assets.objects.create(assets=assets, device=nk.get('device'), macaddress=nk.get('macaddress'), ip=nk.get('address'), module=nk.get('module'), mtu=nk.get('mtu'), active=nk.get('active')) except Exception as ex: logger.warn(msg="写入服务器网卡信息失败: {ex}".format(ex=str(ex))) else: return JsonResponse({'msg': "数据更新失败-无法链接主机~", "code": 502}) return JsonResponse({'msg': "数据更新成功", "code": 200}) else: return JsonResponse({'msg': "数据更新失败-请检查Ansible配置", "code": 400}) elif genre == 'crawHw': try: server_assets = Server_Assets.objects.get(id=server_id) assets = Assets.objects.get(id=server_assets.assets_id) if server_assets.keyfile == 1: resource = [ {"ip": server_assets.ip, "port": int(server_assets.port), "username": server_assets.username, "sudo_passwd": server_assets.sudo_passwd}] else: resource = [{"ip": server_assets.ip, "port": server_assets.port, "username": server_assets.username, "password": server_assets.passwd, "sudo_passwd": server_assets.sudo_passwd}] except Exception as e: logger.error(msg="更新硬件信息失败: {ex}".format(ex=ex)) return JsonResponse({'msg': "数据更新失败-查询不到该主机资料~", "code": 502}) ANS = ANSRunner(resource) ANS.run_model(host_list=[server_assets.ip], module_name='crawHw', module_args="") data = ANS.handle_cmdb_crawHw_data(ANS.get_model_result()) if data: for ds in data: if ds.get('mem_info'): for mem in ds.get('mem_info'): if Ram_Assets.objects.filter(assets=assets, device_slot=mem.get('slot')).count() > 0: try: Ram_Assets.objects.filter(assets=assets, device_slot=mem.get('slot')).update( device_slot=mem.get('slot'), device_model=mem.get('serial'), device_brand=mem.get('manufacturer'), device_volume=mem.get('size'), device_status="Online" ) except Exception as ex: return JsonResponse({'msg': "数据更新失败-写入数据失败", "code": 400}) else: try: Ram_Assets.objects.create(device_slot=mem.get('slot'), device_model=mem.get('serial'), device_brand=mem.get('manufacturer'), device_volume=mem.get('size'), device_status="Online", assets=assets ) recordAssets.delay(user=str(request.user), content="修改服务器资产:{ip}".format(ip=server_assets.ip), type="server", id=server_assets.id) except Exception as e: return JsonResponse({'msg': "数据更新失败-写入数据失败", "code": 400}) if ds.get('disk_info'): for disk in ds.get('disk_info'): if Disk_Assets.objects.filter(assets=assets, device_slot=disk.get('slot')).count() > 0: try: Disk_Assets.objects.filter(assets=assets, device_slot=disk.get('slot')).update( device_serial=disk.get('serial'), device_model=disk.get('model'), device_brand=disk.get('manufacturer'), device_volume=disk.get('size'), device_status="Online" ) except Exception as e: return JsonResponse({'msg': "数据更新失败-写入数据失败", "code": 400}) else: try: Disk_Assets.objects.create(device_serial=disk.get('serial'), device_model=disk.get('model'), device_brand=disk.get('manufacturer'), device_volume=disk.get('size'), device_status="Online", assets=assets, device_slot=disk.get('slot') ) recordAssets.delay(user=str(request.user), content="修改服务器资产:{ip}".format(ip=server_assets.ip), type="server", id=server_assets.id) except Exception as e: return JsonResponse({'msg': "数据更新失败-写入数据失败", "code": 400}) return JsonResponse({'msg': "数据更新成功", "code": 200}) else: return JsonResponse({'msg': "数据更新失败,系统可能不支持,未能获取数据", "code": 400}) else: return JsonResponse({'msg': "您没有该项操作的权限~", "code": 400})
def topo_edge(request): if request.method == 'GET': edges = Edges.objects.all() seredges = Server_Edges.objects.all() netedges = Network_Edges.objects.all() lineedges = Line_Edges.objects.all() edgesdic = [] if edges: for edge in edges: edgeid = edge.id edgetype = edge.edges_type if edgetype == "net": for netedge in netedges: if edge.id == netedge.Edges_id: srcdev = Network_Assets.objects.get( id=netedge.src_id).hostname dstdev = Network_Assets.objects.get( id=netedge.dst_id).hostname elif edge.edges_type == "line": for lineedge in lineedges: if edge.id == lineedge.Edges_id: srcdev = Network_Assets.objects.get( id=lineedge.src_id).hostname dstdev = Line_Assets.objects.get( id=lineedge.dst_id).line_name elif edge.edges_type == "server": for seredge in seredges: if edge.id == seredge.Edges_id: srcdev = Network_Assets.objects.get( id=seredge.src_id).hostname dstdev = Server_Assets.objects.get( id=seredge.dst_id).hostname edgesdic.append({ 'id': str(edgeid), 'type': edgetype, 'srcdev': srcdev, 'dstdev': dstdev }) return render(request, 'topo/topo_edge.html', {'edges': edgesdic}) elif request.method == 'POST': if request.POST.get('op') == 'type_select': srcdic = [] dstdic = [] link_type = request.POST.get('link_type') netasset = Network_Assets.objects.filter(is_master=True) for net in netasset: srcdic.append({'id': net.id, 'name': net.hostname}) if link_type == "server": serverasset = Server_Assets.objects.all() for server in serverasset: dstdic.append({'id': server.id, 'name': server.hostname}) return JsonResponse({'src': srcdic, 'dst': dstdic}) elif link_type == "net": return JsonResponse({'src': srcdic, 'dst': srcdic}) elif link_type == "line": lineasset = Line_Assets.objects.filter(line_is_master=True) for line in lineasset: dstdic.append({'id': line.id, 'name': line.line_name}) return JsonResponse({'src': srcdic, 'dst': dstdic}) elif request.POST.get('op') == 'add_link': link_type = request.POST.get('link_type') src = request.POST.get('src') dst = request.POST.get('dst') try: srcasset = Network_Assets.objects.get(id=src) except Exception as e: logger.warn("查询资产错误,错误原因:%s", e) try: edge = Edges.objects.create(edges_type=link_type) except Exception as ex: logger.warn("增加edge错误,错误原因:%s", e) if link_type == "server": dstasset = Server_Assets.objects.get(id=dst) try: Server_Edges.objects.create(Edges=edge, src=srcasset, dst=dstasset) except Exception as e: logger.warn("增加edge错误,错误原因:%s", e) edge.delete() return JsonResponse({'msg': '添加成功'}) elif link_type == "net": dstasset = Network_Assets.objects.get(id=dst) try: Network_Edges.objects.create(Edges=edge, src=srcasset, dst=dstasset) except Exception as ex: logger.warn("增加edge错误,错误原因:%s", e) edge.delete() return JsonResponse({'msg': '添加成功'}) elif link_type == "line": dstasset = Line_Assets.objects.get(id=dst) try: Line_Edges.objects.create(Edges=edge, src=srcasset, dst=dstasset) except Exception as ex: logger.warn("增加edge错误,错误原因:%s", e) edge.delete() return JsonResponse({'msg': '添加成功'}) elif request.POST.get('op') == 'del_edge': id = request.POST.get('id') edge = Edges.objects.get(id=id) if edge.edges_type == "net": try: with transaction.atomic(): Network_Edges.objects.get(Edges_id=id).delete() edge.delete() except Exception as e: logger.debug("删除Edge错误,错误原因:%s", e) return JsonResponse({'msg': "删除失败~", "code": '500'}) return JsonResponse({'msg': "删除成功~", "code": '400'}) elif edge.edges_type == "line": try: with transaction.atomic(): Line_Edges.objects.get(Edges_id=id).delete() edge.delete() except Exception as e: logger.debug("删除Edge错误,错误原因:%s", e) return JsonResponse({'msg': "删除失败~", "code": '500'}) return JsonResponse({'msg': "删除成功~", "code": '400'}) elif edge.edges_type == "server": try: with transaction.atomic(): Server_Edges.objects.get(Edges_id=id).delete() edge.delete() except Exception as e: logger.debug("删除Edge错误,错误原因:%s", e) return JsonResponse({'msg': "删除失败~", "code": '500'}) return JsonResponse({'msg': "删除成功~", "code": '400'})
def task_view(request): if request.method == "GET": try: workList = WorkerState.objects.all() regTaskList = [] for task in list(keys(cTasks)): if task.startswith('ConfManage.tasks.cron') or task.startswith( 'ConfManage.tasks.sched'): regTaskList.append(task) except Exception as ex: logger.warn(msg="获取Celery Task失败: {ex}".format(ex=str(ex))) taskLog = [] return render( request, 'task/task_view.html', { "user": request.user, "regTaskList": regTaskList, "workList": workList }, ) elif request.method == "POST": op = request.POST.get('op') if op in ['view', 'delete', 'kill' ] and request.user.has_perm('djcelery.change_taskstate'): try: task = {} for ds in PeriodicTask.objects.all(): task[ds.task] = ds.name taskLog = TaskState.objects.get(id=request.POST.get('id')) except: return JsonResponse({ "code": 500, "data": None, "msg": "任务不存在" }) if op == 'view': try: data = dict() work = WorkerState.objects.get(id=taskLog.worker_id) data['id'] = taskLog.id data['task_id'] = taskLog.task_id data['worker'] = work.hostname if task.has_key(taskLog.name): data['name'] = task[taskLog.name] else: data['name'] = taskLog.name data['tstamp'] = taskLog.tstamp data['args'] = taskLog.args.replace('[u', '[') data['kwargs'] = taskLog.kwargs.replace('u\'', '\'') data['result'] = taskLog.result data['state'] = taskLog.state data['runtime'] = taskLog.runtime return JsonResponse({ "code": 200, "data": data, "msg": "操作成功" }) except Exception as ex: logger.warn(msg="查看Celery Task运行日志失败: {ex}".format( ex=str(ex))) return JsonResponse({ "code": 500, "data": None, "msg": "日志查看失败。" }) elif op == 'delete': try: taskLog.delete() return JsonResponse({ "code": 200, "data": None, "msg": "删除成功" }) except Exception as ex: return JsonResponse({ "code": 500, "data": ex, "msg": "日志删除失败" }) elif op == 'kill': try: revoke(taskLog.task_id, terminate=True) return JsonResponse({ "code": 200, "data": None, "msg": "任务终止成功" }) except Exception as ex: logger.warn(msg="终止任务失败: {ex}".format(ex=str(ex))) return JsonResponse({ "code": 500, "data": ex, "msg": "任务终止成功" }) else: return JsonResponse({ "code": 500, "data": "终止任务失败: {ex}".format(ex=str(ex)), "msg": "不支持的操作或者您没有权限操作操作此项。" }) else: return JsonResponse({"code": 500, "data": None, "msg": "不支持的HTTP操作"})