def template_edit(request): request_data = QueryDict(request.body) user = user_get(request) did = request_data.get("id", None) if request.method == "GET": did = request.GET.get("id", None) if did: data = Exec.objects.get(id=did) else: data = "" return render(request, "exec/template_edit.html", {"data": data}) if request.method == "POST": data = { "name": request_data.get('name'), "types": request_data.get('types'), "body": request_data.get('body'), "desc": request_data.get('desc'), } if did: Exec.objects.filter(id=did).update(**data) data = {"code": 0, "msg": "模板修改成功。"} else: Exec.objects.create(created_by=user, **data) data = {"code": 0, "msg": "添加模板成功。"} return JsonResponse(data) elif request.method == "DELETE": Exec.objects.filter(id__in=did.split(',')).update( deleted_at=human_datetime(), deleted_by=user) data = {"code": 0, "msg": "模板删除成功~"} return JsonResponse(data)
def role(request): user = user_get(request) request_data = QueryDict(request.body) d_id = request_data.get('id', None) name = request_data.get('name', None) if request.method == "GET": return render(request, 'user/role.html') elif request.method == "POST": if Role.objects.filter(name=name, deleted_by__id__isnull=True).exists(): data = {"code": 1, "msg": "角色已存在,创建失败~"} else: Role.objects.create(name=name, created_by=user) data = {"code": 0, "msg": "角色创建成功~"} return JsonResponse(data) elif request.method == "PUT": if Role.objects.filter(name=name, deleted_by__id__isnull=True).exists(): data = {"code": 1, "msg": "角色已存在,修改失败~"} else: Role.objects.filter(id=d_id).update(name=name) data = {"code": 0, "msg": "角色修改成功~"} return JsonResponse(data) elif request.method == "DELETE": Role.objects.filter(id__in=d_id.split(",")).update( deleted_at=human_datetime(), deleted_by=user) data = {"code": 0, "msg": "删除角色成功"} return JsonResponse(data)
def _handle_event(self, event): close_old_connections() obj = SimpleLazyObject( lambda: Schedule.objects.filter(pk=event.job_id).first()) if event.code == EVENT_SCHEDULER_SHUTDOWN: logging.warning(f'EVENT_SCHEDULER_SHUTDOWN: {event}') Notify.make_notify('schedule', '1', '调度器已关闭', '调度器意外关闭,请排查故障!') elif event.code == EVENT_JOB_MAX_INSTANCES: logging.warning(f'EVENT_JOB_MAX_INSTANCES: {event}') send_fail_notify(obj, '达到调度实例上限,一般为上个周期的执行任务还未结束,请增加调度间隔或减少任务执行耗时') elif event.code == EVENT_JOB_ERROR: logging.warning( f'EVENT_JOB_ERROR: job_id {event.job_id} exception: {event.exception}' ) send_fail_notify(obj, f'执行异常:{event.exception}') elif event.code == EVENT_JOB_EXECUTED: if event.retval: score = 0 for item in event.retval: score += 1 if item[1] else 0 history = History.objects.create( task_id=event.job_id, status=2 if score == len(event.retval) else 1 if score else 0, run_time=human_datetime(event.scheduled_run_time), output=json.dumps(event.retval)) Schedule.objects.filter(pk=event.job_id).update(latest=history) if score != 0: send_fail_notify(obj)
def contact_edit(request): request_data = QueryDict(request.body) did = request_data.get('id', None) user = user_get(request) if request.method == "GET": did = request.GET.get('id') if did: data = Contact.objects.filter(id=did).first() else: data = "" return render(request, "alarm/contact_edit.html", {"data": data}) elif request.method == "POST": data = { "name": request_data.get("name"), "phone": request_data.get("phone"), "email": request_data.get("email"), "ding": request_data.get("ding"), "wx_token": request_data.get("wx_token"), "qy_wx": request_data.get("qy_wx"), } if did: Contact.objects.filter(id=did).update(**data) data = {"code": 1, "msg": "联系人修改成功~"} else: Contact.objects.create(created_by=user, **data) data = {"code": 0, "msg": "联系人添加成功~"} return JsonResponse(data) elif request.method == "DELETE": Contact.objects.filter(id__in=did.split(',')).update( deleted_at=human_datetime(), deleted_by=user) data = {"code": 0, "msg": "联系人删除成功"} return JsonResponse(data)
def edit_user(request): if request.method == 'GET': did = request.GET.get('id', None) data = Role.objects.filter(deleted_at__isnull=True) li_st = [] for item in data: di_ct = {"id": item.id, 'name': item.name} li_st.append(di_ct) if did: user = User.objects.get(id=did) context = {'id': did, 'profile': user, "role": li_st} else: context = {"role": li_st} return render(request, 'user/edit_user.html', context) elif request.method == 'POST': user = user_get(request) did = request.POST.get('id') data = { "username": request.POST.get("username"), "name": request.POST.get("name"), "sex": request.POST.get("sex"), "phone": request.POST.get("phone"), "email": request.POST.get("email"), "card_id": request.POST.get("card_id"), "home_address": request.POST.get("home_address"), "desc": request.POST.get("desc", None), } if did: if User.objects.filter(phone=data["phone"], deleted_by_id__isnull=True).exclude(id=did): return JsonResponse({"code": 1, "msg": "手机号已存在"}) if User.objects.filter(email=data["email"], deleted_by_id__isnull=True).exclude(id=did): return JsonResponse({"code": 1, "msg": "邮箱已存在"}) User.objects.filter(id=did).update(**data) data = {"code": 0, "msg": "用户资料修改成功~"} else: data["password"] = request.POST.get("password") if User.objects.filter(username=data["username"]).first(): return JsonResponse({"code": 1, "msg": "用户名已存在"}) if User.objects.filter(phone=data["phone"], deleted_by_id__isnull=True).first(): return JsonResponse({"code": 1, "msg": "手机号已存在"}) if User.objects.filter(email=data["email"], deleted_by_id__isnull=True).first(): return JsonResponse({"code": 1, "msg": "邮箱已存在"}) User.objects.create_user(created_by=user, **data) data = {"code": 0, "msg": "用户添加成功~"} return JsonResponse(data) elif request.method == "DELETE": user = user_get(request) request_data = QueryDict(request.body) did = request_data.get("id").split(",") User.objects.filter(id__in=did).update(deleted_at=human_datetime(), deleted_by=user, is_active=0) data = {"code": 0, "msg": "账号删除成功~"} return JsonResponse(data)
def schedule_view(request): if request.method == "GET": did = request.GET.get("id", None) hid = request.GET.get("hid", None) if did: data = Schedule.objects.get(id=did) data = data.latest.id if hid: data = hid record = History.objects.filter(id=data).first() outputs = json.loads(record.output) host_ids = (x[0] for x in outputs if isinstance(x[0], int)) hosts_info = { x.id: x.hostname for x in Host.objects.filter(id__in=host_ids, deleted_by__id__isnull=True) } data = { 'run_time': record.run_time, 'success': 0, 'failure': 0, 'duration': 0, 'outputs': [] } for h_id, code, duration, out in outputs: key = 'success' if code == 0 else 'failure' data[key] += 1 data['duration'] += duration data['outputs'].append({ 'name': hosts_info.get(h_id, '本机'), 'code': code, 'duration': duration, 'output': out }) data['duration'] = f"{data['duration'] / len(outputs):.3f}" return render(request, "exec/schedule_view.html", data) elif request.method == "POST": did = request.POST.get("id") data = Schedule.objects.filter(id=did).first() if not data: data = {"code": 1, "msg": "未找到指定任务"} return JsonResponse(data) data = dispatch(data.command, eval(data.targets), True) score = 0 for item in data: score += 1 if item[1] else 0 history = History.objects.create( task_id=did, status=2 if score == len(data) else 1 if score else 0, run_time=human_datetime(), output=json.dumps(data)) data = {"code": 0, "msg": "执行成功", "data": history.id} return JsonResponse(data)
def _do_notify(task, mode, url, msg): if mode == '1': texts = [ '## <font color="#f90202">任务执行失败通知</font> ## ', f'**任务名称:** {task.name} ', f'**任务类型:** {task.types} ', f'**描述信息:** {msg or "请在任务计划执行历史中查看详情"} ', f'**发生时间:** {human_datetime()} ', ] data = { 'msgtype': 'markdown', 'markdown': { 'title': '任务执行失败通知', 'text': '\n\n'.join(texts) } } res = requests.post(url, json=data) elif mode == '3': data = { 'task_id': task.id, 'task_name': task.name, 'task_type': task.type, 'message': msg or '请在任务计划执行历史中查看详情', 'created_at': human_datetime() } res = requests.post(url, json=data) elif mode == '2': texts = [ '## <font color="warning">任务执行失败通知</font>', f'任务名称: {task.name}', f'任务类型: {task.type}', f'描述信息: {msg or "请在任务计划执行历史中查看详情"}', f'发生时间: {human_datetime()}', ] data = { 'msgtype': 'markdown', 'markdown': { 'content': '\n'.join(texts) } } res = requests.post(url, json=data) if res.status_code != 200: Notify.make_notify('schedule', '1', '任务执行通知发送失败', f'返回状态码:{res.status_code}, 请求URL:{url}') if mode in ['1', '3']: res = res.json() if res.get('errcode') != 0: Notify.make_notify('schedule', '1', '任务执行通知发送失败', f'返回数据:{res}')
def host(request): if request.method == "GET": data = Host.objects.all() types, system = [], [] for item in data: types.append(item.types) system.append(item.system) context = {"types": list(set(types)), "system": list(set(system))} return render(request, "host/host.html", context) elif request.method == "DELETE": user = user_get(request) request_data = QueryDict(request.body) did = request_data.get("id").split(",") Host.objects.filter(id__in=did).update(deleted_at=human_datetime(), deleted_by=user) data = {"code": 0, "msg": "主机删除成功~"} return JsonResponse(data) elif request.method == "POST": key = request.FILES.get("file") data = key.read() data = {"code": 0, "msg": "上传成功", "data": data.decode('utf-8')} return JsonResponse(data)
def edit_k8s(request): user = user_get(request) request_data = QueryDict(request.body) d_id = request_data.get("id", None) if request.method == "GET": d_id = request.GET.get("id", None) if d_id: data = K8s.objects.get(id=d_id) else: data = "" return render(request, "k8s/edit_k8s.html", {"data": data}) elif request.method == "POST": data = { "name": request_data.get('name'), "ca": request_data.get('ca'), "config": request_data.get("config"), "desc": request_data.get('desc'), } hostname = Host.objects.get(hostname=request_data.get('hostname'), deleted_by__id__isnull=True) if d_id: K8s.objects.filter(id=d_id).update(hostname=hostname, **data) data = {"code": 0, "msg": "修改成功~"} else: if K8s.objects.filter(hostname=hostname, deleted_by__id__isnull=True).exists(): data = {"code": 1, "msg": "添加失败,主机已存在~"} else: K8s.objects.create(created_by=user, hostname=hostname, **data) data = {"code": 0, "msg": "主机添加成功~"} return JsonResponse(data) elif request.method == "DELETE": K8s.objects.filter(id__in=d_id.split(",")).update( deleted_at=human_datetime(), deleted_by=user) data = {"code": 0, "msg": "删除成功."} return JsonResponse(data)
def schedule_edit(request): user = user_get(request) request_data = QueryDict(request.body) did = request_data.get("id", None) if request.method == "GET": did = request.GET.get("id") if did: data = Schedule.objects.get(id=did) data.targets = ','.join(eval(data.targets)) data.rst_notify = eval(data.rst_notify) else: data = "" return render(request, "exec/schedule_edit.html", {"data": data}) elif request.method == "POST": data = { 'name': request.POST.get("name"), 'types': request.POST.get("types"), 'command': request.POST.get("command"), 'targets': request.POST.get("targets").split(","), 'desc': request.POST.get("desc"), 'rst_notify': { "mode": request_data.get('rst_notify.mode'), 'value': request_data.get('rst_notify.value') } } trigger = request.POST.get("trigger") if did: if trigger == "interval": interval = request.POST.get("interval") Schedule.objects.filter(id=did).update(trigger=trigger, trigger_args=interval, **data) elif trigger == "date": date = request.POST.get("date") Schedule.objects.filter(id=did).update(trigger=trigger, trigger_args=date, **data) elif trigger == "cron": cron = request.POST.get("cron") Schedule.objects.filter(id=did).update(trigger=trigger, trigger_args=cron, **data) obj = Schedule.objects.filter(id=did).first() if obj and obj.is_active: message = {'id': obj.id, 'action': 'modify'} message.update({ 'trigger': obj.trigger, 'trigger_args': obj.trigger_args, 'command': obj.command, 'targets': obj.targets }) rds_cli = get_redis_connection() rds_cli.lpush(settings.SCHEDULE_KEY, json.dumps(message)) data = {"code": 0, "msg": "类别修改成功~"} else: if trigger == "interval": interval = request.POST.get("interval") Schedule.objects.create(created_by=user, trigger=trigger, trigger_args=interval, **data) elif trigger == "date": date = request.POST.get("date") Schedule.objects.create(created_by=user, trigger=trigger, trigger_args=date, **data) elif trigger == "cron": cron = request.POST.get("cron") Schedule.objects.create(created_by=user, trigger=trigger, trigger_args=cron, **data) data = {"code": 0, "msg": "任务添加成功~"} return JsonResponse(data) elif request.method == "DELETE": obj = Schedule.objects.filter(id=did).first() if obj: if obj.is_active: data = {"code": 1, "msg": "该任务在运行中,请先停止任务再尝试删除"} else: Schedule.objects.filter(id=did).update( deleted_at=human_datetime(), deleted_by=user) data = {"code": 0, "msg": "任务删除成功"} return JsonResponse(data) elif request.method == "PUT": obj = Schedule.objects.filter(id=did).first() if obj: if obj.is_active: obj.is_active = 0 obj.save() message = {'id': did, 'action': 'remove'} data = {"code": 1, "msg": "任务已停止"} else: message = {'id': did, 'action': 'add'} message.update({ 'trigger': obj.trigger, 'trigger_args': obj.trigger_args, 'command': obj.command, 'targets': obj.targets }) obj.is_active = 1 obj.save() data = {"code": 0, "msg": "任务启动成功"} rds_cli = get_redis_connection() rds_cli.lpush(settings.SCHEDULE_KEY, json.dumps(message)) return JsonResponse(data)
def parsing_edit(request): request_data = QueryDict(request.body) user = user_get(request) did = request_data.get("id", None) if request.method == "GET": dom = Domains.objects.filter(deleted_by__id__isnull=True) did = request.GET.get('id', None) if did: data = Parsing.objects.get(id=did) else: data = "" return render(request, "domains/parsing_edit.html", { "data": data, "domain": dom }) elif request.method == "POST": data = { "RR": request_data.get("RR"), "Type": request_data.get("Type"), "Value": request_data.get("Value"), "TTL": request_data.get("TTL"), "Line": request_data.get("Line"), "Priority": request_data.get("Priority", None), "RecordId": request_data.get("RecordId", None), } pars = Domains.objects.get(id=request_data.get("domain")) if did: api_key = Ali_Edit_Parsing(pars.api.key, pars.api.secret, pars.api.region, **data) if api_key['code'] == 0: Parsing.objects.filter(id=did).update(**data) data = {"code": 0, "msg": "域名解析修改成功~"} else: data = {"code": 0, "msg": "域名解析失败~"} else: api_key = Ali_Edit_Parsing(pars.api.key, pars.api.secret, pars.api.region, pars.domain, **data) if api_key['code'] == 0: data['RecordId'] = json.loads(api_key['data'])['RecordId'] Parsing.objects.create(created_by=user, **data, domain=pars) data = {"code": 0, "msg": "域名解析添加成功~"} else: data = {"code": 0, "msg": "域名解析失败~"} return JsonResponse(data) elif request.method == "DELETE": Pars = Parsing.objects.filter(id=did) data = Ali_Del_Parsing(Pars.first().domain.api.key, Pars.first().domain.api.secret, Pars.first().domain.api.region, Pars.first().RecordId) if data['code'] == 0: Pars.update(deleted_at=human_datetime(), deleted_by=user) data = {"code": 0, "msg": "域名解析同步删除成功~"} else: Pars.update(deleted_at=human_datetime(), deleted_by=user) data = {"code": 0, "msg": "域名解析本地删除成功~"} return JsonResponse(data) elif request.method == "SYNC": domain = Domains.objects.filter(deleted_by__id__isnull=True) if domain: for item in domain: api_key = Ali_Parsing(item.api.key, item.api.secret, item.api.region, item.domain) if api_key['code'] == 0: data = json.loads(api_key['data']) for dom in data['DomainRecords']['Record']: if "Priority" in dom: Priority = dom['Priority'] else: Priority = None di_ct = { 'RR': dom['RR'], 'Line': dom['Line'], 'Type': dom['Type'], 'Value': dom['Value'], 'RecordId': dom['RecordId'], 'TTL': dom['TTL'], 'domain_id': item.id, 'Priority': Priority } Parsing.objects.update_or_create( RecordId=dom['RecordId'], defaults=di_ct, created_by=user) else: pass data = {"code": 0, "msg": "域名解析同步成功~"} else: data = {"code": 1, "msg": "域名查找失败~"} return JsonResponse(data)
def api_edit(request): request_data = QueryDict(request.body) did = request_data.get("id", None) user = user_get(request) if request.method == "GET": did = request.GET.get('id') if did: data = Api.objects.get(id=did) else: data = "" return render(request, "domains/api_edit.html", {"data": data}) elif request.method == "POST": data = { "name": request_data.get("name"), "cloud": request_data.get("cloud"), "region": request_data.get("region"), "key": request_data.get("key"), "secret": request_data.get("secret"), "desc": request_data.get("desc"), } api_key = Ali_Domain(data["key"], data["secret"], data["region"]) if api_key['code'] == 0: if did: Api.objects.filter(id=did).update(**data) data = {"code": 0, "msg": "API修改成功~"} else: Api.objects.create(created_by=user, **data) data = {"code": 0, "msg": "API添加成功~"} else: data = {"code": 0, "msg": "API接口验证失败~"} return JsonResponse(data) elif request.method == "DELETE": Api.objects.filter(id__in=did.split(',')).update( deleted_at=human_datetime(), deleted_by=user) data = {"code": 0, "msg": "API删除成功~"} return JsonResponse(data) elif request.method == "PUT": if did: Api_obj = Api.objects.filter(id__in=did) else: Api_obj = Api.objects.all() if Api_obj.count() < 0: data = {"code": 1, "msg": f"请添加API接口"} else: li_st = [] cg, sb = 0, 0 for item in Api_obj: data = Ali_Domain(item.key, item.secret, item.region) if data['code'] == 0: data = json.loads(data['data']) for i in data['Domains']['Domain']: di_ct = { 'api_id': item.id, 'domain': i['DomainName'], 'dns1': i['DnsServers']['DnsServer'][0], 'dns2': i['DnsServers']['DnsServer'][1] } Domains.objects.update_or_create( domain=i['DomainName'], defaults=di_ct, created_by=user) cg += 1 else: li_st.append(item.name) sb += 1 if sb > 1: data = { "code": 1, "msg": f"同步异常,总:{Api_obj.count()},成功:{cg},失败:{sb},失败名称{str(li_st)}" } else: data = { "code": 0, "msg": f"同步成功,总:{Api_obj.count()},成功:{cg},失败:{sb}" } return JsonResponse(data)