Example #1
0
    async def get(self, *args, **kwargs):
        publish_name = self.get_argument('publish_name',
                                         default=None,
                                         strip=True)
        username = self.get_current_user()
        publish_app_list = []
        host_list = []

        if publish_name:
            ### 选中发布
            all_host_info = {}
            with DBContext('r') as session:
                app_info = session.query(TaskPublishConfig).filter(
                    TaskPublishConfig.publish_name == publish_name).all()

            for msg in app_info:
                data_dict = model_to_dict(msg)
                need_data = dict(repository=data_dict.get('repository'),
                                 build_host=data_dict.get('build_host'),
                                 temp_name=data_dict.get('temp_name'))

                tag_name = data_dict.get('tag_name')
                if tag_name:
                    server_info = session.query(Server).outerjoin(
                        ServerTag, Server.id == ServerTag.server_id).outerjoin(
                            Tag, Tag.id == ServerTag.tag_id).filter(
                                Tag.tag_name == tag_name).all()

                    for s in server_info:
                        server_dict = model_to_dict(s)
                        all_host_info[str(
                            server_dict['hostname'])] = server_dict['ip']
                        host_list.append(server_dict['hostname'])

                    need_data['all_host_info'] = all_host_info
                    need_data['host_list'] = host_list

                else:
                    if data_dict.get('publish_type') == 'server':
                        return self.write(dict(code=-1, msg='请注意,当前应用没有配置标签'))

                return self.write(dict(code=0, msg='获取详细成功', data=need_data))

        else:
            with DBContext('r') as session:
                publish_info = session.query(
                    TaskPublishConfig.publish_name,
                    GitRepo.user_info).outerjoin(
                        GitRepo, TaskPublishConfig.repository ==
                        GitRepo.ssh_url_to_repo).order_by(
                            TaskPublishConfig.id).all()
            for msg in publish_info:
                if self.is_superuser:
                    publish_app_list.append(msg[0])
                elif msg[1] and username in msg[1].split(','):
                    for u in msg[1].split(','):
                        if username == u.split("@")[0]:
                            publish_app_list.append(msg[0])
            return self.write(dict(code=0, msg='获取成功', data=publish_app_list))
Example #2
0
    def get(self, *args, **kwargs):
        value = self.get_argument('value', default=None, strip=True)
        db_list = []
        with DBContext('r') as session:
            db_info = session.query(DB).outerjoin(
                DBTag,
                DB.id == DBTag.db_id).outerjoin(Tag,
                                                Tag.id == DBTag.tag_id).filter(
                                                    Tag.tag_name == str(value),
                                                    DB.db_type == 'mysql',
                                                    DB.db_mark == '写')
            proxy_host = session.query(
                Tag.proxy_host).filter(Tag.tag_name == value).first()[0]

            if not proxy_host:
                return self.write(dict(code=-1, msg='请给选择标签添加代理主机'))

            for msg in db_info:
                data_dict = model_to_dict(msg)
                db_list.append(data_dict['db_code'])

            if len(db_list) == 0:
                return self.write(dict(code=-2, msg='当前标签没有MySQL写库'))

        self.write(dict(code=0, msg='获取成功', data=db_list))
Example #3
0
    def get(self, *args, **kwargs):
        key = self.get_argument('key', default=None, strip=True)
        tag_list = json.loads(key)['tag_list']
        if len(tag_list) == 0:
            return self.write(dict(code=-1, msg='请至少选中一个标签'))

        server_list = []
        proxy_list = []
        with DBContext('r') as session:
            server_info = session.query(Server).outerjoin(
                ServerTag, Server.id == ServerTag.server_id).outerjoin(
                    Tag, Tag.id == ServerTag.tag_id).filter(
                        Tag.tag_name.in_(tag_list))

            proxy_host = session.query(Tag.proxy_host).filter(
                Tag.tag_name.in_(tag_list)).all()

        for p in proxy_host:
            proxy_list.append(p[0])
        if not proxy_host:
            return self.write(dict(code=-1, msg='请给选择标签添加代理主机'))

        for msg in server_info:
            data_dict = model_to_dict(msg)
            data_dict.pop('create_time')
            server_list.append(data_dict['hostname'])

        self.write(
            dict(code=0,
                 msg='获取成功',
                 data=dict(server_list=server_list,
                           proxy_list=list(set(proxy_list)))))
Example #4
0
    def post(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))
        tag = data.get('tag', None)
        sql_data = data.get('sql_data', None)
        db_name = data.get('db_name', None)
        db_code = data.get('db_code', None)
        the_way = data.get('the_way', None)
        db_str = ''

        if not tag or not sql_data or not db_name or not db_code:
            return self.write(dict(code=-1, msg='必填项不能为空'))

        with DBContext('r') as session:
            db_info = session.query(DB).filter(DB.db_code == db_code).all()
            proxy_host = session.query(
                Tag.proxy_host).filter(Tag.tag_name == tag).first()[0]

            temp_info = session.query(TempList).filter(
                TempList.temp_id == 9001).first()

        if not temp_info:
            return self.write(dict(code=-2, msg='关联的任务模板有误,快去检查!'))

        for msg in db_info:
            data_dict = model_to_dict(msg)
            data_dict.pop('create_time')
            data_dict.pop('db_detail')
            db_str = str(base64.b64encode(
                json.dumps(data_dict).encode('utf-8')),
                         encoding="utf8")

        sql_data = str(base64.b64encode(sql_data.encode('utf-8')),
                       encoding="utf8")

        args_dict = dict(MYSQLINFO=db_str,
                         DB_NAME=db_name,
                         SQL_DATA=sql_data,
                         THE_WAY=the_way)
        hosts_dict = {1: proxy_host}
        data_info = dict(
            exec_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            temp_id=9001,
            task_name='MySQL',
            task_type='数据库优化',
            submitter=self.get_current_nickname(),
            associated_user="",
            args=str(args_dict),
            hosts=str(hosts_dict),
            schedule='ready',
            details='')
        return_data = acc_create_task(**data_info)

        data = dict(list_id=return_data['list_id'],
                    task_group=1,
                    task_level=1,
                    exec_ip=proxy_host)
        return_data['data'] = data
        return self.write(return_data)
Example #5
0
    def get(self, *args, **kwargs):
        key = self.get_argument('key', default=None, strip=True)
        # value = self.get_argument('value', default=None, strip=True)
        page_size = self.get_argument('page', default=1, strip=True)
        limit = self.get_argument('limit', default="15", strip=True)
        limit_start = (int(page_size) - 1) * int(limit)
        nickname = self.get_current_nickname()

        common_jobs_list = []
        with DBContext('r') as session:
            # TODO 做搜索
            if key:
                # TODO 超级管理员做搜索
                if self.is_superuser:
                    count = session.query(CommonJobsModel).filter(
                        or_(CommonJobsModel.task_name.like('%{}%'.format(key)))).count()

                    common_jobs_info = session.query(CommonJobsModel).filter(
                        or_(CommonJobsModel.task_name.like('%{}%'.format(key))))
                else:
                    # TODO 普通用户做搜素

                    count = session.query(CommonJobsModel).filter(or_(CommonJobsModel.creator == nickname,
                                                                      CommonJobsModel.authorized_user.like(
                                                                          '%{}%'.format(nickname)))).filter(
                        CommonJobsModel.task_name.like('%{}%'.format(key))).count()

                    common_jobs_info = session.query(CommonJobsModel).filter(or_(CommonJobsModel.creator == nickname,
                                                                                 CommonJobsModel.authorized_user.like(
                                                                                     '%{}%'.format(nickname)))).filter(
                        CommonJobsModel.task_name.like('%{}%'.format(key))).all()

            # TODO 正常分页展示
            else:
                # TODO 超级管理员展示所有
                if self.is_superuser:
                    count = session.query(CommonJobsModel).count()
                    common_jobs_info = session.query(CommonJobsModel).offset(limit_start).limit(int(limit))

                else:
                    # TODO 普通用户前端只展示有权限的
                    count = session.query(CommonJobsModel).filter(or_(CommonJobsModel.creator == nickname,
                                                                      CommonJobsModel.authorized_user.like(
                                                                          '%{}%'.format(nickname)))).count()

                    common_jobs_info = session.query(CommonJobsModel).filter(or_(CommonJobsModel.creator == nickname,
                                                                                 CommonJobsModel.authorized_user.like(
                                                                                     '%{}%'.format(nickname)))).offset(
                        limit_start).limit(int(limit))

            for msg in common_jobs_info:
                data_dict = model_to_dict(msg)
                data_dict['create_time'] = str(data_dict['create_time'])
                data_dict['update_time'] = str(data_dict['update_time'])
                common_jobs_list.append(data_dict)

            self.write(dict(code=0, msg='获取成功', count=count, data=common_jobs_list))
    def get(self, *args, **kwargs):
        key = self.get_argument('key', default=None, strip=True)
        value = self.get_argument('value', default=None, strip=True)
        page_size = self.get_argument('page', default=1, strip=True)
        limit = self.get_argument('limit', default="888", strip=True)
        limit_start = (int(page_size) - 1) * int(limit)
        tag_list = []

        with DBContext('r') as session:
            if key == 'tag_name' and value:
                count = session.query(Tag).filter(
                    Tag.tag_name.like('%{}%'.format(value))).count()
                all_tags = session.query(Tag).filter(
                    Tag.tag_name.like('%{}%'.format(value))).order_by(
                        Tag.id).offset(limit_start).limit(int(limit))
            elif limit == '888':
                count = session.query(Tag).count()
                all_tags = session.query(Tag).order_by(Tag.id).all()
            elif key and key != 'tag_name' and value:
                count = session.query(Tag).filter_by(**{key: value}).count()
                all_tags = session.query(Tag).order_by(
                    Tag.id).filter_by(**{
                        key: value
                    }).order_by(Tag.id).offset(limit_start).limit(int(limit))
            else:
                count = session.query(Tag).count()
                all_tags = session.query(Tag).order_by(
                    Tag.id).offset(limit_start).limit(int(limit))

            for msg in all_tags:
                db_list = []
                server_list = []
                data_dict = model_to_dict(msg)
                data_dict['create_time'] = str(data_dict['create_time'])
                if data_dict['users']:
                    data_dict['users'] = data_dict.get('users', '').split(',')
                else:
                    data_dict['users'] = []
                server_tags = session.query(ServerTag.id, Server.id).outerjoin(
                    Server, Server.id == ServerTag.server_id).filter(
                        ServerTag.tag_id == msg.id).all()
                for i in server_tags:
                    server_list.append(i[1])
                data_dict['servers'] = server_list
                data_dict['server_len'] = len(server_tags)

                db_tags = session.query(DBTag.id, DB.id, DB.db_code).outerjoin(
                    DB,
                    DB.id == DBTag.db_id).filter(DBTag.tag_id == msg.id).all()
                for i in db_tags:
                    db_list.append(i[1])
                data_dict['db_len'] = len(db_tags)
                data_dict['dbs'] = db_list
                tag_list.append(data_dict)

        self.write(dict(code=0, msg='获取成功', count=count, data=tag_list))
Example #7
0
    def get(self, *args, **kwargs):
        key = self.get_argument('key', default=None, strip=True)
        proxy_list = []
        with DBContext('r') as session:
            if key:
                proxy_info = session.query(ProxyInfo).filter(ProxyInfo.proxy_host == key).all()
            else:
                proxy_info = session.query(ProxyInfo).all()

        for msg in proxy_info:
            data_dict = model_to_dict(msg)
            proxy_list.append(data_dict)
        return self.write(dict(code=0, msg='获取成功', data=proxy_list))
Example #8
0
    def get(self, *args, **kwargs):
        value = self.get_argument('value', default=None, strip=True)
        server_list = []
        with DBContext('r') as session:
            server_info = session.query(Server).outerjoin(ServerTag, Server.id == ServerTag.server_id).outerjoin(
                Tag, Tag.id == ServerTag.tag_id).filter(Tag.tag_name == str(value))

            for msg in server_info:
                data_dict = model_to_dict(msg)
                data_dict.pop('create_time')
                server_list.append(data_dict)

        self.write(dict(code=0, msg='获取成功', data=server_list))
Example #9
0
    def get(self, *args, **kwargs):
        with DBContext('r') as session:
            project_info = session.query(ProjectModel).all()

        # project_list = [model_to_dict(msg) for msg in project_info]
        project_list = []
        for msg in project_info:
            data_dict = model_to_dict(msg)
            if data_dict.get('user_list'):
                data_dict['user_list'] = data_dict.get('user_list').split(',')

            project_list.append(data_dict)

        self.write(dict(code=0, msg='获取成功', data=project_list))
Example #10
0
    def get(self, *args, **kwargs):
        nickname = self.get_current_nickname()
        tag_list = []

        with DBContext('r') as session:
            the_tags = session.query(Tag).order_by(Tag.id).all()

        for msg in the_tags:
            data_dict = model_to_dict(msg)
            data_dict.pop('create_time')
            if self.is_superuser:
                tag_list.append(data_dict)
            elif data_dict['users'] and nickname in data_dict['users'].split(','):
                tag_list.append(data_dict)
        return self.write(dict(code=0, msg='获取成功', data=tag_list))
Example #11
0
    def get(self, *args, **kwargs):
        _tree = [{
            "expand":
            True,
            "title":
            'root',
            "children": [{
                "title": "server",
                "expand": False,
                "children": []
            }, {
                "title": 'DB',
                "expand": False,
                "children": []
            }]
        }]

        with DBContext('r') as session:
            db_tags = session.query(Tag).order_by(Tag.id).all()
            for msg in db_tags:
                db_dict = {}
                server_dict = {}
                data_dict = model_to_dict(msg)
                server_tags = session.query(ServerTag.id).outerjoin(
                    Server, Server.id == ServerTag.server_id).filter(
                        ServerTag.tag_id == msg.id).all()
                server_dict['the_len'] = len(server_tags)
                server_dict['title'] = data_dict['tag_name'] + ' ({})'.format(
                    len(server_tags))
                server_dict['tag_name'] = data_dict['tag_name']
                server_dict['node'] = 'server'
                _tree[0]["children"][0]['children'].append(server_dict)

                db_tags = session.query(DBTag.id).outerjoin(
                    DB,
                    DB.id == DBTag.db_id).filter(DBTag.tag_id == msg.id).all()

                db_dict['the_len'] = len(db_tags)
                db_dict['tag_name'] = data_dict['tag_name']
                db_dict['node'] = 'DB'
                db_dict['title'] = data_dict['tag_name'] + ' ({})'.format(
                    len(db_tags))
                _tree[0]["children"][1]['children'].append(db_dict)

        self.write(dict(code=0, msg='获取成功', data=_tree))
Example #12
0
    def post(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))
        tag = data.get('tag', None)
        sql_data = data.get('sql_data', None)
        approver = data.get('approver', None)
        if not tag or not sql_data or not approver:
            return self.write(dict(code=-1, msg='必填项不能为空'))

        db_str = ""
        with DBContext('r') as session:
            temp_info = session.query(TempList).filter(TempList.temp_id == 330).first()
            if not temp_info:
                return self.write(dict(code=-2, msg='关联的任务模板有误,快去检查!'))

            db_info = session.query(DB).outerjoin(DBTag, DB.id == DBTag.db_id).outerjoin(Tag,
                                                                                         Tag.id == DBTag.tag_id).filter(
                Tag.tag_name == str(tag), DB.db_type == 'mysql', DB.db_mark == '写')
            proxy_host = session.query(Tag.proxy_host).filter(Tag.tag_name == tag).first()[0]
            inception_info = session.query(ProxyInfo.inception).filter(ProxyInfo.proxy_host == proxy_host).first()[0]

        for msg in db_info:
            data_dict = model_to_dict(msg)
            data_dict.pop('create_time')
            data_dict.pop('db_detail')
            base64.b64encode(str(data_dict).encode('utf-8'))
            if db_str:
                db_str = db_str + ",,," + json.dumps(data_dict)
            else:
                db_str = json.dumps(data_dict)
        db_str = str(base64.b64encode(db_str.encode('utf-8')), encoding="utf8")
        inception_info = str(base64.b64encode(str(inception_info).encode('utf-8')), encoding="utf8")
        sql_data = str(base64.b64encode(sql_data.encode('utf-8')), encoding="utf8")

        args_dict = dict(MYSQLINFO=db_str, SQL_DATA=sql_data, INCEPTION=inception_info)
        hosts_dict = {1: proxy_host}
        data_info = dict(exec_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), temp_id=330,
                         task_name='MySQL', task_type='数据库审核', submitter=self.get_current_nickname(), executor=approver,
                         associated_user="", args=str(args_dict), hosts=str(hosts_dict), schedule='new', details='')

        return_data = acc_create_task(**data_info)
        return self.write(return_data)
Example #13
0
    def get(self, *args, **kwargs):
        key = self.get_argument('key', default=None, strip=True)
        value = self.get_argument('value', default=None, strip=True)
        repository_list = []

        with DBContext('r') as session:
            if key and value:
                repository_info = session.query(DockerRegistry).filter_by(
                    **{
                        key: value
                    }).all()
            else:
                repository_info = session.query(DockerRegistry).order_by(
                    DockerRegistry.id).all()

        for msg in repository_info:
            data_dict = model_to_dict(msg)
            data_dict['create_time'] = str(data_dict['create_time'])
            repository_list.append(data_dict)

        return self.write(dict(code=0, msg='获取成功', data=repository_list))
Example #14
0
    def get(self, *args, **kwargs):
        key = self.get_argument('key', default=None, strip=True)
        value = self.get_argument('value', default=None, strip=True)
        publish_app_list = []

        with DBContext('r') as session:
            if key and value:
                publish_info = session.query(TaskPublishConfig).filter_by(
                    **{
                        key: value
                    }).all()
            else:
                publish_info = session.query(TaskPublishConfig).order_by(
                    TaskPublishConfig.id).all()

        for msg in publish_info:
            data_dict = model_to_dict(msg)
            data_dict['create_time'] = str(data_dict['create_time'])
            publish_app_list.append(data_dict)

        return self.write(dict(code=0, msg='获取成功', data=publish_app_list))
Example #15
0
    def get(self, *args, **kwargs):
        project_code = self.get_argument('project_code', default=None, strip=True)

        with DBContext('r') as session:
            config_info = session.query(BusinessModel).filter(BusinessModel.project_code == project_code).all()

        config_list = [model_to_dict(msg) for msg in config_info]

        _tree = [{"expand": True, "title": project_code, "children": [], "data_type": 'project'}]

        if config_list:
            tmp_tree = {"environ": {}, "service": {}}

            for t in config_list:
                service, environ = t['service'], t["environment"]

                # 因为是第一层所以没有parent
                tmp_tree["environ"][environ] = {
                    "expand": False, "title": environ, "parent": "root", "children": [], "data_type": 'env'
                }

                # 父节点是对应的environ
                tmp_tree["service"][environ + "|" + service] = {
                    "expand": False, "title": service, "parent": environ,
                    "children": [], "data_type": 'service'
                }
            # service的数据插入到environ的children中
            for tmpService in tmp_tree["service"].values():
                tmp_tree["environ"][tmpService["parent"]]["children"].append(tmpService)

            for tmpEnviron in tmp_tree["environ"].values():
                if tmpEnviron not in ["all", "all_env"]:
                    _tree[0]["children"].append(tmpEnviron)
            return self.write(dict(code=0, msg='获取项目Tree成功', data=_tree))
        else:
            return self.write(dict(code=0, msg='获取项目Tree失败', data=_tree))
Example #16
0
    async def get(self, *args, **kwargs):
        publish_name = self.get_argument('publish_name',
                                         default=None,
                                         strip=True)
        nickname = self.get_current_nickname()
        publish_app_list = []

        if publish_name:
            all_host_info = {}
            with DBContext('r') as session:
                app_info = session.query(TaskPublishConfig).filter(
                    TaskPublishConfig.publish_name == publish_name).all()

            for msg in app_info:
                data_dict = model_to_dict(msg)
                need_data = dict(repository=data_dict.get('repository'),
                                 build_host=data_dict.get('build_host'),
                                 temp_name=data_dict.get('temp_name'))

                if data_dict.get('publish_hosts'):
                    hosts_list = data_dict.get('publish_hosts').split('\n')
                    for host in hosts_list:
                        all_host_info[host.split(' ')[0]] = host.split(
                            ' ')[1:4]

                need_data['all_host_info'] = all_host_info
                publish_hosts_api = data_dict.get('publish_hosts_api')
                if publish_hosts_api:
                    http_client = httpclient.AsyncHTTPClient()
                    response = await http_client.fetch(
                        publish_hosts_api,
                        raise_error=False,
                        headers=self.request.headers)
                    if response.code == 200:
                        response_data = json.loads(
                            response.body.decode('utf-8'))
                        if response_data:
                            for res in response_data['data']['server_list']:
                                if res.get('ip'):
                                    all_host_info[res.get('ip')] = [
                                        res.get('port', 22),
                                        res.get('admin_user', 'root')
                                    ]
                        need_data['all_host_info'] = all_host_info
                    else:
                        return self.write(
                            dict(code=-3,
                                 msg='主机组API获取失败 error code:{}'.format(
                                     response.code),
                                 data=need_data))
                return self.write(dict(code=0, msg='获取详细成功', data=need_data))

        else:
            with DBContext('r') as session:
                publish_info = session.query(
                    TaskPublishConfig.publish_name,
                    TaskCodeRepository.user_info).outerjoin(
                        TaskCodeRepository, TaskPublishConfig.repository ==
                        TaskCodeRepository.repository).order_by(
                            TaskPublishConfig.id).all()
            for msg in publish_info:
                if self.is_superuser:
                    publish_app_list.append(msg[0])
                elif msg[1] and nickname in msg[1].split(','):
                    publish_app_list.append(msg[0])
            return self.write(dict(code=0, msg='获取成功', data=publish_app_list))
Example #17
0
    def post(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))
        custom = data.get('custom')

        publish_name = data.get('publish_name', None)
        publish_tag = data.get('publish_tag', None)
        host_list = data.get('host_list', None)
        start_time = data.get('start_time', None)
        start_time = datetime.datetime.strptime(
            start_time, "%Y-%m-%dT%H:%M:%S.%fZ") + datetime.timedelta(hours=8)

        args_dict = {}

        if custom:
            if custom.get('custom_key') and custom.get('custom_value'):
                args_dict[custom.get('custom_key')] = custom.get(
                    'custom_value')

        if not publish_name or not publish_tag or not start_time:
            return self.write(dict(code=-1, msg='必填项不能为空'))

        with DBContext('r') as session:
            conf_info = session.query(TaskPublishConfig).filter(
                TaskPublishConfig.publish_name == publish_name).first()
            temp_id = session.query(TempList.temp_id).filter(
                TempList.temp_name == conf_info.temp_name).first()

            if not temp_id:
                return self.write(dict(code=-1, msg='关联的任务模板有误,快去检查!'))
            else:
                temp_id = temp_id[0]

            first_group = session.query(TempDetails.group).filter(
                TempDetails.temp_id == temp_id).order_by(
                    TempDetails.group).first()

            if not first_group:
                return self.write(dict(code=-1, msg='关联的任务模板任务组有误,快去检查!'))

            else:
                first_group = first_group[0]

            if host_list:
                server_info = session.query(Server).filter(
                    Server.hostname.in_(host_list)).all()
                server_dict = {}
                for msg in server_info:
                    data_dict = model_to_dict(msg)
                    if data_dict['hostname']:
                        server_dict[data_dict['hostname']] = data_dict['ip']
                args_dict['SERVER_DICT'] = json.dumps(server_dict)

        conf_dict = model_to_dict(conf_info)
        conf_dict.pop('id')
        conf_dict.pop('create_time')
        args_dict['PUBLISH_NAME'] = publish_name
        args_dict['PUBLISH_TAG'] = publish_tag

        for i, j in conf_dict.items():
            if j and not i.startswith('Secret') and not i.startswith('secret'):
                args_dict[i.upper()] = j

        hosts_dict = {first_group: conf_info.build_host}
        data_info = dict(
            exec_time=start_time,
            temp_id=temp_id,
            task_name=publish_name,
            task_type=conf_info.temp_name,
            submitter=self.get_current_nickname(),
            associated_user="",
            args=str(args_dict),
            hosts=str(hosts_dict),
            schedule='new',
            details='',
        )

        return_data = acc_create_task(**data_info)
        return self.write(return_data)
Example #18
0
    def get(self, *args, **kwargs):
        key = self.get_argument('key', default=None, strip=True)
        value = self.get_argument('value', default=None, strip=True)
        page_size = self.get_argument('page', default=1, strip=True)
        limit = self.get_argument('limit', default='888', strip=True)
        limit_start = (int(page_size) - 1) * int(limit)
        db_list = []
        with DBContext('r') as session:
            ### 通过TAG搜索
            if key == 'tag_name' and value:
                count = session.query(DB).outerjoin(DBTag, DB.id == DBTag.db_id).outerjoin(Tag, Tag.id ==
                                                                                           DBTag.tag_id).filter(
                    Tag.tag_name == value).count()
                db_info = session.query(DB).outerjoin(DBTag, DB.id == DBTag.db_id).outerjoin(Tag, Tag.id ==
                                                                                             DBTag.tag_id).filter(
                    Tag.tag_name == value).order_by(DB.id).offset(limit_start).limit(int(limit))
                for msg in db_info:
                    tag_list = []
                    data_dict = model_to_dict(msg)
                    data_dict['create_time'] = str(data_dict['create_time'])
                    db_tags = session.query(Tag.tag_name).outerjoin(DBTag, Tag.id == DBTag.tag_id).filter(
                        DBTag.db_id == data_dict['id']).all()
                    for t in db_tags:
                        tag_list.append(t[0])
                    data_dict['tag_list'] = tag_list
                    db_list.append(data_dict)
                return self.write(dict(code=0, msg='获取成功', count=count, data=db_list))

            ### 监听搜索
            if key and key != 'tag_name' and not value:
                count = session.query(DB).filter(or_(DB.db_code.like('%{}%'.format(key)),
                                                     DB.db_host.like('%{}%'.format(key)),
                                                     DB.proxy_host.like('%{}%'.format(key)),
                                                     DB.db_type.like('%{}%'.format(key)),
                                                     DB.db_mark.like('%{}%'.format(key)),
                                                     DB.state.like('%{}%'.format(key)),
                                                     DB.db_env.like('%{}%'.format(key)))).count()

                db_info = session.query(DB).filter(or_(DB.db_code.like('%{}%'.format(key)),
                                                       DB.db_host.like('%{}%'.format(key)),
                                                       DB.proxy_host.like('%{}%'.format(key)),
                                                       DB.db_type.like('%{}%'.format(key)),
                                                       DB.db_mark.like('%{}%'.format(key)),
                                                       DB.state.like('%{}%'.format(key)),
                                                       DB.db_env.like('%{}%'.format(key)))).order_by(DB.id).offset(
                    limit_start).limit(int(limit))

                for msg in db_info:
                    tag_list = []
                    data_dict = model_to_dict(msg)
                    data_dict['create_time'] = str(data_dict['create_time'])
                    db_tags = session.query(Tag.tag_name).outerjoin(DBTag, Tag.id == DBTag.tag_id).filter(
                        DBTag.db_id == data_dict['id']).all()
                    for t in db_tags:
                        tag_list.append(t[0])
                    data_dict['tag_list'] = tag_list
                    db_list.append(data_dict)

                return self.write(dict(code=0, msg='获取成功', count=count, data=db_list))

            ### 888查看所有的数据库
            if limit == '888':
                count = session.query(DB).count()
                db_info = session.query(DB).order_by(DB.id).all()
            else:
                if key and value:
                    count = session.query(DB).filter_by(**{key: value}).count()
                    db_info = session.query(DB).filter_by(**{key: value}).order_by(DB.id).offset(limit_start).limit(
                        int(limit))
                else:
                    count = session.query(DB).count()
                    db_info = session.query(DB).order_by(DB.id).offset(limit_start).limit(int(limit))

            for msg in db_info:
                tag_list = []
                data_dict = model_to_dict(msg)
                db_tags = session.query(Tag.tag_name).outerjoin(DBTag, Tag.id == DBTag.tag_id).filter(
                    DBTag.db_id == data_dict['id']).all()
                for t in db_tags:
                    tag_list.append(t[0])
                data_dict['create_time'] = str(data_dict['create_time'])
                data_dict['tag_list'] = tag_list
                db_list.append(data_dict)

        self.write(dict(code=0, msg='获取成功', count=count, data=db_list))
Example #19
0
    def get(self, *args, **kwargs):
        key = self.get_argument('key', default=None, strip=True)
        value = self.get_argument('value', default=None, strip=True)
        page_size = self.get_argument('page', default=1, strip=True)
        limit = self.get_argument('limit', default="888", strip=True)
        limit_start = (int(page_size) - 1) * int(limit)
        server_list = []
        with DBContext('r') as session:
            ### 通过TAG搜索
            if key == 'tag_name' and value:
                count = session.query(Server).outerjoin(ServerTag, Server.id == ServerTag.server_id
                                                        ).outerjoin(Tag, Tag.id == ServerTag.tag_id).filter(
                    Tag.tag_name == value).count()
                server_info = session.query(Server).outerjoin(ServerTag, Server.id == ServerTag.server_id
                                                              ).outerjoin(Tag, Tag.id == ServerTag.tag_id).filter(
                    Tag.tag_name == value).order_by(Server.id).offset(limit_start).limit(int(limit))

                for msg in server_info:
                    tag_list = []
                    data_dict = model_to_dict(msg)
                    data_dict['create_time'] = str(data_dict['create_time'])
                    db_tags = session.query(Tag.tag_name).outerjoin(ServerTag, Tag.id == ServerTag.tag_id).filter(
                        ServerTag.server_id == data_dict['id']).all()
                    for t in db_tags:
                        tag_list.append(t[0])
                    data_dict['tag_list'] = tag_list
                    server_list.append(data_dict)
                return self.write(dict(code=0, msg='获取成功', count=count, data=server_list))

            ### 监听搜索
            if key and key != 'tag_name' and not value:
                count = session.query(Server).filter(or_(Server.hostname.like('%{}%'.format(key)),
                                                         Server.ip.like('%{}%'.format(key)),
                                                         Server.state.like('%{}%'.format(key)))).count()
                server_info = session.query(Server).filter(or_(Server.hostname.like('%{}%'.format(key)),
                                                               Server.ip.like('%{}%'.format(key)),
                                                               Server.state.like('%{}%'.format(key)))).order_by(
                    Server.id).offset(limit_start).limit(int(limit))

                for msg in server_info:
                    tag_list = []
                    data_dict = model_to_dict(msg)
                    data_dict['create_time'] = str(data_dict['create_time'])
                    db_tags = session.query(Tag.tag_name).outerjoin(ServerTag, Tag.id == ServerTag.tag_id).filter(
                        ServerTag.server_id == data_dict['id']).all()
                    for t in db_tags:
                        tag_list.append(t[0])

                    data_dict['tag_list'] = tag_list
                    server_list.append(data_dict)

                return self.write(dict(code=0, msg='获取成功', count=count, data=server_list))

            if limit == "888":
                ### 888查看所有
                count = session.query(Server).count()
                server_info = session.query(Server).order_by(Server.id).all()
            else:
                ## 正常分页搜索
                if key and value:
                    count = session.query(Server).filter_by(**{key: value}).count()
                    server_info = session.query(Server).filter_by(**{key: value}).order_by(Server.id).offset(
                        limit_start).limit(int(limit))
                else:
                    count = session.query(Server).count()
                    server_info = session.query(Server).order_by(Server.id).offset(limit_start).limit(int(limit))

            for msg in server_info:
                tag_list = []
                data_dict = model_to_dict(msg)
                db_tags = session.query(Tag.tag_name).outerjoin(ServerTag, Tag.id == ServerTag.tag_id).filter(
                    ServerTag.server_id == data_dict['id']).all()
                for t in db_tags:
                    tag_list.append(t[0])
                data_dict['create_time'] = str(data_dict['create_time'])
                data_dict['tag_list'] = tag_list
                server_list.append(data_dict)

        self.write(dict(code=0, msg='获取成功', count=count, data=server_list))