示例#1
0
    def get(self, request):

        ret = {"result": 0, "msg": None}
        idc_id = request.GET.get("id", 0)

        ## ajax 请求的权限验证
        if not request.user.has_perm(self.permission_required):
            ret["result"] = 1
            ret["msg"] = "Sorry,你没有权限,请联系运维!"
            return JsonResponse(ret)

        try:
            idc_obj = IDC.objects.get(id__exact=idc_id)
        except IDC.DoesNotExist:
            ret["result"] = 1
            ret["msg"] = "IDC id: %s 不存在,请刷新重试" % (idc_id)
            wslog_error().error("IDC 模型对象id: %s 不存在" % (idc_id))
            return JsonResponse(ret)
        try:
            idc_info = model_to_dict(idc_obj)
        except Exception as e:
            ret["result"] = 1
            ret["msg"] = "IDC 模型对象转dict 失败,请查看日志"
            wslog_error().error("IDC 模型对象id: %s 转dict 失败,错误信息: %s" %
                                (idc_id, e.args))
        else:
            ret["idc_info"] = idc_info
            wslog_info().info("IDC 模型对象id: %s 查询成功并返回给前端" % (idc_id))

        return JsonResponse(ret)
示例#2
0
    def post(self, request):
        ret = {"result": 0, "msg": None}

        ## ajax 请求的权限验证
        if not request.user.has_perm(self.permission_required):
            ret["result"] = 1
            ret["msg"] = "Sorry,你没有'删除 cmdb 模型对象'的权限,请联系运维!"
            return JsonResponse(ret)

        cid = request.POST.get("id")

        ret = GetCmdbObj(cid, ret)
        if ret["result"] == 1:
            return JsonResponse(ret)

        cmdb_obj = ret["msg"]

        try:
            cmdb_obj.delete()
        except Exception as e:
            ret["result"] = 1
            ret["msg"] = "CmdbModel 删除对象 %s 失败,请查看日志" % (cmdb_obj.name)
            wslog_error().error("CmdbModel 删除 ID: %s 的对象失败,错误信息: %s" %
                                (cid, e.args))
        else:
            ret["msg"] = "CmdbModel 删除对象 %s 成功" % (cmdb_obj.name)
            wslog_info().info("CmdbModel 删除对象 %s 成功" % (cmdb_obj.name))

        return JsonResponse(ret)
示例#3
0
def WxMsgSend(send_data):
    r = requests.post(wx_url, data=send_data)
    if r.content.decode('utf8') == 'OK':
        wslog_info().info("微信消息 发送 成功")
    else:
        wslog_error().error("微信消息 发送 失败,错误信息: %s" %
                            (json.loads(r.content)["errmsg"]))
示例#4
0
def mail_send_html(subject, message, mail_to, html_content=None):
    ''' 如果html_content 为None 则邮件不能发送, 而上面那种方式则不会 '''
    try:
        m = EmailMultiAlternatives(subject, message, EMAIL_HOST_USER, mail_to)
        m.attach_alternative(html_content, "text/html")
        m.send()
    except Exception as e:
        wslog_error().error("邮件: '%s' 发送失败,错误信息: %s" % (subject, e.args))
    else:
        wslog_info().info("邮件: '%s' 发送成功" % (subject))
示例#5
0
def mail_send(subject, message, mail_to, html_content=None):
    try:
        send_mail(subject,
                  message,
                  EMAIL_HOST_USER,
                  mail_to,
                  fail_silently=False,
                  html_message=html_content)
    except Exception as e:
        wslog_error().error("邮件: '%s' 发送失败,错误信息: %s" % (subject, e.args))
    else:
        wslog_info().info("邮件: '%s' 发送成功" % (subject))
示例#6
0
    def post(self, request):
        ret = {"result": 0}

        ## ajax 请求的权限验证
        if not request.user.has_perm(self.permission_required):
            ret["result"] = 1
            ret["msg"] = "Sorry,你没有权限,请联系运维!"
            return JsonResponse(ret)

        fr_id = request.POST.get("id", 0)
        fr_form = FirewallRulesChangeForm(request.POST)

        if not fr_form.is_valid():
            ret['result'] = 1
            error_msg = json.loads(fr_form.errors.as_json(escape_html=False))
            ret["msg"] = '\n'.join(
                [i["message"] for v in error_msg.values() for i in v])
            return JsonResponse(ret)

        try:
            fr_obj = FirewallRulesModel.objects.get(id__exact=fr_id)
        except FirewallRulesModel.DoesNotExist:
            ret["result"] = 1
            ret["msg"] = "FirewallRulesModel id: %s 不存在,请刷新重试" % (fr_id)
            wslog_error().error("FirewallRulesModel 模型对象id: %s 不存在" % (fr_id))
            return JsonResponse(ret)

        fr_change_info = fr_form.cleaned_data
        try:
            fr_obj.s_hostname = fr_change_info.get("s_hostname")
            fr_obj.s_ip = fr_change_info.get("s_ip")
            fr_obj.d_hostname = fr_change_info.get("d_hostname")
            fr_obj.d_ip = fr_change_info.get("d_ip")
            fr_obj.d_port = fr_change_info.get("d_port")
            fr_obj.protocol = fr_change_info.get("protocol")
            fr_obj.comment = fr_change_info.get("comment")
            fr_obj.update_user = request.user.username
            fr_obj.save(update_fields=[
                "s_hostname", "s_ip", "d_hostname", "d_ip", "d_port",
                "protocol", "comment", "update_user", "last_update_time"
            ])
        except Exception as e:
            ret["result"] = 1
            ret["msg"] = "FirewallRulesModel: %s 修改规则保存失败,请查看日志" % (fr_id)
            wslog_error().error("FirewallRulesModel: id-%s 保存修改规则失败,错误信息: %s" %
                                (fr_id, e.args))
        else:
            ret["msg"] = "FirewallRulesModel: %s 更改规则成功" % (fr_id)
            wslog_info().info("FirewallRulesModel: id-%s 更改规则成功" % (fr_id))

        return JsonResponse(ret)
示例#7
0
    def post(self, request):
        ret = {"result": 0}

        if not request.user.has_perm(self.permission_required):
            ret["result"] = 1
            ret["msg"] = "Sorry,你没有权限,请联系运维!"
            return JsonResponse(ret)

        user_obj = request.user
        firewall_rules_pre = request.POST.get("firewall_rules", None)

        if not firewall_rules_pre:
            ret["result"] = 1
            ret["msg"] = "防火墙工单必须导入包含防火墙策略的xlsx表"
            return JsonResponse(ret)

        firewall_rules_list = json.loads(firewall_rules_pre)

        for fr in firewall_rules_list:
            firewall_rule_form = FirewallRulesForm(fr)
            if not firewall_rule_form.is_valid():
                ret["result"] = 1
                error_msg = json.loads(
                    firewall_rule_form.errors.as_json(escape_html=False))
                fr_error = "%s -> %s:%s" % (fr.get(
                    "s_ip", None), fr.get("d_ip", None), fr.get(
                        "d_port", None))
                ret["msg"] = '\n'.join(
                    [i["message"] for v in error_msg.values()
                     for i in v]) + '\n' + fr_error
                return JsonResponse(ret)

            print("firewall_rule_form.cleaned_data: ",
                  firewall_rule_form.cleaned_data)
            try:
                fr_obj = FirewallRulesModel(**firewall_rule_form.cleaned_data)
                fr_obj.commit_by = user_obj.username
                fr_obj.save()
            except Exception as e:
                ret["result"] = 1
                ret["msg"] = "FirewallRulesModel 模型对象保存失败,错误信息: %s" % (e.args)
                wslog_error().error("添加 FirewallRulesModel 模型对象 '%s -> %s:%s' 失败,错误信息: %s" % (firewall_rule_form.cleaned_data.get('s_ip') ,\
                                                                                                       firewall_rule_form.cleaned_data.get('d_ip'),\
                                                                                                       firewall_rule_form.cleaned_data.get('d_port'),\
                                                                                                       e.args))
                return JsonResponse(ret)

        ret["msg"] = "防火墙规则导入成功"
        wslog_info().info("防火墙规则导入成功")

        return JsonResponse(ret)
示例#8
0
    def get(self, request):
        ret = {"result": 0, "msg": None}

        ## ajax 请求的权限验证
        if not request.user.has_perm(self.permission_required):
            ret["result"] = 1
            ret["msg"] = "Sorry,你没有'修改 cmdb 模型对象'的权限,请联系运维!"
            return JsonResponse(ret)

        cid = request.GET.get("id")

        ret = GetCmdbObj(cid, ret)
        if ret["result"] == 1:
            return JsonResponse(ret)

        cmdb_obj = ret["msg"]

        try:
            ips_list = [{
                "id": i["id"],
                "private_ip": i['private_ip']
            } for i in ServerModel.objects.filter(
                env__exact=cmdb_obj.env, status__exact="Running").values(
                    "id", "private_ip")]
        except Exception as e:
            ret["result"] = 1
            ret["msg"] = "ServerModel 模型中未查到 env: %s 的对象" % (cmdb_obj.env)
            wslog_error().error("ServerModel 模型中未查到 env: %s 的对象,错误信息: %s" %
                                (cmdb_obj.env, e.args))
            return JsonResponse(ret)

        try:
            cmdb_info = model_to_dict(cmdb_obj)
            del cmdb_info["offline_time"]
            cmdb_info["ips"] = [i["id"] for i in cmdb_obj.ips.values("id")]
            cmdb_info["ips_list"] = ips_list
            cmdb_info["dev_team"] = list(cmdb_obj.dev_team.values("id"))
        except Exception as e:
            ret["result"] = 1
            ret["msg"] = "CmdbModel 模型对象 %s 转为 dict 失败,请查看日志" % (cmdb_obj.name)
            wslog_error().error("CmdbModel 模型对象 %s 转为 dict 失败,错误信息: %s" %
                                (cmdb_obj.name, e.args))
        else:
            ret["msg"] = "CmdbModel 模型对象 %s 转 dict 处理成功" % (cmdb_obj.name)
            wslog_info().info("CmdbModel 模型对象 %s 转 dict 处理成功,可以提交给前端" %
                              (cmdb_obj.name))
            ret["cmdb_info"] = cmdb_info

        return JsonResponse(ret)
示例#9
0
文件: cron.py 项目: zeus911/WS-OPS
def CmdbStatisticByDayCrontab():
    myday = date.today().isoformat()
    count = CmdbModel.objects.count()

    csbd_obj = CmdbStatisticByDayModel()

    try:
        csbd_obj.myday = myday
        csbd_obj.count = count
        csbd_obj.save()
    except Exception as e:
        wslog_error().error("统计 %s 的应用总数失败,错误信息: %s" % (myday, e.args))
        sys.exit()
    else:
        wslog_info().info("统计 %s 的应用总数成功" % (myday))
示例#10
0
文件: cron.py 项目: zeus911/WS-OPS
def ServerStatisticByDayCrontab():
    myday = date.today().isoformat()
    count = ServerModel.objects.count()

    ssbd_obj = ServerStatisticByDayModel()

    try:
        ssbd_obj.myday = myday
        ssbd_obj.count = count
        ssbd_obj.save()
    except Exception as e:
        wslog_error().error("统计 %s 的服务器总数失败,错误信息: %s" % (myday, e.args))
        sys.exit()
    else:
        wslog_info().info("统计 %s 的服务器总数成功" % (myday))
示例#11
0
    def post(self, request):

        ret = {"result": 0, "msg": None}

        ## ajax 请求的权限验证
        if not request.user.has_perm(self.permission_required):
            ret["result"] = 1
            ret["msg"] = "Sorry,你没有权限,请联系运维!"
            return JsonResponse(ret)

        idc_id = request.POST.get("id", 0)
        idc_form = IdcChangeForm(request.POST)

        if not idc_form.is_valid():
            ret['result'] = 1
            error_msg = json.loads(idc_form.errors.as_json(escape_html=False))
            ret["msg"] = '\n'.join(
                [i["message"] for v in error_msg.values() for i in v])
            return JsonResponse(ret)

        try:
            idc_obj = IDC.objects.get(id__exact=idc_id)
        except IDC.DoesNotExist:
            ret["result"] = 1
            ret["msg"] = "IDC id: %s 不存在,请刷新重试" % (idc_id)
            wslog_error().error("IDC 模型对象id: %s 不存在" % (idc_id))
            return JsonResponse(ret)

        idc_change_info = idc_form.cleaned_data

        try:
            idc_obj.user = idc_change_info.get("user")
            idc_obj.email = idc_change_info.get("email")
            idc_obj.phone = idc_change_info.get("phone")
            idc_obj.address = idc_change_info.get("address")
            idc_obj.save(update_fields=[
                "user", "email", "phone", "address", "last_update_time"
            ])
        except Exception as e:
            ret["result"] = 1
            ret["msg"] = "IDC: %s 修改信息保存失败,请查看日志" % (idc_obj.cn_name)
            wslog_error().error("IDC: id-%s 保存修改信息失败,错误信息: %s" %
                                (idc_id, e.args))
        else:
            ret["msg"] = "IDC: %s 更改信息成功" % (idc_obj.cn_name)
            wslog_info().info("IDC: id-%s 更改信息成功" % (idc_id))

        return JsonResponse(ret)
示例#12
0
    def post(self, request):

        ret = {"result": 0, "msg": None}

        ## ajax 请求的权限验证
        if not request.user.has_perm(self.permission_required):
            ret["result"] = 1
            ret["msg"] = "Sorry,你没有'添加 cmdb 模型对象'的权限,请联系运维!"
            return JsonResponse(ret)

        cmdb_add_form = CmdbAddForm(request.POST)

        if not cmdb_add_form.is_valid():
            ret["result"] = 1
            error_msg = json.loads(
                cmdb_add_form.errors.as_json(escape_html=False))
            ret["msg"] = '\n'.join(
                [i["message"] for v in error_msg.values() for i in v])
            return JsonResponse(ret)

        try:
            cmdb_obj = CmdbModel(**cmdb_add_form.cleaned_data)
            cmdb_obj.save()
        except Exception as e:
            ret["result"] = 1
            ret["msg"] = "CmdbModel 模型对象: %s 添加失败,请查看日志" % (
                cmdb_add_form.cleaned_data.get("name"))
            wslog_error().error(
                "CmdbModel 模型对象: %s 添加失败,错误信息: %s" %
                (cmdb_add_form.cleaned_data.get("name"), e.args))
            return JsonResponse(ret)

        ips = request.POST.getlist("ips")

        ret = CmdbIpsUpdate(ips, cmdb_obj, ret)

        if ret["result"] == 0:
            ret["msg"] = "cmdb 模型对象: %s 添加成功" % (
                cmdb_add_form.cleaned_data.get("name"))
            wslog_info().info("CmdbModel 模型对象: %s 添加成功" %
                              (cmdb_add_form.cleaned_data.get("name")))

        return JsonResponse(ret)
示例#13
0
def ZabbixHostAutoSync():
    zabbix_api_get_host = zapi.host.get(output=["host", "status"],
                                        selectInterfaces=['ip', 'port'])
    for h in zabbix_api_get_host:
        z_data = {}
        z_data['hostid'] = h['hostid']
        z_data['status'] = h['status']
        z_data['host'] = h['host']
        if not h['interfaces']:
            wslog_error().error("该hostid: %s 下不存在interface" % (h['hostid']))
            continue

        h_ips = list(set([i["ip"] for i in h['interfaces']]))
        if len(h_ips) > 1:
            wslog_error().error("该hostid: %s 下 ip 地址 %s 不唯一" %
                                (h['hostid'], ";".join(h_ips)))
            continue

#        if h_ips[0].startswith("10.82"):
#            wslog_error().error("该hostid: %s ip 地址 %s 不是阿里云上的IP,暂时不处理" %(h['hostid'],h_ips[0]))
#            continue
        z_data['ip'] = h_ips[0]

        try:
            s_obj = ServerModel.objects.get(private_ip__exact=z_data['ip'])
        except ServerModel.DoesNotExist:
            wslog_error().error("ServerModel 模型加不存在 IP 地址: %s 的对象" %
                                (z_data['ip']))
            continue

        try:
            zh = ZabbixHostModel(**z_data)
            zh.server = s_obj
            zh.save()
        except Exception as e:
            wslog_error().error("模型 ZabbixHostModel 模型对象 %s 创建失败,错误信息: %s" %
                                (z_data['ip'], e.args))
            continue
        else:
            wslog_info().info("模型 ZabbixHostModel 模型对象 %s 创建成功" %
                              (z_data['ip']))
示例#14
0
文件: cron.py 项目: zeus911/WS-OPS
def ServerAliyunAutoRefreshCrontab():

    id_list = [
        i["id"] for i in ServerModel.objects.exclude(
            private_ip__startswith="10.82").values("id")
    ]
    for id in id_list:
        try:
            server_aliyun_obj = ServerModel.objects.get(id__exact=id)
            private_ip = server_aliyun_obj.private_ip
        except Exception as e:
            wslog_error().error("获取server_aliyun 对象失败,错误信息: %s" % (e.args))
            continue

        ret = GetServerInfoFromApi(private_ip, server_aliyun_obj)

        if ret["result"] == 1:
            wslog_error().error("服务器: %s 自动刷新失败,错误信息: %s" %
                                (private_ip, ret["msg"]))
            continue
        else:
            wslog_info().info("服务器: %s 自动刷新成功" % (private_ip))
示例#15
0
    def get(self, request):
        ret = {"result": 0, "msg": None}

        cid = request.GET.get('id')
        ret = GetCmdbObj(cid, ret)
        if ret["result"] == 1:
            return JsonResponse(ret)

        cmdb_obj = ret["msg"]

        try:
            cmdb_info = CmdbModel.objects.filter(id__exact=cid).values()[0]
            cmdb_info["env"] = cmdb_obj.get_env_display()
            cmdb_info["type"] = cmdb_obj.get_type_display()
            cmdb_info["way"] = cmdb_obj.get_way_display()
            cmdb_info["dev_team"] = ' ; '.join(
                [i.get("name") for i in cmdb_obj.dev_team.values("name")])
            cmdb_info["ips"] = "\n".join([
                ip["private_ip"]
                for ip in list(cmdb_obj.ips.values("private_ip"))
            ])
            cmdb_info["ports"] = cmdb_obj.ports.replace(";", "\n")
            if cmdb_info.get("online_time"):
                cmdb_info["online_time"] = cmdb_info["online_time"]
            if cmdb_info.get("offline_time"):
                cmdb_info["offline_time"] = cmdb_info["offline_time"]
            if cmdb_info.get("last_update_time"):
                cmdb_info["last_update_time"] = cmdb_info["last_update_time"]
        except Exception as e:
            ret["result"] = 1
            ret["msg"] = "CmdbModel 对象 %s 转为 dict 失败,请查看日志" % (cmdb_obj.name)
            wslog_error().error("CmdbModel 对象 %s 转为 dict 失败,错误信息: %s" %
                                (cmdb_obj.name, e.args))
        else:
            wslog_info().info("获取 CmdbModel 对象 %s 信息成功" % (cmdb_obj.name))
            ret["msg"] = "CmdbModel 对象 %s 获取成功" % (cmdb_obj.name)
            ret["cmdb_info"] = cmdb_info

        return JsonResponse(ret)
示例#16
0
    def post(self, request):
        ret = {"result": 0}
        version = request.POST.get('version')
        module_name = request.POST.get('module_name')
        try:
            PublishVersionModel.objects.get(version__exact=version)
        except PublishVersionModel.DoesNotExist:
            pass
        else:
            ret["result"] = 1
            ret["msg"] = "版本: %s 已经存在" % (version)
            wslog_error().error("jenkis post 打包信息失败,版本记录表中已经存在该版本: %s" %
                                (version))

        try:
            m_obj = CmdbModel.objects.get(name__exact=module_name)
        except CmdbModel.DoesNotExist:
            ret["result"] = 1
            ret["msg"] = "modelu_name: %s 不存在,因此jenkins打包的版本不能写库" % (
                module_name)
            wslog_error().error(ret["msg"])
        else:
            version_info = request.POST.copy()
            version_info.pop("module_name")

        try:
            pv_obj = PublishVersionModel(**version_info.dict())
            pv_obj.module_name = m_obj
            pv_obj.save()
        except Exception as e:
            ret["result"] = 1
            ret["msg"] = "jenkins打包的版本: %s 不能写库,请查看日志" % (version)
            wslog_error().error("jenkins打包的版本: %s 不能写库,错误日志: %s" %
                                (version, e.args))
        else:
            ret["msg"] = "jenkins打包的版本: %s post 成功" % (version)
            wslog_info().info(ret["msg"])
        return JsonResponse(ret)
示例#17
0
def ServerAliyunAutoAdd():

    local_result = ServerModel.objects.exclude(
        private_ip__startswith="10.82").values("private_ip")
    local_server_list = [i['private_ip'] for i in local_result]
    local_server_add = []
    local_server_delete = []

    try:
        aliyun_result = AliyunDescribeInstances()
    except Exception as e:
        wslog_error().error("服务器自动添加失败,错误信息: %s" % (e.args))
    else:
        aliyun_ecs_list = [
            i["NetworkInterfaces"]["NetworkInterface"][0]["PrimaryIpAddress"]
            for i in aliyun_result
        ]
        local_server_add = list(
            set(aliyun_ecs_list).difference(set(local_server_list)))
        local_server_delete = list(
            set(local_server_list).difference(set(aliyun_ecs_list)))

    idc_obj = IDC.objects.get(pk=1)

    #添加服务器到本地 ServerModel 模型
    if local_server_add:
        for s in local_server_add:
            server = ServerModel()
            server.private_ip = s
            server.idc = idc_obj
            try:
                server.save()
            except Exception as e:
                wslog_error().error("自动添加服务器: %s,错误信息: %s" % (s, e.args))
                continue

            try:
                with open("/etc/ansible/hosts", 'a+') as f:
                    f.seek(0)
                    if "%s\n" % (s) not in f.readlines():
                        f.write("%s\n" % (s))
            except Exception as e:
                wslog_error().error("自动添加服务器: %s,错误信息: %s" % (s, e.args))
                continue
            else:
                wslog_info().info("服务器: %s 自动添加成功" % (s))
                continue

    #将在阿里云上不存在的服务器,从本地的 ServerModel 模型中删除
    if local_server_delete:
        for s in local_server_delete:
            try:
                server_obj = ServerModel.objects.get(private_ip__exact=s)
            except ServerModel.DoesNostExist:
                wslog_error().error("自动删除服务器: %s ,已经不存在,所以不用删除" % (s))
                continue
            except Exception as e:
                wslog_error().error("自动删除服务器: %s,错误信息:%s" % (s, e.args))
                continue
            try:
                server_obj.delete()
            except Exception as e:
                wslog_error().error("自动删除服务器: %s,错误信息: %s" % (s, e.args))
                continue
            else:
                wslog_info().info("服务器: %s 自动删除成功" % (s))
                continue
示例#18
0
文件: cron.py 项目: zeus911/WS-OPS
def CmdbAutoAddCrontab():
    server_ip_name_list = list(
        ServerModel.objects.exclude(private_ip__startswith="10.82").values(
            "id", "private_ip", "instance_name", "status"))

    #根据 CmdbModel 模型中的 instance_name 字段自动添加 CMDB,如果没有该字段则不能自动添加 CMDB,
    #因此该方法适用于 Aliyun 上的服务器,IDC中的服务器需要手动添加,该方法也不会修改IDC服务器 CMDB 的信息
    for ss in server_ip_name_list:
        try:
            ss_obj = ServerModel.objects.get(id__exact=ss["id"])
        except Exception as e:
            wslog_error().error("获取服务器 %s 对象失败,错误信息: %s" %
                                (ss["private_ip"], e.args))
            continue

        if ss["status"] != "Running":
            wslog_info().info("该服务器: %s 状态 %s 所以需要删除其关联的CMDB" %
                              (ss["private_ip"], ss["status"]))
            ss_obj.cmdbmodel_set.clear()
            continue

        if not ss["instance_name"]:
            wslog_error().error("该服务器: %s 没有实例名" % (ss["private_ip"]))
            continue

        app_name_list = ss["instance_name"].split("_")[-2::-1]
        if not app_name_list:
            wslog_error().error("该服务器: %s 实例名 %s 格式不正确" %
                                (ss["private_ip"], ss["instance_name"]))
            continue

        cmdb_name_list = [
            i["name"] for i in list(CmdbModel.objects.values("name"))
        ]

        cmdb_obj_list = []
        for app in app_name_list:
            cmdb_data = {
                "way": "0",
                "type": "1",
                "env": "online",
                "status": "0",
                "ports": "8080"
            }
            if not cmdb_name_list:
                cmdb_data["name"] = app
                try:
                    cc = CmdbModel(**cmdb_data)
                    cc.save()
                    cc.ips.set([ss_obj])
                    ''' 每个模块的管理组都要关联 ops 组 '''
                    cc.dev_team.set(
                        list(Group.objects.filter(name__exact='ops')))
                except Exception as e:
                    wslog_error().error("CmdbModel 自动添加失败,错误信息: %s" % (e.args))
                    continue
                else:
                    wslog_info().info(
                        "CmdbModel 自动添加对象 %s 并关联 ServerModel 成功" % (app))
                    continue

            if app in cmdb_name_list:
                try:
                    cmdb_obj = CmdbModel.objects.get(name__exact=app)
                except Exception as e:
                    wslog_error().error("CmdbModel 查询对象 %s 失败,错误信息: %s" %
                                        (app, e.args))
                    continue
                cmdb_obj_list.append(cmdb_obj)
            else:
                cmdb_data["name"] = app
                try:
                    cm_obj = CmdbModel(**cmdb_data)
                    cm_obj.save()
                except Exception as e:
                    wslog_error().error("CmdbModel 自动添加失败,错误信息: %s" % (e.args))
                    continue
                else:
                    wslog_info().info("CmdbModel 自动添加对象 %s 成功" % (app))
                    ''' 每个模块的管理组都要关联 ops 组 '''
                    cm_obj.dev_team.set(
                        list(Group.objects.filter(name__exact='ops')))
                    cmdb_obj_list.append(cm_obj)
        if cmdb_obj_list:
            ss_obj.cmdbmodel_set.set(cmdb_obj_list)

        try:
            CmdbModel.objects.filter(ips__private_ip__exact=None).delete()
        except Exception as e:
            wslog_error().error("CmdbModel 自动删除关联IP为空的对象失败,错误信息: %s" %
                                (e.args))
示例#19
0
    def post(self, request):
        ret = {"result": 0, "msg": None}

        ## ajax 请求的权限验证
        if not request.user.has_perm(self.permission_required):
            ret["result"] = 1
            ret["msg"] = "Sorry,你没有'修改 cmdb 模型对象'的权限,请联系运维!"
            return JsonResponse(ret)

        cid = request.POST.get("id")
        ret = GetCmdbObj(cid, ret)

        if ret["result"] == 1:
            return JsonResponse(ret)

        cmdb_obj = ret["msg"]

        cmdb_update_form = CmdbUpdateForm(request.POST)
        if not cmdb_update_form.is_valid():
            ret["result"] = 1
            error_msg = json.loads(
                cmdb_update_form.errors.as_json(escape_html=False))
            ret["msg"] = '\n'.join(
                [i["message"] for v in error_msg.values() for i in v])
            return JsonResponse(ret)

        try:
            cmdb_obj.env = cmdb_update_form.cleaned_data.get("env")
            cmdb_obj.type = cmdb_update_form.cleaned_data.get("type")
            cmdb_obj.way = cmdb_update_form.cleaned_data.get("way")
            cmdb_obj.describe = cmdb_update_form.cleaned_data.get("describe")
            cmdb_obj.path = cmdb_update_form.cleaned_data.get("path")
            cmdb_obj.log = cmdb_update_form.cleaned_data.get("log")
            cmdb_obj.ports = cmdb_update_form.cleaned_data.get("ports")
            cmdb_obj.script = cmdb_update_form.cleaned_data.get("script")
            cmdb_obj.ansible_playbook = cmdb_update_form.cleaned_data.get(
                "ansible_playbook")
            cmdb_obj.status = cmdb_update_form.cleaned_data.get("status")
            cmdb_obj.save(update_fields=[
                "env", "type", "way", "describe", "path", "log", "ports",
                "script", "ansible_playbook", "status", "last_update_time"
            ])
        except Exception as e:
            ret["result"] = 1
            ret["msg"] = "CmdbModel 模型对象更新失败,请查看日志" % (cmdb_obj.name)
            wslog_error().error("CmdbModel 模型对象 %s 更新失败,错误信息: %s" %
                                (cmdb_obj.name, e.args))
            return JsonResponse(ret)

        ips = request.POST.getlist("ips")
        ret = CmdbIpsUpdate(ips, cmdb_obj, ret)

        if ret["result"] == 1:
            return JsonResponse(ret)

        group_list = request.POST.getlist("dev_team")
        ret = CmdbDevTeamUpdate(group_list, cmdb_obj, ret)

        if ret["result"] == 0:
            ret["msg"] = "cmdb 模型对象: %s 更新成功" % (cmdb_obj.name)
            wslog_info().info("CmdbModel 模型对象: %s 更新成功" % (cmdb_obj.name))

        return JsonResponse(ret)