コード例 #1
0
 def __init__(self, username: str, bk_biz_id: int):
     """
     :param username: 用户名
     :param bk_biz_id: 业务 ID
     """
     self.cc_client = BkCCClient(username)
     self.bk_biz_id = bk_biz_id
コード例 #2
0
class BizTopoQueryService:
    """ 业务拓扑信息查询 """
    def __init__(self, username: str, bk_biz_id: int):
        """
        :param username: 用户名
        :param bk_biz_id: 业务 ID
        """
        self.cc_client = BkCCClient(username)
        self.bk_biz_id = bk_biz_id

    def _fetch_biz_inst_topo(self) -> List:
        """
        查询业务拓扑

        :return: 业务,集群,模块拓扑信息
        """
        return self.cc_client.search_biz_inst_topo(self.bk_biz_id)

    def _fetch_biz_internal_module(self) -> Dict:
        """
        查询业务的内部模块

        :return: 业务的空闲机/故障机/待回收模块
        """
        return self.cc_client.get_biz_internal_module(self.bk_biz_id)

    def fetch(self) -> List:
        """
        查询全量业务拓扑

        :return: 全量业务拓扑(包含普通拓扑,内部模块)
        """
        biz_inst_topo = self._fetch_biz_inst_topo()
        raw_inner_mod_topo = self._fetch_biz_internal_module()
        # topo 最外层为业务,如果首个业务存在即为查询结果
        if biz_inst_topo and raw_inner_mod_topo:
            # 将内部模块补充到业务下属集群首位
            inner_mod_topo = {
                'bk_obj_id':
                'set',
                'bk_obj_name':
                _('集群'),
                'bk_inst_id':
                raw_inner_mod_topo['bk_set_id'],
                'bk_inst_name':
                raw_inner_mod_topo['bk_set_name'],
                'child': [{
                    'bk_obj_id': 'module',
                    'bk_obj_name': _('模块'),
                    'bk_inst_id': mod['bk_module_id'],
                    'bk_inst_name': mod['bk_module_name'],
                    'child': [],
                } for mod in raw_inner_mod_topo['module']],
            }
            biz_inst_topo[0]['child'].insert(0, inner_mod_topo)

        return biz_inst_topo
コード例 #3
0
 def test_list_biz_hosts(self, request_user, requests_mock):
     requests_mock.post(ANY, json=FAKE_HOSTS_RESP)
     resp = BkCCClient(request_user.username).list_biz_hosts(
         1001, PageData(), bk_set_ids=[], bk_module_ids=[], fields=[]
     )
     assert resp['count'] == 2
     assert resp['info'][0]['bk_host_innerip'] == '127.0.0.1'
     assert requests_mock.called
コード例 #4
0
ファイル: business.py プロジェクト: penglongli/bk-bcs
 def __init__(
     self,
     username: str,
     fields: List = None,
     condition: Dict = None,
     bk_supplier_account: str = settings.BKCC_DEFAULT_SUPPLIER_ACCOUNT,
 ):
     """
     :param username: 查询者用户名
     :param fields: 指定字段
     :param condition: 查询条件
     :param bk_supplier_account: 供应商
     """
     self.cc_client = BkCCClient(username)
     self.fields = fields
     self.condition = condition
     self.bk_supplier_account = bk_supplier_account
コード例 #5
0
 def __init__(
     self,
     username: str,
     bk_biz_id: int,
     bk_set_ids: List = None,
     bk_module_ids: List = None,
     host_property_filter: Dict = None,
     bk_supplier_account: str = settings.BKCC_DEFAULT_SUPPLIER_ACCOUNT,
 ):
     """
     :param username: 查询者用户名
     :param bk_biz_id: 业务 ID
     :param bk_set_ids: 集群 ID 列表
     :parma bk_module_ids: 模块 ID 列表
     :param host_property_filter: 主机属性组合查询条件
     :param bk_supplier_account: 供应商
     """
     self.cc_client = BkCCClient(username)
     self.bk_biz_id = bk_biz_id
     self.bk_set_ids = bk_set_ids
     self.bk_module_ids = bk_module_ids
     self.host_property_filter = host_property_filter
     self.bk_supplier_account = bk_supplier_account
コード例 #6
0
 def test_get_biz_internal_module(self, request_user, requests_mock):
     requests_mock.post(ANY, json=FAKE_INTERNAL_MODULE_RESP)
     internal_module = BkCCClient(request_user.username).get_biz_internal_module(1)
     assert internal_module['bk_set_name'] == '空闲机池'
     assert internal_module['module'][0]['bk_module_id'] == 11
     assert requests_mock.called
コード例 #7
0
 def test_search_biz_inst_topo(self, request_user, requests_mock):
     requests_mock.post(ANY, json=FAKE_TOPO_RESP)
     topo = BkCCClient(request_user.username).search_biz_inst_topo(1)
     assert topo[0]['child'][0]['bk_inst_id'] == 5001
     assert requests_mock.called
コード例 #8
0
 def test_search_business(self, request_user, requests_mock):
     requests_mock.post(ANY, json=FAKE_BIZS_RESP)
     client = BkCCClient(request_user.username)
     data = client.search_business(PageData(), ["bs2_name_id"], {"bk_biz_id": 1})
     assert data["info"][0]["bs2_name_id"] == 1
     assert requests_mock.called
コード例 #9
0
ファイル: business.py プロジェクト: penglongli/bk-bcs
class AppQueryService:
    """业务查询相关服务"""
    def __init__(
        self,
        username: str,
        fields: List = None,
        condition: Dict = None,
        bk_supplier_account: str = settings.BKCC_DEFAULT_SUPPLIER_ACCOUNT,
    ):
        """
        :param username: 查询者用户名
        :param fields: 指定字段
        :param condition: 查询条件
        :param bk_supplier_account: 供应商
        """
        self.cc_client = BkCCClient(username)
        self.fields = fields
        self.condition = condition
        self.bk_supplier_account = bk_supplier_account

    def _fetch_count(self) -> int:
        """查询指定条件下业务数量,用于后续并发查询用"""
        page = PageData(start=constants.DEFAULT_START_AT,
                        limit=constants.LIMIT_FOR_COUNT)
        resp_data = self.cc_client.search_business(page, ['bk_biz_id'],
                                                   self.condition,
                                                   self.bk_supplier_account)
        return resp_data['count']

    def fetch_all(self) -> List[Dict]:
        """并发查询 CMDB,获取符合条件的全量业务信息"""
        total = self._fetch_count()
        tasks = []
        for start in range(constants.DEFAULT_START_AT, total,
                           constants.CMDB_MAX_LIMIT):
            # 组装并行任务配置信息
            tasks.append(
                functools.partial(
                    self.cc_client.search_business,
                    PageData(start=start, limit=constants.CMDB_MAX_LIMIT),
                    self.fields,
                    self.condition,
                    self.bk_supplier_account,
                ))

        try:
            results = async_run(tasks)
        except AsyncRunException as e:
            raise CompParseBkCommonResponseError(
                None,
                _('根据条件查询全量业务失败:{}').format(e))

        # 所有的请求结果合并,即为全量数据
        return [app for r in results for app in r.ret['info']]

    def get(self, bk_biz_id: int) -> Dict:
        """获取单个业务信息"""
        resp_data = self.cc_client.search_business(
            PageData(),
            fields=self.fields,
            condition={'bk_biz_id': bk_biz_id},
            bk_supplier_account=self.bk_supplier_account,
        )
        if not (resp_data['count'] and resp_data['info']):
            raise ResourceNotFoundError(_('ID 为 {} 的业务不存在').format(bk_biz_id))
        return resp_data['info'][0]
コード例 #10
0
class HostQueryService:
    """ 主机查询相关服务 """
    def __init__(
        self,
        username: str,
        bk_biz_id: int,
        bk_set_ids: List = None,
        bk_module_ids: List = None,
        host_property_filter: Dict = None,
        bk_supplier_account: str = settings.BKCC_DEFAULT_SUPPLIER_ACCOUNT,
    ):
        """
        :param username: 查询者用户名
        :param bk_biz_id: 业务 ID
        :param bk_set_ids: 集群 ID 列表
        :parma bk_module_ids: 模块 ID 列表
        :param host_property_filter: 主机属性组合查询条件
        :param bk_supplier_account: 供应商
        """
        self.cc_client = BkCCClient(username)
        self.bk_biz_id = bk_biz_id
        self.bk_set_ids = bk_set_ids
        self.bk_module_ids = bk_module_ids
        self.host_property_filter = host_property_filter
        self.bk_supplier_account = bk_supplier_account

    def _fetch_count(self) -> int:
        """ 查询指定条件下主机数量 """
        resp_data = self.cc_client.list_biz_hosts(
            self.bk_biz_id,
            PageData(start=constants.DEFAULT_START_AT,
                     limit=constants.LIMIT_FOR_COUNT),
            self.bk_set_ids,
            self.bk_module_ids,
            ['bk_host_innerip'],
            self.host_property_filter,
            self.bk_supplier_account,
        )
        return resp_data['count']

    def fetch_all(self) -> List[Dict]:
        """
        并发查询 CMDB,获取符合条件的全量主机信息

        :return: 主机列表
        """
        total = self._fetch_count()
        tasks = []
        for start in range(constants.DEFAULT_START_AT, total,
                           constants.CMDB_LIST_HOSTS_MAX_LIMIT):
            # 组装并行任务配置信息
            tasks.append(
                functools.partial(
                    self.cc_client.list_biz_hosts,
                    self.bk_biz_id,
                    PageData(
                        start=start,
                        limit=constants.CMDB_LIST_HOSTS_MAX_LIMIT,
                    ),
                    self.bk_set_ids,
                    self.bk_module_ids,
                    constants.DEFAULT_HOST_FIELDS,
                    self.host_property_filter,
                    self.bk_supplier_account,
                ))

        try:
            results = async_run(tasks)
        except AsyncRunException as e:
            raise CompParseBkCommonResponseError(
                None,
                _('根据条件查询业务全量主机失败:{}').format(e))

        # 所有的请求结果合并,即为全量数据
        return [host for r in results for host in r.ret['info']]