def get_node_metric(request, access_token, project_id, cluster_id, cluster_type): node = paas_cc.get_node_list(access_token, project_id, cluster_id, params={"limit": 10000}) if node.get('code') != 0: raise APIError(node.get('message')) # 过滤掉状态为removed的机器 node_data = [ info for info in node.get("data", {}).get("results") or [] if info.get("status") not in [constants.NodeStatus.REMOVED.value] ] # 重新组装数据 node = { "count": len(node_data), "results": node_data, } node_total = node['count'] node_actived = 0 node_disabled = 0 if cluster_type != ClusterCOES.MESOS.value: # namespace 获取处理 client = k8s.K8SClient(access_token, project_id, cluster_id=cluster_id, env=None) namespace = client.get_namespace() if not namespace.get('result'): raise APIError(namespace.get('message')) # 节点状态处理 计算k8s有容器的节点 if node_total > 0: node_ips = [i['inner_ip'] for i in node['results']] containers = k8s_containers(request, project_id, cluster_id, node_ips) for node in node_ips: if containers.get(node, 0) > 0: node_actived += 1 else: # 节点状态处理 计算mesos有容器的节点 if node_total > 0: node_ips = [i['inner_ip'] for i in node['results']] containers = mesos_containers(request, project_id, cluster_id, node_ips) for node in node_ips: if containers.get(node, 0) > 0: node_actived += 1 node_disabled = node_total - node_actived data = { 'total': node_total, 'actived': node_actived, 'disabled': node_disabled } return data
def verify(self, request): """权限判断接口,前端使用""" # serializer在设置字段required为false时,如果参数为None,会提示字段为null if not request.data.get('resource_code'): request.data.pop('resource_code', '') serializer = serializers.PermVerifySLZ(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) data = serializer.data resource_code = data.get('resource_code') resource_name = data.get('resource_name') is_raise = data.get('is_raise') self.get_project_info(request, data['project_id']) try: perm = bcs_perm.get_perm_cls(data['resource_type'], request, data['project_id'], resource_code, resource_name) except (AttributeError, TypeError): raise APIError(_("resource_code不合法")) handler = getattr(perm, 'can_%s' % data['policy_code']) if handler: try: handler(raise_exception=True) except NoAuthPermError as error: if is_raise: raise VerifyAuthPermError(error.args[0], error.args[1]) else: raise VerifyAuthPermErrorWithNoRaise( error.args[0], error.args[1]) return APIResult({}, _("验证权限成功"))
def instantiation(self, is_update=False): """实例化""" instantiation_result = {"success": [], "failed": []} for ns_id, config in self.configuration.items(): cluster_id = [i for i in config.values()][0][0]["context"]["SYS_CLUSTER_ID"] ns_name = [i for i in config.values()][0][0]["context"]["SYS_NAMESPACE"] try: # 前置检查 self.cluster_ready(cluster_id) except ClusterNotReady as error: logger.warning("bcs_instantiation failed, cluster not ready %s", error) raise APIError("初始化失败,%s绑定的集群(%s) %s" % (ns_name, cluster_id, error)) for ns_id, config in self.configuration.items(): instance_id = [i for i in config.values()][0][0]["context"]["SYS_INSTANCE_ID"] ns_name = [i for i in config.values()][0][0]["context"]["SYS_NAMESPACE"] ns = {"ns_id": ns_id, "ns_name": ns_name, "instance_id": instance_id, "res_type": "", "err_msg": ""} bcs_success = True try: self.instantiation_ns(ns_id, config, is_update) except Rollback as error: if self.is_rollback and (not is_update): self.handler_rollback(ns_id) ns["res_type"] = error.args[0]["res_type"] ns["err_msg"] = error.args[0].get("message", "") bcs_success = False logger.warning("bcs_api: error, %s, add failed to result %s", ns, instantiation_result) except ConfigError as error: if self.is_rollback and (not is_update): self.handler_rollback(ns_id) bcs_success = False ns["err_msg"] = str(error) ns["show_err_msg"] = True logger.exception("bcs_api: %s, instantiation error, %s", ns, error) logger.warning("bcs_api: exception, %s, add failed to result %s", ns, instantiation_result) except Exception as error: if self.is_rollback and (not is_update): self.handler_rollback(ns_id) bcs_success = False ns["err_msg"] = str(error) logger.exception("bcs_api: %s, instantiation error, %s", ns, error) logger.warning("bcs_api: exception, %s, add failed to result %s", ns, instantiation_result) # 统一修改状态 try: VersionInstance.objects.filter(pk=instance_id).update(is_bcs_success=bcs_success) # InstanceConfig.objects.filter(instance_id=instance_id).update( # is_bcs_success=bcs_success) # MetricConfig.objects.filter(instance_id=instance_id).update( # is_bcs_success=bcs_success) except Exception: logging.exception("save is_bcs_success error") if bcs_success is False: instantiation_result["failed"].append(ns) else: instantiation_result["success"].append(ns) logger.info("bcs_api: instantiation_result, %s", instantiation_result) return instantiation_result
def _wrapped_func(*args, **kwargs): # 判断是否抛异常 raise_exception = kwargs.pop("raise_exception", True) try: resp = func(*args, **kwargs) format_func = FORMAT_FUNC.get(f) if format_func: # 获取内容 if isinstance(resp, Response): content = resp.text elif isinstance(resp, six.string_types): content = resp else: raise ValueError( _("返回值[{}]必须是字符串或者Response对象").format(resp)) # 解析格式 err_msg = kwargs.get("err_msg", None) try: resp = format_func(content) except Exception as e: logger.exception("请求第三方失败,使用【%s】格式解析 %s 异常,%s", f, content, e) raise ComponentError(err_msg or e) if handle_resp: if resp.get("code") != ErrorCode.NoError: raise APIError(resp.get("message")) return resp.get("data") return resp except Exception as e: if raise_exception: raise return {"message": str(e)}
def verify_multi(self, request): """权限判断接口,前端使用, 批量接口 """ serializer = serializers.PermMultiVerifySLZ(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) data = serializer.data operator = data['operator'] msg = '' err_data = [] self.get_project_info(request, data['project_id']) for res in data['resource_list']: resource_code = res.get('resource_code') resource_name = res.get('resource_name') try: perm = bcs_perm.get_perm_cls( res['resource_type'], request, data['project_id'], resource_code, resource_name) except (AttributeError, TypeError): raise APIError(_("resource_code不合法")) handler = getattr(perm, 'can_%s' % res['policy_code']) try: if handler: handler(raise_exception=True) except bcs_perm.NoAuthPermError as error: msg = msg or error.args[0] err_data.extend(error.args[1]) if len(data['resource_list']) == 1 and err_data: raise VerifyAuthPermError(msg, err_data) elif operator == constants.PermMultiOperator.AND.value and err_data: raise VerifyAuthPermError(msg, err_data) elif operator == constants.PermMultiOperator.OR.value and len(data['resource_list']) == len(err_data): raise VerifyAuthPermError(msg, err_data) return APIResult({}, _("验证权限成功"))
def get_node_metric(request, access_token, project_id, cluster_id, cluster_type): node_data = get_cluster_nodes(access_token, project_id, cluster_id) # 重新组装数据 node = { "count": len(node_data), "results": node_data, } node_total = node['count'] node_actived = 0 node_disabled = 0 # namespace 获取处理 client = k8s.K8SClient(access_token, project_id, cluster_id=cluster_id, env=None) namespace = client.get_namespace() if not namespace.get('result'): raise APIError(namespace.get('message')) # 节点状态处理 计算k8s有容器的节点 if node_total > 0: node_ips = [i['inner_ip'] for i in node['results']] containers = k8s_containers(request, project_id, cluster_id, node_ips) for node in node_ips: if containers.get(node, 0) > 0: node_actived += 1 node_disabled = node_total - node_actived data = { 'total': node_total, 'actived': node_actived, 'disabled': node_disabled } return data
def instantiation(self, is_update=False): """实例化 """ instantiation_result = {'success': [], 'failed': []} for ns_id, config in self.configuration.items(): cluster_id = [i for i in config.values( )][0][0]['context']['SYS_CLUSTER_ID'] ns_name = [i for i in config.values( )][0][0]['context']['SYS_NAMESPACE'] try: # 前置检查 self.cluster_ready(cluster_id) except ClusterNotReady as error: logger.warning( "bcs_instantiation failed, cluster not ready %s", error) raise APIError('初始化失败,%s绑定的集群(%s) %s' % (ns_name, cluster_id, error)) for ns_id, config in self.configuration.items(): instance_id = [i for i in config.values( )][0][0]['context']['SYS_INSTANCE_ID'] ns_name = [i for i in config.values( )][0][0]['context']['SYS_NAMESPACE'] ns = {'ns_id': ns_id, 'ns_name': ns_name, 'res_type': '', 'err_msg': ''} bcs_success = True try: self.instantiation_ns(ns_id, config, is_update) except Rollback as error: if self.is_rollback and (not is_update): self.handler_rollback(ns_id) ns['res_type'] = error.args[0]['res_type'] ns['err_msg'] = error.args[0].get('message', '') bcs_success = False logger.warning( "bcs_api: error, %s, add failed to result %s", ns, instantiation_result) except ConfigError as error: if self.is_rollback and (not is_update): self.handler_rollback(ns_id) bcs_success = False ns['err_msg'] = str(error) ns['show_err_msg'] = True logger.exception( "bcs_api: %s, instantiation error, %s", ns, error) logger.warning( "bcs_api: exception, %s, add failed to result %s", ns, instantiation_result) except Exception as error: if self.is_rollback and (not is_update): self.handler_rollback(ns_id) bcs_success = False ns['err_msg'] = str(error) logger.exception( "bcs_api: %s, instantiation error, %s", ns, error) logger.warning( "bcs_api: exception, %s, add failed to result %s", ns, instantiation_result) # 统一修改状态 try: VersionInstance.objects.filter( pk=instance_id).update(is_bcs_success=bcs_success) # InstanceConfig.objects.filter(instance_id=instance_id).update( # is_bcs_success=bcs_success) # MetricConfig.objects.filter(instance_id=instance_id).update( # is_bcs_success=bcs_success) except Exception: logging.exception('save is_bcs_success error') if bcs_success is False: instantiation_result['failed'].append(ns) else: instantiation_result['success'].append(ns) logger.info('bcs_api: instantiation_result, %s', instantiation_result) return instantiation_result