Beispiel #1
0
def template_sort(request, template_id):
    """
        re-order template steps.
    """
    user = request.user
    template = _template.get_template_by_params(id=template_id)
    status = 500
    data = {}
    msg = ""
    try:
        step_id_list = request.POST.get("step_id_list","")
        order = 1
        for step_id in step_id_list.split(","):
            step = _template.get_templateStep_by_params(id=step_id)
            if not step:
                msg = "template step not exist: {0}".format(step_id)
                raise Exception(msg)
            step.order = order
            step.save()
            order += 1
        status = 200
        
        change_template_sync_status(template)
    except:
        msg = u"模板步骤移动失败" if not msg else msg
        error = traceback.format_exc()
        print error
    data['msg']=msg
    return HttpResponse(json.dumps({
        'status':status,
        'result':data
    }, cls=LazyEncoder))
Beispiel #2
0
def template_clear_settings(request, template_id):
    """
        清空模板中个性配置项, 包括: 参数/目标机器配置/执行账户.
    """
    user = request.user
    template = _template.get_template_by_params(id=template_id)
    status = 500
    data = {}
    msg = u"操作失败"
    try:

        template.target = None
        template.account = None
        template.mode = enum_template.TEMPLATE_MODE_MANNUAL
        template.save()

        template_steps = TemplateStep.objects.filter(template=template,
                                                     is_delete=False)
        template_steps.update(account=None, target="")

        script_steps = TemplateStepScript.objects.filter(
            step__template=template)
        script_steps.update(parameter="", timeout=0)

        status = 200
        msg = u"操作成功"
    except:
        error = traceback.format_exc()
        print error
    data['msg'] = msg
    return HttpResponse(
        json.dumps({
            'status': status,
            'result': data
        }, cls=LazyEncoder))
Beispiel #3
0
def full_settings_save(request, template_id):
    """
        save full settings of template.

    """
    user = request.user
    status = 500
    data = {}
    try:
        mode = request.POST.get("mode", None)
        account_id = request.POST.get("template_account", None)
        if not mode or not account_id:
            msg = u"有未填写的参数项"
        else:
            account = _account.get_account_by_params(id=int(account_id))
            template = _template.get_template_by_params(id=template_id)

            ips_json = request.POST.get('full_settings_ips_hide', "")
            ip_set = get_input_ips(ips_json)
            template.target = json.dumps(list(ip_set))

            template.mode = mode
            template.account = account
            template.save()
            msg = "save success"
            status = 200
    except Exception as e:
        msg = "ops, error "
        print traceback.format_exc()
    data.update({"msg": msg})
    return HttpResponse(
        json.dumps({
            "status": status,
            "result": data
        }, cls=LazyEncoder))
Beispiel #4
0
def template_sort(request, template_id):
    """
        re-order template steps.
    """
    user = request.user
    template = _template.get_template_by_params(id=template_id)
    status = 500
    data = {}
    msg = ""
    try:
        step_id_list = request.POST.get("step_id_list", "")
        order = 1
        for step_id in step_id_list.split(","):
            step = _template.get_templateStep_by_params(id=step_id)
            if not step:
                msg = "template step not exist: {0}".format(step_id)
                raise Exception(msg)
            step.order = order
            step.save()
            order += 1
        status = 200

        change_template_sync_status(template)
    except:
        msg = u"模板步骤移动失败" if not msg else msg
        error = traceback.format_exc()
        print error
    data['msg'] = msg
    return HttpResponse(
        json.dumps({
            'status': status,
            'result': data
        }, cls=LazyEncoder))
Beispiel #5
0
def template_clear_settings(request, template_id):
    """
        清空模板中个性配置项, 包括: 参数/目标机器配置/执行账户.
    """
    user = request.user
    template = _template.get_template_by_params(id=template_id)
    status = 500
    data = {}
    msg = u"操作失败"
    try:

        template.target = None
        template.account = None
        template.mode = enum_template.TEMPLATE_MODE_MANNUAL
        template.save()

        template_steps = TemplateStep.objects.filter(template=template,is_delete=False)
        template_steps.update(account=None,target="")

        script_steps = TemplateStepScript.objects.filter(step__template=template)
        script_steps.update(parameter="",timeout=0)

        status=200
        msg = u"操作成功"
    except:
        error = traceback.format_exc()
        print error
    data['msg']=msg
    return HttpResponse(json.dumps({
        'status':status,
        'result':data
    }, cls=LazyEncoder))
Beispiel #6
0
def template_delete(request, template_id):
    """
        delete template by template_id
    """
    user = request.user
    template = _template.get_template_by_params(id=template_id)
    status = 500
    data = {}
    msg = ""
    try:
        jobs = _job.get_jobs_by_params(template=template,is_delete=False)
        if jobs:
            msg = u"删除失败: 当前模板存在关联的作业实例"
        else:
            template.is_delete = True
            template.update_user = user
            template.save()
            status=200
            msg = u"模板删除成功"
    except:
        msg = u"模板删除失败" if not msg else msg
        error = traceback.format_exc()
        print error
    data['msg']=msg
    return HttpResponse(json.dumps({
        'status':status,
        'result':data
    }, cls=LazyEncoder))
Beispiel #7
0
def template_delete(request, template_id):
    """
        delete template by template_id
    """
    user = request.user
    template = _template.get_template_by_params(id=template_id)
    status = 500
    data = {}
    msg = ""
    try:
        jobs = _job.get_jobs_by_params(template=template, is_delete=False)
        if jobs:
            msg = u"删除失败: 当前模板存在关联的作业实例"
        else:
            template.is_delete = True
            template.update_user = user
            template.save()
            status = 200
            msg = u"模板删除成功"
    except:
        msg = u"模板删除失败" if not msg else msg
        error = traceback.format_exc()
        print error
    data['msg'] = msg
    return HttpResponse(
        json.dumps({
            'status': status,
            'result': data
        }, cls=LazyEncoder))
Beispiel #8
0
def template_step_add(request):
    """
        add template step to template.
    """
    req = request.POST
    user = request.user
    status = 500
    data = {}
    msg = ""
    template_id = req.get("template_id", "")
    type_value = req.get("type_value", "")
    index = req.get("index", "")
    try:
        template = _template.get_template_by_params(id=template_id)
        if not template:
            msg = u"模板不存在"
            raise
        # if template.create_user!=user:
        #     msg = u"您没有操作该模板的权限"
        #     raise
        ########## add new step #########
        new_order = int(index) + 1
        type_value = int(type_value)
        old_steps = _template.get_templateSteps_by_params(template=template,
                                                          order__gte=new_order,
                                                          is_delete=False)
        for step in old_steps:
            step.order += 1
            step.save()
        step_type = int(type_value) - 1
        new_step = _template.TemplateStep.objects.create(
            template=template,
            step_type=type_value,
            order=new_order,
            name=enum_template.STEP_TYPE_CHOICES[step_type][1])
        if type_value == enum_template.STEP_TYPE_SCRIPT:
            sub_new_step = _template.TemplateStepScript.objects.create(
                step=new_step)
        elif type_value == enum_template.STEP_TYPE_PULL_FILE:
            sub_new_step = _template.TemplateStepPullFile.objects.create(
                step=new_step)
        elif type_value == enum_template.STEP_TYPE_PUSH_FILE:
            sub_new_step = _template.TemplateStepPushFile.objects.create(
                step=new_step)
        elif type_value == enum_template.STEP_TYPE_TEXT:
            sub_new_step = _template.TemplateStepText.objects.create(
                step=new_step)
        status = 200
        data.update({"step_id": new_step.id, "sub_step_id": sub_new_step.id})

        change_template_sync_status(template)
    except Exception, e:
        data['msg'] = msg if msg else u"步骤添加失败"
        error = traceback.format_exc()
        logger.error(error)
        print error
Beispiel #9
0
def template_edit(request,template_id):
    """
        show detail of the template after clicked the button.
    """
    user = request.user
    status = 500
    data = {}
    try:
        method = request.method
        template_file = "md_manage/edit_md.html"
        check_id = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        template = _template.get_template_by_params(id=template_id)
        ajax_url = "/md_manage/template_step/list/{0}/".format(template.pk)
        accounts = _account.get_accounts_by_params(is_delete=False)
        accountForm = AccountForm()
        target_ips = json.loads(template.target) if template.target else []
        hide_ip_dict = build_hidden_ip_dict(target_ips)
        hide_ip_json = json.dumps(hide_ip_dict)

        if method == 'POST':
            templateForm = EditTemplateForm(request.POST,instance=template,user=request.user)
            check_id=request.POST.get("check_id",check_id)
            work_type=request.POST.get("work_type","")
            data.update({"template_id":template.id,"check_id":check_id})
            if templateForm.is_valid():
                user = request.user
                template = templateForm.save(commit=False)
                template.update_user = user
                template.work_type = work_type
                template.save()
                status = 200
            else:
                html = render_to_string(template_file, locals())
                data.update({"html":html})
            data.update({"template_name":template.name})
            return HttpResponse(json.dumps({
                "status":status,
                "result":data,
            }, cls=LazyEncoder))
        else:
            account_id = template.account.id if template.account else 0
            template_name = template.name
            templateForm = EditTemplateForm(instance=template,user=request.user)
            work_type = template.work_type
            html = render_to_string(template_file, locals())
            status=200
            data.update({"html":html,"template_name":template_name,"work_type":work_type})
    except:
        error = traceback.format_exc()
        logger.error(error)
        print error
        data['msg'] = u"服务器错误"
    return HttpResponse(json.dumps({
        "status":status,
        "result":data
    }, cls=LazyEncoder))
Beispiel #10
0
def schedule_add_v2(request,template_id):
    status = 500
    data = {}
    msg = ""
    try:
        user = request.user
        
        template = _template.get_template_by_params(id=template_id)
        if not template:
            msg = u"作业不存在"
        else:
            job = job_sync_v2(template)
            if request.method == 'GET':
                check_id = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
                template_file = "job_manage/timing_modal.html"
                html = render_to_string(template_file, locals())
                data['html'] = html
                data['msg'] = u'ok'
                data['check_id'] = check_id
                status = 200
            elif request.method == 'POST':
                expression = request.POST.get("expression","")
                note = request.POST.get("note","")
                parts = expression.split(" ")
                task = None
                sch_job = None
                try:
                    if len(parts) == 7:
                        task = ScheduleJobs.objects.create(creator=user,executor=user,job=job,expression=expression,note=note,status=SCHEDULE_STATUS_STARTED)
                        sch_job = scheduler.add_job(handle_job_schedule,trigger="cron",
                                                    second=parts[0],
                                                    minute=parts[1],
                                                    hour=parts[2],
                                                    day_of_week=parts[3],
                                                    day=parts[4],
                                                    month=parts[5],
                                                    year=parts[6],
                                                    args=[job_id,user.username,task.id])
                    else:
                        msg = u"表达式格式错误"
                        raise Exception(msg)
                    task.schedule_id = sch_job.id
                    task.save()
                    status = 200
                    msg = "add ok."
                except Exception,e:
                    msg = e.message
                    error = traceback.format_exc()
                    logger.error(error)
                if not sch_job and task: task.delete()
            else:
Beispiel #11
0
def template_view(request,template_id):
    """
        show template view.
    """
    user = request.user
    sdicts = {'result': 0}
    template = _template.get_template_by_params(id=template_id)
    
    job_list = _job.get_jobs_by_params(template=template)
    
    template_file = "md_manage/md_view.html"

    ajax_url = u'/job/job_list/'+template_id+'/'
    html = render_to_string(template_file, locals())
    sdicts['html'] = html
    sdicts['template_name'] = template.name
    return HttpResponse(json.dumps(sdicts, cls=LazyEncoder))
Beispiel #12
0
def template_step_add(request):
    """
        add template step to template.
    """
    req = request.POST
    user = request.user
    status = 500
    data = {}
    msg = ""
    template_id = req.get("template_id","")
    type_value = req.get("type_value","")
    index = req.get("index","")
    try:
        template = _template.get_template_by_params(id=template_id)
        if not template:
            msg = u"模板不存在"
            raise
        # if template.create_user!=user:
        #     msg = u"您没有操作该模板的权限"
        #     raise
        ########## add new step #########
        new_order = int(index) +1
        type_value = int(type_value)
        old_steps = _template.get_templateSteps_by_params(template=template,order__gte=new_order,is_delete=False)
        for step in old_steps:
            step.order += 1
            step.save()
        step_type = int(type_value)-1
        new_step = _template.TemplateStep.objects.create(template=template,step_type=type_value,order=new_order,name=enum_template.STEP_TYPE_CHOICES[step_type][1])
        if type_value == enum_template.STEP_TYPE_SCRIPT:
            sub_new_step = _template.TemplateStepScript.objects.create(step=new_step)
        elif type_value == enum_template.STEP_TYPE_PULL_FILE:
            sub_new_step = _template.TemplateStepPullFile.objects.create(step=new_step)
        elif type_value == enum_template.STEP_TYPE_PUSH_FILE:
            sub_new_step = _template.TemplateStepPushFile.objects.create(step=new_step)
        elif type_value == enum_template.STEP_TYPE_TEXT:
            sub_new_step = _template.TemplateStepText.objects.create(step=new_step)
        status=200
        data.update({"step_id":new_step.id,"sub_step_id":sub_new_step.id})
        
        change_template_sync_status(template)
    except Exception,e:
        data['msg'] = msg if msg else u"步骤添加失败"
        error = traceback.format_exc()
        logger.error(error)
        print error
Beispiel #13
0
def template_view(request, template_id):
    """
        show template view.
    """
    user = request.user
    sdicts = {'result': 0}
    template = _template.get_template_by_params(id=template_id)

    job_list = _job.get_jobs_by_params(template=template)

    template_file = "md_manage/md_view.html"

    ajax_url = u'/job/job_list/' + template_id + '/'
    html = render_to_string(template_file, locals())
    sdicts['html'] = html
    sdicts['template_name'] = template.name
    return HttpResponse(json.dumps(sdicts, cls=LazyEncoder))
Beispiel #14
0
def full_settings_save(request, template_id):
    """
        save full settings of template.

    """
    user = request.user
    status = 500
    data = {}
    try:
        mode = request.POST.get("mode", None)
        account_id = request.POST.get("template_account", None)
        if not mode or not account_id:
            msg = u"有未填写的参数项"
        else:
            account = _account.get_account_by_params(id=int(account_id))
            template = _template.get_template_by_params(id=template_id)

            ips_json = request.POST.get('full_settings_ips_hide',"")
            ip_set = get_input_ips(ips_json)
            template.target = json.dumps(list(ip_set))

            template.mode = mode
            template.account = account
            template.save()
            msg = "save success"
            status = 200
    except Exception as e:
        msg = "ops, error "
        print traceback.format_exc()
    data.update({
        "msg": msg
    })
    return HttpResponse(json.dumps({
        "status": status,
        "result": data
    }, cls=LazyEncoder))
Beispiel #15
0
                    jobStepScript = _job.get_jobStepScript_by_params(
                        id=jobStepScript_id)
                    jobStepScript.version = version
                    jobStepScript.save()
            code = 200
        except Exception, e:
            code = 500

        sdicts['status'] = code
        return HttpResponse(json.dumps(sdicts))
    else:
        try:
            version_id = request.GET.get('version_id', 0)
            template_id = request.GET.get('template_id', 0)
            version = _script.get_version_by_params(id=version_id)
            template = _template.get_template_by_params(id=template_id)
            jobStepScripts = _job.get_jobStepScripts_by_params(
                step__job__template=template, step__job__is_delete=False)
            code = 200
        except Exception, e:
            code = 500

        template_file = "script_manage/version_sync_modal.html"
        html = render_to_string(template_file, locals())
        sdicts['status'] = code
        sdicts['html'] = html
        return HttpResponse(json.dumps(sdicts))


@login_required
@csrf_exempt
Beispiel #16
0
                if jobStepScript_id:
                    jobStepScript = _job.get_jobStepScript_by_params(id=jobStepScript_id)
                    jobStepScript.version = version
                    jobStepScript.save()
            code = 200
        except Exception,e:
            code = 500
    
        sdicts['status'] = code
        return HttpResponse(json.dumps(sdicts))
    else:
        try:
            version_id = request.GET.get('version_id',0)
            template_id = request.GET.get('template_id',0)
            version = _script.get_version_by_params(id=version_id)
            template = _template.get_template_by_params(id=template_id)
            jobStepScripts = _job.get_jobStepScripts_by_params(step__job__template=template,step__job__is_delete=False)
            code = 200
        except Exception,e:
            code = 500
        
        template_file = "script_manage/version_sync_modal.html"
        html = render_to_string(template_file, locals())
        sdicts['status'] = code
        sdicts['html'] = html
        return HttpResponse(json.dumps(sdicts))

@login_required
@csrf_exempt
def template_list_v2(request,version_id):
    '''
Beispiel #17
0
def template_edit(request, template_id):
    """
        show detail of the template after clicked the button.
    """
    user = request.user
    status = 500
    data = {}
    try:
        method = request.method
        template_file = "md_manage/edit_md.html"
        check_id = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        template = _template.get_template_by_params(id=template_id)
        ajax_url = "/md_manage/template_step/list/{0}/".format(template.pk)
        accounts = _account.get_accounts_by_params(is_delete=False)
        accountForm = AccountForm()
        target_ips = json.loads(template.target) if template.target else []
        hide_ip_dict = build_hidden_ip_dict(target_ips)
        hide_ip_json = json.dumps(hide_ip_dict)

        if method == 'POST':
            templateForm = EditTemplateForm(request.POST,
                                            instance=template,
                                            user=request.user)
            check_id = request.POST.get("check_id", check_id)
            work_type = request.POST.get("work_type", "")
            data.update({"template_id": template.id, "check_id": check_id})
            if templateForm.is_valid():
                user = request.user
                template = templateForm.save(commit=False)
                template.update_user = user
                template.work_type = work_type
                template.save()
                status = 200
            else:
                html = render_to_string(template_file, locals())
                data.update({"html": html})
            data.update({"template_name": template.name})
            return HttpResponse(
                json.dumps({
                    "status": status,
                    "result": data,
                },
                           cls=LazyEncoder))
        else:
            account_id = template.account.id if template.account else 0
            template_name = template.name
            templateForm = EditTemplateForm(instance=template,
                                            user=request.user)
            work_type = template.work_type
            html = render_to_string(template_file, locals())
            status = 200
            data.update({
                "html": html,
                "template_name": template_name,
                "work_type": work_type
            })
    except:
        error = traceback.format_exc()
        logger.error(error)
        print error
        data['msg'] = u"服务器错误"
    return HttpResponse(
        json.dumps({
            "status": status,
            "result": data
        }, cls=LazyEncoder))
Beispiel #18
0
def update_auth(request):
    '''
        更新用户授权.
    '''
    result = {}
    status = 500
    data = {}
    msg = ''
    try:
        user = request.user
        req = request.POST
        req_type = req.get("auth_type", "")
        obj_ids = req.getlist('obj_list[]', [])
        select_ids = req.getlist("user_list[]", [])
        logger.debug(
            "start update auth, auth_type:{0}, obj_ids:{1}, user_names:{2}".
            format(req_type, ','.join(obj_ids), ','.join(select_ids)))
        if req_type not in PERM_PTYPE_MAP.keys():
            msg = u'授权类型错误'
            raise Exception, msg
        if not obj_ids or not isinstance(obj_ids, list):
            msg = u'未勾选或所选对象类型错误'
            raise Exception, msg
        user_names = []
        logger.debug("request:{0}".format(req))
        auth_type = PERM_PTYPE_MAP.get(req_type)
        msg = u'不允许二次授权,请重新选择'
        for obj_id in obj_ids:
            if auth_type == PERM_PTYPE_TEMPLATE and _template.get_template_by_params(
                    id=obj_id).create_user != user:
                raise Exception, msg
            if auth_type == PERM_PTYPE_JOB and _job.get_job_by_params(
                    id=obj_id).create_user != user:
                raise Exception, msg
            if auth_type == PERM_PTYPE_SCRIPT and _script.get_script_by_params(
                    id=obj_id).create_user != user:
                raise Exception, msg
        msg = ""
        for select_id in select_ids:
            if str(select_id).startswith('emp_'):
                user_names.append(select_id.split('_')[1])
        for obj_id in obj_ids:
            logger.debug(
                "==> start update perm for object id:{0}".format(obj_id))
            old_perms = Perm.objects.filter(ptype=PERM_PTYPE_MAP[req_type],
                                            object_id=obj_id,
                                            is_delete=False).values_list('id')
            old_perm_ids = [i[0] for i in old_perms]
            new_perm_ids = set()

            scripts = None
            if auth_type == PERM_PTYPE_TEMPLATE:
                #获取所有该模板的脚本
                steps = TemplateStep.objects.filter(
                    template__id=obj_id,
                    step_type=enum_template.STEP_TYPE_SCRIPT,
                    is_delete=False)
                script_steps = TemplateStepScript.objects.filter(
                    step__in=steps)
                scripts = [step.version.script for step in script_steps]

            for user_name in user_names:
                to_user = User.objects.get(username=user_name)
                p, is_create = Perm.objects.get_or_create(
                    ptype=PERM_PTYPE_MAP[req_type],
                    object_id=obj_id,
                    is_delete=False,
                    create_user=user,
                    to_user=to_user)
                new_perm_ids.add(p.id)
                if is_create:
                    logger.debug(
                        'perm of user:{0} to {1}_id:{2} is created'.format(
                            user_name, req_type, obj_id))
                else:
                    logger.debug(
                        'perm of user:{0} to {1}_id:{2} already exists.'.
                        format(user_name, req_type, obj_id))

                ### 自动脚本授权
                if auth_type == PERM_PTYPE_TEMPLATE:
                    for script in scripts:
                        p, is_create = Perm.objects.get_or_create(
                            ptype=PERM_PTYPE_SCRIPT,
                            object_id=script.id,
                            is_delete=False,
                            create_user=user,
                            to_user=to_user)
                        logger.debug(
                            "create auth for script:{0} to user:{1},is_create:{2}"
                            .format(script.id, to_user.username, is_create))

            discard_perms = set(old_perm_ids).difference(new_perm_ids)
            if discard_perms:
                names = [
                    i[0] for i in Perm.objects.filter(
                        id__in=discard_perms).values_list('to_user__username')
                ]
                logger.debug("drop perms of {0} to {1}_id:{2}".format(
                    ','.join(names), req_type, obj_id))
                Perm.objects.filter(id__in=discard_perms).update(
                    is_delete=True)

                ### 脚本授权回收.
                if auth_type == PERM_PTYPE_TEMPLATE:
                    script_ids = [script.id for script in scripts] or []
                    for script_id in script_ids:
                        rel_script_steps = TemplateStepScript.objects.filter(
                            version__script__id=script_id,
                            step__is_delete=False)
                        rel_template_ids = [
                            script_step.step.template.id
                            for script_step in rel_script_steps
                        ]
                        for name in names:
                            # 存在其他关联模板授权的不进行回收该脚本.
                            if Perm.objects.filter(
                                    ptype=PERM_PTYPE_TEMPLATE,
                                    object_id__in=rel_template_ids,
                                    is_delete=False,
                                    to_user__username=name).count() > 0:
                                logger.debug(
                                    "other template using this template, no revoke,user:{0},script_id:{1}"
                                    .format(name, script_id))
                            else:
                                logger.debug(
                                    "revoke auth, script_id:{0}, user:{1}".
                                    format(script_id, name))
                                Perm.objects.filter(
                                    ptype=PERM_PTYPE_SCRIPT,
                                    object_id=script_id,
                                    is_delete=False,
                                    create_user=user,
                                    to_user__username=name).update(
                                        is_delete=True)

            logger.debug("==> update perm successfully!\n")
        msg = u'授权更新成功'
        status = 200
        logger.debug("## All perm update successfully!\n")
    except Exception, e:
        msg = u'授权更新失败' if not msg else msg
        error = traceback.format_exc()
        print error
        logger.error(error)