Ejemplo n.º 1
0
def get_ns_variable(access_token, project_id, namespace_id):
    """获取命名空间相关的变量信息"""
    context = {}
    # 获取命名空间的信息
    resp = paas_cc.get_namespace(access_token, project_id, namespace_id)
    if resp.get('code') != 0:
        raise ValidationError('{}(namespace_id:{}):{}'.format(_("查询命名空间的信息出错"), namespace_id, resp.get('message')))
    data = resp.get('data')
    cluster_id = data.get('cluster_id')
    context['SYS_CLUSTER_ID'] = cluster_id
    context['SYS_NAMESPACE'] = data.get('name')
    has_image_secret = data.get('has_image_secret')
    # 获取镜像地址
    context['SYS_JFROG_DOMAIN'] = paas_cc.get_jfrog_domain(access_token, project_id, context['SYS_CLUSTER_ID'])
    context['SYS_IMAGE_REGISTRY_LIST'] = paas_cc.get_image_registry_list(access_token, cluster_id)
    bcs_context = get_bcs_context(access_token, project_id)
    context.update(bcs_context)
    # k8s 集群获取集群版本信息
    cluster_version = get_cluster_version(access_token, project_id, cluster_id)
    return has_image_secret, cluster_version, context
Ejemplo n.º 2
0
def get_ns_variable(access_token, project_id, namespace_id):
    """获取命名空间相关的变量信息
    """
    context = {}
    # 获取命名空间的信息
    resp = paas_cc.get_namespace(access_token, project_id, namespace_id)
    if resp.get('code') != 0:
        raise ValidationError(u"查询命名空间的信息出错(namespace_id:%s):%s" %
                              (namespace_id, resp.get('message')))
    data = resp.get('data')
    cluster_id = data.get('cluster_id')
    context['SYS_CLUSTER_ID'] = cluster_id
    context['SYS_NAMESPACE'] = data.get('name')
    has_image_secret = data.get('has_image_secret')
    # 获取镜像地址
    jfrog_domain = paas_cc.get_jfrog_domain(access_token, project_id,
                                            context['SYS_CLUSTER_ID'])
    context['SYS_JFROG_DOMAIN'] = jfrog_domain

    bcs_context = get_bcs_context(access_token, project_id)
    context.update(bcs_context)
    # k8s 集群获取集群版本信息
    cluster_version = get_cluster_version(access_token, project_id, cluster_id)
    return has_image_secret, cluster_version, context
Ejemplo n.º 3
0
    def update_services(self, request, project_id, cluster_id, namespace,
                        name):
        """更新 service"""
        access_token = request.user.token.access_token
        flag, project_kind = self.get_project_kind(request, project_id)
        if not flag:
            return project_kind

        if project_kind == MESOS_VALUE:
            # mesos 相关数据
            slz_class = ServiceCreateOrUpdateSLZ
            s_sys_con = SEVICE_SYS_CONFIG
            s_cate = 'service'
        else:
            if namespace in K8S_SYS_NAMESPACE:
                return Response({
                    "code":
                    400,
                    "message":
                    _("不允许操作系统命名空间[{}]").format(','.join(K8S_SYS_NAMESPACE)),
                    "data": {}
                })
            # k8s 相关数据
            slz_class = K8sServiceCreateOrUpdateSLZ
            s_sys_con = K8S_SEVICE_SYS_CONFIG
            s_cate = 'K8sService'

        request_data = request.data or {}
        request_data['version_id'] = request_data['version']
        request_data['item_id'] = 0
        request_data['project_id'] = project_id
        show_version_name = request_data.get('show_version_name', '')
        # 验证请求参数
        slz = slz_class(data=request.data)
        slz.is_valid(raise_exception=True)
        data = slz.data
        namespace_id = data['namespace_id']

        # 检查是否有命名空间的使用权限
        perm = bcs_perm.Namespace(request, project_id, namespace_id)
        perm.can_use(raise_exception=True)

        config = json.loads(data['config'])
        #  获取关联的应用列表
        version_id = data['version_id']
        version_entity = VersionedEntity.objects.get(id=version_id)
        entity = version_entity.get_entity()

        # 实例化时后台需要做的处理
        if project_kind == MESOS_VALUE:
            app_weight = json.loads(data['app_id'])
            apps = entity.get('application') if entity else None
            application_id_list = apps.split(',') if apps else []

            app_id_list = app_weight.keys()
            service_app_list = Application.objects.filter(
                id__in=application_id_list, app_id__in=app_id_list)

            lb_name = data.get('lb_name', '')
            handel_service_db_config(config, service_app_list, app_weight,
                                     lb_name, version_id)
        else:
            logger.exception(
                f"deploy_tag_list {type(data['deploy_tag_list'])}")
            handel_k8s_service_db_config(config,
                                         data['deploy_tag_list'],
                                         version_id,
                                         is_upadte=True)
            resource_version = data['resource_version']
            config['metadata']['resourceVersion'] = resource_version
            cluster_version = get_cluster_version(access_token, project_id,
                                                  cluster_id)
            config = handle_k8s_api_version(config, cluster_id,
                                            cluster_version, 'Service')
        # 前端的缓存数据储存到备注中
        config = handle_webcache_config(config)

        # 获取上下文信息
        username = request.user.username
        now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        context = {
            'SYS_CLUSTER_ID': cluster_id,
            'SYS_NAMESPACE': namespace,
            'SYS_VERSION_ID': version_id,
            'SYS_PROJECT_ID': project_id,
            'SYS_OPERATOR': username,
            'SYS_TEMPLATE_ID': version_entity.template_id,
            'SYS_VERSION': show_version_name,
            'LABLE_VERSION': show_version_name,
            'SYS_INSTANCE_ID': data['instance_id'],
            'SYS_CREATOR': data.get('creator', ''),
            'SYS_CREATE_TIME': data.get('create_time', ''),
            'SYS_UPDATOR': username,
            'SYS_UPDATE_TIME': now_time,
        }
        bcs_context = get_bcs_context(access_token, project_id)
        context.update(bcs_context)

        # 生成配置文件
        sys_config = copy.deepcopy(s_sys_con)
        resource_config = update_nested_dict(config, sys_config)
        resource_config = json.dumps(resource_config)
        try:
            config_profile = render_mako_context(resource_config, context)
        except Exception:
            logger.exception(u"配置文件变量替换出错\nconfig:%s\ncontext:%s" %
                             (resource_config, context))
            raise ValidationError(_("配置文件中有未替换的变量"))

        service_name = config.get('metadata', {}).get('name')
        _config_content = {
            'name': service_name,
            'config': json.loads(config_profile),
            'context': context
        }

        # 更新 service
        config_objs = InstanceConfig.objects.filter(
            namespace=namespace_id,
            category=s_cate,
            name=service_name,
        )
        if config_objs.exists():
            config_objs.update(
                creator=username,
                updator=username,
                oper_type='update',
                updated=now_time,
                is_deleted=False,
            )
            _instance_config = config_objs.first()
        else:
            _instance_config = InstanceConfig.objects.create(
                namespace=namespace_id,
                category=s_cate,
                name=service_name,
                config=config_profile,
                instance_id=data.get('instance_id', 0),
                creator=username,
                updator=username,
                oper_type='update',
                updated=now_time,
                is_deleted=False,
            )
        _config_content['instance_config_id'] = _instance_config.id
        configuration = {namespace_id: {s_cate: [_config_content]}}

        driver = get_scheduler_driver(access_token, project_id, configuration,
                                      request.project.kind)
        result = driver.instantiation(is_update=True)

        failed = []
        if isinstance(result, dict):
            failed = result.get('failed') or []
        # 添加操作审计
        activity_client.ContextActivityLogClient(
            project_id=project_id,
            user=username,
            resource_type="instance",
            resource=service_name,
            resource_id=_instance_config.id,
            extra=json.dumps(configuration),
            description=_("更新Service[{}]命名空间[{}]").format(
                service_name, namespace),
        ).log_modify(activity_status="failed" if failed else "succeed")

        if failed:
            return Response({
                "code":
                400,
                "message":
                _("Service[{}]在命名空间[{}]更新失败,请联系集群管理员解决").format(
                    service_name, namespace),
                "data": {},
            })
        return Response({"code": 0, "message": "OK", "data": {}})