Пример #1
0
def preview_parse(manifest, namespace):
    data = parse(manifest, namespace)
    result = dict()
    for key in data:
        r_key = "/".join(key.split(", "))
        result[r_key] = data[key].content
    return result
Пример #2
0
 def retrieve(self, request, *args, **kwargs):
     base_url = get_base_url(request)
     instance = App.objects.get(id=self.app_id)
     content = instance.release.content
     resources = parser.parse(content, instance.namespace).values()
     data = []
     # request.META.HTTP_REFERER
     # raise ValueError(request.META)
     for resource in resources:
         resource_dict = yaml.load(resource.content)
         url = resource_link(
             base_url=base_url,
             kind=resource.kind.lower(),
             name=resource_dict["metadata"]["name"],
             namespace=instance.namespace,
             release_name=instance.name,
         )
         item = {
             "link": url,
             "namespace": instance.namespace,
             "name": resource_dict["metadata"]["name"],
             "kind": resource.kind.lower(),
         }
         data.append(item)
     return Response({"data": data})
Пример #3
0
 def refresh_structure(self, namespace):
     structure = []
     resources = parser.parse(self.content, namespace).values()
     for resource in resources:
         structure.append({
             "name": resource.name.split("/")[-1],
             "kind": resource.kind,
         })
     self.structure = structure
     self.save(update_fields=["structure"])
Пример #4
0
def collect_resource_status(base_url,
                            kubeconfig,
                            app,
                            project_code,
                            bin_path=settings.DASHBOARD_CTL_BIN):
    """
    dashboard_client = make_dashboard_ctl_client(
        kubeconfig=kubeconfig
    )
    """
    def status_sumary(status, app, bin_path=settings.DASHBOARD_CTL_BIN):
        if not status and not app.transitioning_result:
            return {
                "messages": _("未找到资源,可能未部署成功,请在Helm Release列表也查看失败原因."),
                "is_normal": False,
                "desired_pods": "-",
                "ready_pods": "-",
            }

        # 暂未实现该类资源状态信息
        if "pods" not in status:
            return {
                "messages": "",
                "is_normal": True,
                "desired_pods": "-",
                "ready_pods": "-",
            }

        messages = [item["message"] for item in status["pods"]["warnings"]]
        messages = filter(lambda x: x, messages)

        desired_pods = safe_get(status, "pods.desired", None)
        ready_pods = safe_get(status, "pods.running", None)
        data = {
            "desired_pods": str(desired_pods),
            "ready_pods": str(ready_pods),
            "messages": "\n".join(messages),
            "is_normal": desired_pods == ready_pods,
        }
        return data

    namespace = app.namespace
    content = app.release.content
    resources = parser.parse(content, app.namespace)
    resources = resources.values()
    release_name = app.name

    dashboard_overview = dashboard_get_overview(kubeconfig=kubeconfig,
                                                namespace=namespace,
                                                bin_path=bin_path)

    result = {}
    structure = app.release.extract_structure(namespace)
    for item in structure:
        kind = item["kind"]
        name = item["name"]

        status = extract_state_info_from_dashboard_overview(
            overview_status=dashboard_overview,
            kind=kind,
            namespace=namespace,
            name=name)
        """
        status = {}
        if kind.lower() in ["deployment", "replicaset", "daemonset",
                            "job", "statefulset", "cronjob", "replicationcontroller"]:
            try:
                status = dashboard_client.workload_status(
                    kind=kind,
                    name=name,
                    namespace=namespace,
                    parameters=dict()
                )
            except DashboardExecutionError as e:
                if "handler returned wrong status code: got 404 want 200" in e.output:
                    pass
                else:
                    raise
        """

        if status:
            link = resource_link(
                base_url=base_url,
                kind=kind,
                project_code=project_code,
                name=name,
                namespace=namespace,
                release_name=release_name,
            )
        else:
            link = None

        key = "{kind}/{namespace}/{name}".format(
            name=name,
            namespace=namespace,
            kind=kind,
        )
        result[key] = {
            "namespace": namespace,
            "name": name,
            "kind": kind,
            "status": status,
            "status_sumary": status_sumary(status, app),
            "link": link,
        }
    return result
Пример #5
0
def helm_init(access_token, project_id, cluster_id, bcs_agent_namespace):
    if not settings.HELM_NEED_REGIST_TO_BKE_WHEN_INIT:
        data = {
            "code": 0,
            "initialized": True,
            "detail": "HELM_NEED_REGIST_TO_BKE_WHEN_INIT set",
            "message": "ok",
        }
        return data

    # 1. do registering to bcs
    # need to be re-entrant
    bcs_client = bcs_utils_client.get_bcs_client(project_id=project_id,
                                                 cluster_id=cluster_id,
                                                 access_token=access_token)
    bcs_cluster_info = bcs_client.get_or_register_bcs_cluster()
    if not bcs_cluster_info.get("result"):
        data = {
            "code": 10601,
            "message": "failed to regist to bcs.",
            "data": bcs_cluster_info
        }
        return Response(data=data)

    bcs_cluster_info = bcs_cluster_info["data"]
    content = render_bcs_agent_template(
        token=bcs_cluster_info["token"],
        bcs_cluster_id=bcs_cluster_info["bcs_cluster_id"],
        namespace="kube-system",  # namespace for bcs agent
        access_token=access_token,
        project_id=project_id,
        cluster_id=cluster_id)
    resources = parser.parse(content, bcs_agent_namespace).values()

    # 2. apply bcs agent deploy resource to target cluster
    # need to be re-entrant
    client = k8s.K8SClient(access_token, project_id, cluster_id, env=None)

    errors = []
    for item in resources:
        if item.kind != "Secret":
            continue

        data = yaml.load(item.content)
        result = client.create_secret(bcs_agent_namespace, data)
        if result["code"] == 0:
            continue
        if not (result["code"] == 4001 and "exists" in result["message"]):
            errors.append("create_secret, %s" % json.dumps(result))
            logger.error("ClusterHelmInitView client.create_secret, %s",
                         json.dumps(result))

    for item in resources:
        if item.kind != "ServiceAccount":
            continue

        data = yaml.load(item.content)
        result = client.create_serviceaccounts(bcs_agent_namespace, data)
        if result["code"] == 0:
            continue
        if not (result["code"] == 4001 and "exists" in result["message"]):
            errors.append("create_serviceaccounts, %s" % json.dumps(result))
            logger.error(
                "ClusterHelmInitView client.create_serviceaccounts, %s",
                json.dumps(result))

    for item in resources:
        if item.kind != "ClusterRoleBinding":
            continue

        data = yaml.load(item.content)
        result = client.create_clusterrolebindings(bcs_agent_namespace, data)
        if result["code"] == 0:
            continue
        if not (result["code"] == 4001 and "exists" in result["message"]):
            errors.append("create_clusterrolebindings, %s" %
                          json.dumps(result))
            logger.error(
                "ClusterHelmInitView client.create_clusterrolebindings, %s",
                json.dumps(result))

    for item in resources:
        if item.kind != "Deployment":
            continue

        data = yaml.load(item.content)
        result = client.create_deployment(bcs_agent_namespace, data)
        if result["code"] == 0:
            continue
        if not (result["code"] == 4001 and "exists" in result["message"]):
            errors.append("create_deployment, %s" % json.dumps(result))
            logger.error("ClusterHelmInitView client.create_deployment, %s",
                         json.dumps(result))

    # step3 and step4 has been moved to enable container service
    # 3. add plain public repo for project
    # public_repos = self.get_or_add_public_repos(project_id)

    # 4. add private repo for project
    # private_repos = self.get_or_add_private_repos(project_id, request.user)

    data = {
        "code": 0 if not bool(errors) else 400,
        "initialized": not bool(errors),
        "detail": errors,
        "message": "\n\n".join(errors),
    }
    return data