Esempio n. 1
0
    def run(self, kwargs):
        pid_path = self.getPidPath('monitor_core.pid')
        if self.checkPidExist(pid_path):
            app.logger.info("[monitor] core is running")
            return False

        pid = str(os.getpid())
        if not self.setPidFile(pid_path, pid):
            err_msg = self.getErrMsg()
            app.logger.info("Cann't get a lock file,err msg : " + err_msg)
            return False
        '''
        整体延迟10秒,为什么 因为会出现一种情况,就是。从数据库回去数据的时候 job没有运行,
        但是等到判断的时候,发现job运行了,所以我们要做一个延迟处理,让Job进行都运行起来
        '''
        time.sleep(10)

        params = self.getEnvFile()
        server_id = params['id']
        host = params['name']
        list = JobList.query.filter_by(
            server_id=server_id,
            status=CommonConstant.default_status_true,
            is_del=CommonConstant.default_status_false).all()
        if not list:
            app.logger.info("%s没有Job需要监控" % (host))
            return True

        self.current_time = time.time() - 300
        for item in list:
            self.handleItem(ModelHelper.model2Dict(item), host)
            self.residentProcess(ModelHelper.model2Dict(item))

        app.logger.info("it's over~~")
        return True
Esempio n. 2
0
def job_info():
    req = request.values
    id = int(req['id']) if ('id' in req and req['id']) else 0
    info = JobList.query.filter_by(id=id).first()
    if not info:
        return redirect(GlobalUrlService.buildHomeUrl("/job/index/index"))

    info = ModelHelper.model2Dict(info)

    server_info = JobServer.query.filter_by(id=info['server_id']).first()
    cate_info = JobCategory.query.filter_by(id=info['cate_id']).first()
    server_env_map = CommonConstant.server_env_map
    run_status_map = CommonConstant.run_status_map

    info['next_run_time'] = DateHelper.getDateOnTimestamps(
        info['next_run_time'], '%Y-%m-%d %H:%M')
    info['env_name'] = server_env_map.get(info['env_id'])
    info['run_status_desc'] = run_status_map.get(info['run_status'])
    info['job_status_desc'] = job_status_map.get(info['status'])
    info['server_name'] = server_info.name
    info['cate_name'] = cate_info.name if cate_info else ''
    info['run_interval_desc'] = DateHelper.formatBeautyTime(
        info['run_interval'] * 60)

    user_map = ModelHelper.getDictFilterField(
        User,
        select_field=User.id,
        id_list=[info['owner_uid'], info['relate_uid']])

    ##获取最近5天运行记录
    log_list = JobRunLog.query.filter_by(job_id=id).order_by(
        JobRunLog.id.desc())[0:5]
    log_data = []
    if log_list:
        for item in log_list:
            tmp_data = ModelHelper.model2Dict(item)
            tmp_data['status_desc'] = CommonConstant.job_log_status_map[
                tmp_data['status']]
            tmp_data['duration'] = ""
            if DateHelper.getCurrentTime(date=tmp_data['end_time']
                                         ) == CommonConstant.DEFAULT_DATETIME:
                tmp_data['end_time'] = "未知"
                tmp_data['duration'] = time.time() - time.mktime(
                    tmp_data['start_time'].timetuple())
            else:
                tmp_data['duration'] = tmp_data['end_time'].timestamp(
                ) - tmp_data['start_time'].timestamp()
            tmp_data['duration'] = DateHelper.formatBeautyTime(
                tmp_data['duration'])
            log_data.append(tmp_data)

    return UtilHelper.renderView(
        "home/job/index/info.html", {
            "info": info,
            "log_list": log_data,
            "user_map": user_map,
            "job_level_map": CommonConstant.job_level_map,
        })
Esempio n. 3
0
def tools_alert():
    req = request.values
    page = int(req.get("p", 1))
    date_from = req.get("date_from", DateHelper.getCurrentTime(fmt="%Y-%m-%d"))
    date_to = req.get("date_to", DateHelper.getCurrentTime(fmt="%Y-%m-%d"))
    status = int(req.get("status", CommonConstant.default_status_neg_99))

    query = JobAlertList.query.filter(
        JobAlertList.created_time.between(date_from, date_to + " 23:59:59"))
    if status > CommonConstant.default_status_neg_99:
        query = query.filter_by(status=status)

    page_params = {
        "total": query.count(),
        "page_size": CommonConstant.PAGE_SIZE,
        "page": page,
        "display": CommonConstant.PAGE_DISPLAY,
    }

    pages = UtilHelper.iPagination(page_params)
    offset = (page - 1) * CommonConstant.PAGE_SIZE
    limit = CommonConstant.PAGE_SIZE * page
    list = query.order_by(JobAlertList.id.desc())[offset:limit]
    data = []
    if list:
        job_ids = ModelHelper.getFieldList(list, "job_id")
        job_map = ModelHelper.getDictFilterField(JobList,
                                                 select_field=JobList.id,
                                                 id_list=job_ids.sort())
        for item in list:
            tmp_data = ModelHelper.model2Dict(item)
            tmp_job_info = ModelHelper.model2Dict(
                job_map.get(tmp_data['job_id']))
            tmp_data['status_desc'] = CommonConstant.common_status_map4[
                tmp_data['status']]
            tmp_data['job_name'] = tmp_job_info['name']

            data.append(tmp_data)

    sc = {'date_from': date_from, 'date_to': date_to, 'status': status}

    return UtilHelper.renderView(
        "home/job/tools/alert.html", {
            "list": data,
            "pages": pages,
            "sc": sc,
            "status_map": CommonConstant.common_status_map4,
            "current": "alert"
        })
Esempio n. 4
0
def home_index():
    date = DateHelper.getCurrentTime(fmt="%Y-%m-%d")
    job_count = JobList.query.filter_by(is_del=CommonConstant.default_status_false).count()
    server_count = JobServer.query.filter_by(status=CommonConstant.default_status_true).count()
    alert_count = JobAlertList.query.filter(JobAlertList.created_time.between(date, date + " 23:59:59")).count()

    cate_map = ModelHelper.getDictFilterField( JobCategory )
    cat_job_map = {}
    cat_job_list = JobList.query.with_entities(JobList.cate_id ,func.count( JobList.id) )\
        .filter_by(is_del=CommonConstant.default_status_false)\
        .group_by(JobList.cate_id).all()
    if cat_job_list:
        for _item in cat_job_list:
            cat_job_map[ _item[0] ] = _item[1]

    type_job_map = {}
    job_type_map = CommonConstant.job_type_map
    type_job_list = JobList.query.with_entities(JobList.job_type, func.count(JobList.id)) \
        .filter_by(is_del=CommonConstant.default_status_false) \
        .group_by(JobList.job_type).all()
    if type_job_list:
        for _item in type_job_list:
            type_job_map[ _item[0] ] = _item[1]

    return UtilHelper.renderView("home/index/index.html", {
        "job_count": job_count,
        "server_count": server_count,
        "alert_count": alert_count,
        'cate_map' : cate_map,
        'cat_job_map' : cat_job_map,
        'job_type_map' : job_type_map,
        'type_job_map' : type_job_map,
    })
Esempio n. 5
0
    def run(self, kwargs):
        pid_path = self.getPidPath( 'monitor_system.pid' )
        if self.checkPidExist(pid_path):
            app.logger.info("[monitor] system is running")
            return False

        pid = str( os.getpid() )
        if not self.setPidFile( pid_path,pid):
            err_msg = self.getErrMsg()
            app.logger.info("Cann't get a lock file,err msg : " + err_msg)
            return False

        params = self.getEnvFile()
        server_id = params['id']
        host = params['name']
        ## 判断是否有僵尸进程

        cmd = "ps -A -o stat,ppid,pid,cmd | grep -v grep  |grep -e '^[Zz]'"
        status,output = subprocess.getstatusoutput( cmd )
        if len( output ) < 1:
            return True

        output_arr = output.split( '\n' )
        if len( output_arr ) > 3:#多余3个僵尸进程
            staff_list = StaffService.getRootStaffList()
            staff_ids = ModelHelper.getFieldList( staff_list,"id")
            for tmp_staff_id in staff_ids:
                news_params = {
                    "uid": tmp_staff_id,
                    "title": "僵尸进程:" + host,
                    "content": "<br/>".join( output_arr )
                }
                NewsService.addNews(news_params)
        return True
Esempio n. 6
0
def server_index():
    req = request.values
    kw = req.get("kw", "").strip()
    page = int(req.get("p", 1))

    query = JobServer.query
    if kw:
        query = query.filter(JobServer.name.ilike('%{}%'.format(kw)))

    page_params = {
        "total": query.count(),
        "page_size": CommonConstant.PAGE_SIZE,
        "page": page,
        "display": CommonConstant.PAGE_DISPLAY
    }

    pages = UtilHelper.iPagination(page_params)
    offset = (page - 1) * CommonConstant.PAGE_SIZE
    limit = CommonConstant.PAGE_SIZE * page
    list = query.order_by(JobServer.id.desc())[offset:limit]

    data = []
    server_env_map = CommonConstant.server_env_map
    if list:
        for item in list:
            tmp_data = ModelHelper.model2Dict(item)
            tmp_env_ids = (item.env).strip(
                CommonConstant.special_strike).split(
                    CommonConstant.special_strike)
            tmp_env_list = []
            for _env_id in tmp_env_ids:
                if int(_env_id) not in server_env_map.keys():
                    continue
                tmp_env_list.append(server_env_map.get(int(_env_id)))

            tmp_data['env'] = ",".join(tmp_env_list)
            data.append(tmp_data)

    sc = {'kw': kw}

    set_flag = RBACService.checkPageRelatePrivilege("set")
    ops_flag = RBACService.checkPageRelatePrivilege("ops")

    return UtilHelper.renderView(
        "home/job/server/index.html", {
            "list": data,
            "pages": pages,
            "server_env_map": CommonConstant.server_env_map,
            "sc": sc,
            "set_flag": set_flag,
            "ops_flag": ops_flag
        })
Esempio n. 7
0
def staff_index():
    req = request.values
    kw = req.get("kw", "").strip()
    page = int(req.get("p", 1))

    query = User.query
    if kw:
        query = query.filter( or_( User.name.ilike( '%{}%'.format(kw) ) ,User.email.ilike( '%{}%'.format(kw) ) ))

    page_params = {
        "total": query.count(),
        "page_size": CommonConstant.PAGE_SIZE,
        "page": page,
        "display": CommonConstant.PAGE_DISPLAY,
    }

    pages = UtilHelper.iPagination(page_params)
    offset = (page - 1) * CommonConstant.PAGE_SIZE
    limit = CommonConstant.PAGE_SIZE * page
    list = query.order_by( User.id.desc() )[offset:limit]

    dept_map = ModelHelper.getDictFilterField( Role )
    sc = {
        'kw': kw
    }

    set_flag = RBACService.checkPageRelatePrivilege("set")
    ops_flag = RBACService.checkPageRelatePrivilege("ops")

    return UtilHelper.renderView( "home/rbac/staff/index.html",   {
        "list": list,
        "pages": pages,
        "dept_map" : dept_map,
        "sc": sc,
        "set_flag": set_flag,
        "ops_flag": ops_flag,
    })
Esempio n. 8
0
    def run(self, params):
        list = JobAlertList.query.filter_by(status=CommonConstant.default_status_neg_2)\
            .order_by( JobAlertList.id.asc() ).limit(10).all()

        if not list:
            app.logger.info("没有报警异常数据需要处理")
            return self.exitOK()

        job_ids = ModelHelper.getFieldList(list, "job_id")
        job_map = ModelHelper.getDictFilterField(JobList, select_field=JobList.id, id_list= job_ids )

        staff_ids = []
        for _key,_item in job_map.items():
            staff_ids.append( _item.owner_uid )
            staff_ids.append( _item.relate_uid )

        staff_map = ModelHelper.getDictFilterField(User, select_field= User.id, id_list= staff_ids)
        done_ids = []
        alert_content = [
            "Job异常报警"
        ]

        cate_map = ModelHelper.getDictFilterField(JobCategory)
        for item in list:

            tmp_data = ModelHelper.model2Dict( item )
            tmp_job_info = ModelHelper.model2Dict(job_map.get(tmp_data['job_id']))

            #负责人和相关人用户信息
            tmp_job_owner_info =  ModelHelper.model2Dict( staff_map.get( tmp_job_info['owner_uid'] ) )
            tmp_job_relate_info =  ModelHelper.model2Dict( staff_map.get( tmp_job_info['relate_uid'] ) )

            #分类
            tmp_cate_info = ModelHelper.model2Dict( cate_map.get( tmp_job_info['cate_id'] ) )

            done_ids.append(tmp_data['id'])
            tmp_msg = "Job Id: {0},名称:[{1}]{2},负责人:{3},相关人:{4},重要级别:{5},类型:{6},报警内容:{7}"\
                .format( tmp_job_info['id'],tmp_cate_info['name'],tmp_job_info['name']
                         ,tmp_job_owner_info['name'],tmp_job_relate_info['name']
                         ,CommonConstant.job_level_map[ tmp_job_info['job_level'] ]
                         ,CommonConstant.job_type_map[ tmp_job_info['job_type'] ]
                         , tmp_data['content']
                         )

            if 'Job平台标识没有运行'  in tmp_msg or 'Job平台标识正在运行'  in tmp_msg:
                continue

            self.handleItem(tmp_data, tmp_job_info)
            alert_content.append(tmp_msg)


        if done_ids:
            '''
            synchronize_session用于query在进行delete or update操作时,对session的同步策略。
            False - 不对session进行同步,直接进行delete or update操作
            '''
            JobAlertList.query.filter( JobAlertList.id.in_( done_ids ) )\
                .update( dict( status =  CommonConstant.default_status_true  ) ,synchronize_session=False )
            db.session.commit()


        if len( alert_content ) > 1:
            alert_content = "\r\n".join( alert_content )
            self.dingdingAlert( alert_content )
            self.wechatworkAlert( alert_content )

        return self.exitOK()
Esempio n. 9
0
def grant_assign():
    if UtilHelper.isGet():
        req = request.values
        role_id = int(req.get("role_id", 0))
        role_pid = int(req.get("role_pid", 0))
        '''
        取出来所有的一级部门
        '''
        p_role_list = Role.query.filter_by(pid=CommonConstant.default_status_false)\
            .order_by( Role.id.asc() ).all()

        if not role_pid and p_role_list:  #如果没有父部门,那就选择一个
            role_pid = p_role_list[0].id

        sub_role_list = Role.query.filter_by( pid = role_pid)\
            .order_by( Role.id.asc() ).all()

        if not role_id and sub_role_list:
            role_id = sub_role_list[0].id

        user_list = User.query.filter_by(
            status=CommonConstant.default_status_true, role_id=role_id).all()

        action_list = Action.query.filter_by( status = CommonConstant.default_status_true )\
            .order_by( Action.level1_weight.desc(),Action.level2_weight.desc(),Action.weight.desc() ).all()

        action_data = {}
        if action_list:
            for item in action_list:
                tmp_level1_key = item.level1_name
                tmp_level2_key = item.level2_name
                if tmp_level1_key not in action_data:
                    action_data[tmp_level1_key] = {
                        "name": tmp_level1_key,
                        "counter": 0,
                        "sub": {}
                    }

                if tmp_level2_key not in action_data[tmp_level1_key]['sub']:
                    action_data[tmp_level1_key]['sub'][tmp_level2_key] = {
                        "name": tmp_level2_key,
                        "counter": 0,
                        "act_list": []
                    }

                action_data[tmp_level1_key]['counter'] += 1
                action_data[tmp_level1_key]['sub'][tmp_level2_key][
                    'counter'] += 1

                tmp_data = {
                    "id": item.id,
                    "name": item.name,
                    "is_important": item.is_important
                }
                action_data[tmp_level1_key]['sub'][tmp_level2_key][
                    'act_list'].append(tmp_data)

        owned_act = RoleAction.query.filter_by(
            role_id=role_id, status=CommonConstant.default_status_true).all()
        owned_act_ids = ModelHelper.getFieldList(owned_act, 'action_id')

        sc = {
            "role_id": role_id,
            "role_pid": role_pid,
        }

        return UtilHelper.renderView(
            "home/rbac/grant/assign.html", {
                "list": action_data,
                "p_role_list": p_role_list,
                "sub_role_list": sub_role_list,
                "user_list": user_list,
                "owned_act_ids": owned_act_ids,
                "sc": sc
            })

    req = request.values
    role_id = int(req.get("role_id", 0))
    action_ids = request.form.getlist("action_ids[]")
    action_ids = list(map(int, action_ids))
    if not role_id or role_id < 1:
        return UtilHelper.renderErrJSON("请选择部门在分配权限~~")

    info = Role.query.filter_by(id=role_id).first()
    if not info:
        return UtilHelper.renderErrJSON("请选择部门在分配权限 -2~~")
    ###分配权限逻辑还是挺复杂的
    ## 已有的权限
    owned_act = RoleAction.query.filter_by(role_id=role_id).all()
    owned_act_ids = ModelHelper.getFieldList(owned_act, 'action_id')
    '''
    找出删除的权限(生产环境数据库没有删除权限)
    假如已有的权限集合是A,界面传递过得权限集合是B
    权限集合A当中的某个权限不在权限集合B当中,就应该删除
    计算差集
    '''
    delete_act_ids = list(set(owned_act_ids) - set(action_ids))
    if delete_act_ids:
        RoleAction.query.filter( RoleAction.role_id == role_id,RoleAction.action_id.in_( delete_act_ids ) )\
            .update({ "status":CommonConstant.default_status_false },synchronize_session = False)
        db.session.commit()
    '''
    找出添加的权限
    假如已有的权限集合是A,界面传递过得权限集合是B
    权限集合B当中的某个权限不在权限集合A当中,就应该添加
    计算差集
    '''
    add_act_ids = list(set(action_ids) - set(owned_act_ids))
    if add_act_ids:
        for _action_id in add_act_ids:
            _model_role_action = RoleAction()
            _model_role_action.role_id = role_id
            _model_role_action.action_id = _action_id
            db.session.add(_model_role_action)
        db.session.commit()
    '''
    找出需要更新的权限(生产环境数据库没有删除权限)
    假如已有的权限集合是A,界面传递过得权限集合是B
    权限集合B当中的某个权限也在在权限集合A当中,就应该更新
    计算补集
    '''
    update_act_ids = list(set(owned_act_ids).intersection(set(action_ids)))
    if update_act_ids:
        RoleAction.query.filter(RoleAction.role_id == role_id, RoleAction.action_id.in_(update_act_ids)) \
            .update({"status": CommonConstant.default_status_true}, synchronize_session=False)
        db.session.commit()

    return UtilHelper.renderSucJSON({}, "权限分配成功~~")
Esempio n. 10
0
def tools_log():
    status_map = CommonConstant.job_log_status_map

    req = request.values
    page = int(req.get("p", 1))
    date_from = req.get("date_from", DateHelper.getCurrentTime(fmt="%Y-%m-%d"))
    date_to = req.get("date_to", DateHelper.getCurrentTime(fmt="%Y-%m-%d"))
    status = int(req.get("status", CommonConstant.default_status_neg_99))
    job_id = int(req.get("job_id", CommonConstant.default_status_false))

    query = JobRunLog.query.filter(
        JobRunLog.created_time.between(date_from, date_to + " 23:59:59"))

    if job_id:
        query = query.filter_by(job_id=job_id)

    if status > CommonConstant.default_status_neg_99:
        query = query.filter_by(status=status)

    page_params = {
        "total": query.count(),
        "page_size": CommonConstant.PAGE_SIZE,
        "page": page,
        "display": CommonConstant.PAGE_DISPLAY,
    }

    pages = UtilHelper.iPagination(page_params)
    offset = (page - 1) * CommonConstant.PAGE_SIZE
    limit = CommonConstant.PAGE_SIZE * page
    list = query.order_by(JobRunLog.id.desc())[offset:limit]
    data = []
    if list:
        job_ids = ModelHelper.getFieldList(list, "job_id")
        job_map = ModelHelper.getDictFilterField(JobList,
                                                 select_field=JobList.id,
                                                 id_list=job_ids.sort())
        for item in list:
            tmp_data = ModelHelper.model2Dict(item)
            tmp_job_info = ModelHelper.model2Dict(
                job_map.get(tmp_data['job_id']))
            tmp_data['status_desc'] = status_map[tmp_data['status']]
            tmp_data['job_name'] = tmp_job_info['name']
            tmp_data['duration'] = ""
            if DateHelper.getCurrentTime(date=tmp_data['end_time']
                                         ) == CommonConstant.DEFAULT_DATETIME:
                tmp_data['end_time'] = "未知"
                tmp_data['duration'] = time.time() - time.mktime(
                    tmp_data['start_time'].timetuple())
            else:
                tmp_data['duration'] = (tmp_data['end_time'].timestamp() -
                                        tmp_data['start_time'].timestamp())
            tmp_data['duration'] = DateHelper.formatBeautyTime(
                tmp_data['duration'])

            data.append(tmp_data)

    sc = {
        'date_from': date_from,
        'date_to': date_to,
        'status': status,
        'job_id': job_id
    }

    return UtilHelper.renderView(
        "home/job/tools/log.html", {
            "list": data,
            "pages": pages,
            "sc": sc,
            "status_map": status_map,
            "current": "log"
        })
Esempio n. 11
0
def job_index():
    req = request.values
    cate_id = int(req.get("cate_id", CommonConstant.default_status_false))
    owner_uid = int(req.get("owner_uid", CurrentUserService.getUid()))
    env_id = int(req.get("env_id", CommonConstant.default_status_false))
    server_id = int(req.get("server_id", CommonConstant.default_status_false))
    status = int(req.get("status", CommonConstant.default_status_neg_99))
    display_status = int(
        req.get("display_status", CommonConstant.default_status_neg_99))
    job_type = int(req.get("job_type", CommonConstant.default_status_neg_99))
    job_level = int(req.get("job_level", CommonConstant.default_status_neg_99))

    kw = req.get("kw", "").strip()
    page = int(req.get("p", 1))

    query = JobList.query

    if RBACService.checkDataPrivilege("all"):
        pass
    else:
        query = query.filter_by(owner_uid=CurrentUserService.getUid())

    if cate_id:
        query = query.filter_by(cate_id=cate_id)

    if env_id:
        query = query.filter_by(env_id=env_id)

    if owner_uid:
        query = query.filter_by(owner_uid=owner_uid)

    if server_id:
        query = query.filter_by(server_id=server_id)

    if status > CommonConstant.default_status_neg_99:
        query = query.filter_by(status=status)

    if display_status > CommonConstant.default_status_neg_99:
        query = query.filter_by(is_del=display_status)

    if job_type > CommonConstant.default_status_neg_99:
        query = query.filter_by(job_type=job_type)

    if job_level > CommonConstant.default_status_neg_99:
        query = query.filter_by(job_level=job_level)

    if kw:
        if kw.isdigit():
            query = query.filter_by(id=int(kw))
        else:
            query = query.filter(
                or_(JobList.name.ilike('%{}%'.format(kw)),
                    JobList.command.ilike('%{}%'.format(kw))))

    page_params = {
        "total": query.count(),
        "page_size": CommonConstant.PAGE_SIZE,
        "page": page,
        "display": CommonConstant.PAGE_DISPLAY
    }

    pages = UtilHelper.iPagination(page_params)
    offset = (page - 1) * CommonConstant.PAGE_SIZE
    limit = CommonConstant.PAGE_SIZE * page
    list = query.order_by(JobList.id.desc())[offset:limit]
    data = []

    server_map = ModelHelper.getDictFilterField(JobServer)
    cate_map = ModelHelper.getDictFilterField(JobCategory)
    staff_map = ModelHelper.getDictFilterField(User)
    server_env_map = CommonConstant.server_env_map
    run_status_map = CommonConstant.run_status_map
    job_type_map = CommonConstant.job_type_map
    job_level_map = CommonConstant.job_level_map
    if list:
        for item in list:
            tmp_data = ModelHelper.model2Dict(item)
            tmp_server_info = ModelHelper.model2Dict(
                server_map.get(tmp_data['server_id']))
            tmp_cate_info = ModelHelper.model2Dict(
                cate_map.get(tmp_data['cate_id']))
            tmp_owner_staff_info = ModelHelper.model2Dict(
                staff_map.get(tmp_data['owner_uid']))
            tmp_relate_staff_info = ModelHelper.model2Dict(
                staff_map.get(tmp_data['relate_uid']))
            tmp_data['next_run_time'] = DateHelper.getDateOnTimestamps(
                tmp_data['next_run_time'], '%Y-%m-%d %H:%M')
            tmp_data['env_name'] = server_env_map.get(tmp_data['env_id'])
            tmp_data['run_status_desc'] = run_status_map.get(
                tmp_data['run_status'])
            tmp_data['job_status_desc'] = job_status_map.get(
                tmp_data['status'])
            tmp_data['server_name'] = tmp_server_info.get("name")
            tmp_data['cate_name'] = tmp_cate_info.get("name", '')
            tmp_data['owner_name'] = tmp_owner_staff_info.get("name", '')
            tmp_data['relate_name'] = tmp_relate_staff_info.get("name", '')
            tmp_data['run_interval_desc'] = DateHelper.formatBeautyTime(
                tmp_data['run_interval'] * 60)
            data.append(tmp_data)
    sc = {
        'kw': kw,
        'cate_id': cate_id,
        'owner_uid': owner_uid,
        'env_id': env_id,
        'server_id': server_id,
        'status': status,
        'display_status': display_status,
        'job_type': job_type,
        'job_level': job_level,
    }

    set_flag = RBACService.checkPageRelatePrivilege("set")
    ops_flag = RBACService.checkPageRelatePrivilege("ops")
    return UtilHelper.renderView(
        "home/job/index/index.html", {
            "list": data,
            "pages": pages,
            "job_status_map": job_status_map,
            "server_env_map": server_env_map,
            "server_map": server_map,
            "staff_map": staff_map,
            "cate_map": cate_map,
            "display_status_map": display_status_map,
            "job_type_map": job_type_map,
            "job_level_map": job_level_map,
            "sc": sc,
            "set_flag": set_flag,
            "ops_flag": ops_flag,
        })
Esempio n. 12
0
def job_set():
    if UtilHelper.isGet():
        req = request.values
        id = int(req['id']) if ('id' in req and req['id']) else 0
        act = req.get("act", "").strip()
        info = {'owner_uid': CurrentUserService.getUid()}
        if id > 0:
            info = JobList.query.filter_by(id=id).first()
            info = ModelHelper.model2Dict(info)
            info['next_run_time'] = DateHelper.getDateOnTimestamps(
                info['next_run_time'], '%Y-%m-%d %H:%M')

        if act == "copy":
            info['id'] = 0
            info['status'] = 0
            info['name'] = "【复制】" + info['name']

        server_list = JobServer.query.order_by(JobServer.id.desc()).all()
        user_list = User.query.order_by(User.id.desc()).all()
        cate_list = JobCategory.query.order_by(JobCategory.id.desc()).all()

        return UtilHelper.renderView(
            "home/job/index/set.html", {
                "info": info,
                "server_list": server_list,
                "user_list": user_list,
                "cate_list": cate_list,
                "server_env_map": CommonConstant.server_env_map,
                "job_type_map": CommonConstant.job_type_map,
                "job_status_map": job_status_map,
                "job_level_map": CommonConstant.job_level_map,
            })

    req = request.values
    id = int(req['id']) if ('id' in req and req['id']) else 0
    cate_id = int(req.get("cate_id", "0").strip())
    name = req.get("name", "").strip()
    env_id = int(req.get("env_id", "0").strip())
    server_id = int(req.get("server_id", "0").strip())
    owner_uid = int(req.get("owner_uid", "0").strip())
    relate_uid = int(req.get("relate_uid", "0").strip())
    command = req.get("command", "").strip()
    command_kill = req.get("command_kill", "").strip()
    job_type = int(req.get("job_type", "0").strip())
    job_level = int(req.get("job_level", "1").strip())
    status = int(req.get("status", "0").strip())
    next_run_time = req.get("next_run_time", "").strip()
    run_interval = int(req.get("run_interval", "0").strip())
    threshold_down = int(req.get("threshold_down", "0").strip())
    threshold_up = int(req.get("threshold_up", "0").strip())
    note = req.get("note", "").strip()

    if cate_id < 1:
        return UtilHelper.renderErrJSON("请选择所属分类~~")

    if not ValidateHelper.validLength(name, 1, 15):
        return UtilHelper.renderErrJSON("请输入符合规范的名称~~")

    if env_id < 1:
        return UtilHelper.renderErrJSON("请选择运行环境~~")

    if server_id < 1:
        return UtilHelper.renderErrJSON("请选择运行服务器~~")

    if owner_uid < 1:
        return UtilHelper.renderErrJSON("请选择Job负责人~~")

    if relate_uid < 1:
        return UtilHelper.renderErrJSON("请选择Job相关人~~")

    if not ValidateHelper.validLength(command, 5):
        return UtilHelper.renderErrJSON("请输入Job命令~~")

    if job_type < 1:
        return UtilHelper.renderErrJSON("请选择Job类型~~")

    if not ValidateHelper.validDate(next_run_time,
                                    r'^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$'):
        return UtilHelper.renderErrJSON("请选择调度时间~~")

    if job_type != CommonConstant.default_status_pos_2:
        if run_interval < 1:
            return UtilHelper.renderErrJSON("请输入运行间隔~~")

        if threshold_down < 0:
            return UtilHelper.renderErrJSON("请输入预估最短运行时长~~")

        if threshold_up < 1:
            return UtilHelper.renderErrJSON("请输入预估最长运行时长~~")
    else:
        run_interval = threshold_down = threshold_up = 0

    info = JobList.query.filter_by(id=id).first()

    if info:
        model_job = info
        ##正在运行的Job不能编辑运行时间
        if info.run_status == CommonConstant.default_status_pos_2:
            if info.command != command:
                return UtilHelper.renderErrJSON("正在运行的Job不能修改运行命令~~")

            if info.job_type != job_type:
                return UtilHelper.renderErrJSON("正在运行的Job不能修改类型~~")

            if info.status != status:
                return UtilHelper.renderErrJSON("正在运行的Job不能修改调度状态~~")

            if info.next_run_time != DateHelper.getTimestamps(next_run_time +
                                                              ":00"):
                return UtilHelper.renderErrJSON("正在运行的Job不能修改调度时间~~")

    else:
        model_job = JobList()

    ##只有需要调度的才需要判断时间
    if model_job.run_status != CommonConstant.default_status_pos_2 and status \
            and DateHelper.getTimestamps(next_run_time + ":00") < time.time():
        return UtilHelper.renderErrJSON("调度时间不能小于当前时间~~")

    model_job.name = name
    model_job.env_id = env_id
    model_job.server_id = server_id
    model_job.owner_uid = owner_uid
    model_job.relate_uid = relate_uid
    model_job.job_type = job_type
    model_job.job_level = job_level
    model_job.cate_id = cate_id
    model_job.command = command
    model_job.command_kill = command_kill
    model_job.next_run_time = DateHelper.getTimestamps(next_run_time + ":00")
    model_job.run_interval = run_interval
    model_job.threshold_up = threshold_up
    model_job.threshold_down = threshold_down
    model_job.note = note
    model_job.status = status
    if status and (not info or not info.run_status):
        model_job.run_status = CommonConstant.default_status_true

    db.session.add(model_job)
    db.session.commit()

    return UtilHelper.renderSucJSON({"id": model_job.id})