Пример #1
0
def ensure_namespace(api: client.CoreV1Api, namespace):
    if len(
            api.list_namespace(
                field_selector=f'metadata.name={namespace}').items) == 0:
        logger.info(f'creating namespace: {namespace}')
        body = client.V1Namespace(metadata=V1ObjectMeta(name=namespace))
        api.create_namespace(body=body)
    else:
        logger.info(f'namespace exists: {namespace}')
Пример #2
0
def create_namespace(v1: CoreV1Api, body) -> str:
    """
    Create an ingress based on a dict.

    :param v1: CoreV1Api
    :param body: a dict
    :return: str
    """
    print("Create a namespace:")
    v1.create_namespace(body)
    print(f"Namespace created with name '{body['metadata']['name']}'")
    return body['metadata']['name']
def create_namespace(v1: CoreV1Api, body) -> str:
    """
    Create an ingress based on a dict.

    :param v1: CoreV1Api
    :param body: a dict
    :return: str
    """
    print("Create a namespace:")
    v1.create_namespace(body)
    print(f"Namespace created with name '{body['metadata']['name']}'")
    return body['metadata']['name']
Пример #4
0
def create_ns(api: client.CoreV1Api, configmap: Resource,
              cro_spec: ResourceChunk,
              logger: logging.Logger) -> Union[str, Resource]:
    ns_name = cro_spec.get("namespace", "chaostoolkit-run")
    tpl = yaml.safe_load(configmap.data['chaostoolkit-ns.yaml'])
    tpl["metadata"]["name"] = ns_name
    try:
        api.create_namespace(body=tpl)
        return ns_name, tpl
    except ApiException as e:
        if e.status == 409:
            logger.info(
                f"Namespace '{ns_name}' already exists. Let's continue...")
        else:
            raise kopf.PermanentError(
                f"Failed to create namespace: {str(e)}")
def create_namespace_with_name_from_yaml(v1: CoreV1Api, name, yaml_manifest) -> str:
    """
    Create a namespace with a specific name based on a yaml manifest.

    :param v1: CoreV1Api
    :param name: name
    :param yaml_manifest: an absolute path to file
    :return: str
    """
    print(f"Create a namespace with specific name:")
    with open(yaml_manifest) as f:
        dep = yaml.safe_load(f)
        dep['metadata']['name'] = name
        v1.create_namespace(dep)
        print(f"Namespace created with name '{str(dep['metadata']['name'])}'")
        return dep['metadata']['name']
def create_namespace_with_name_from_yaml(v1: CoreV1Api, name, yaml_manifest) -> str:
    """
    Create a namespace with a specific name based on a yaml manifest.

    :param v1: CoreV1Api
    :param name: name
    :param yaml_manifest: an absolute path to file
    :return: str
    """
    print(f"Create a namespace with specific name:")
    with open(yaml_manifest) as f:
        dep = yaml.safe_load(f)
        f.close()
        dep['metadata']['name'] = name
        v1.create_namespace(dep)
        print(f"Namespace created with name '{str(dep['metadata']['name'])}'")
        return dep['metadata']['name']
Пример #7
0
def create_ns(api: client.CoreV1Api, configmap: Resource,
              cro_spec: ResourceChunk) -> Union[str, Resource]:
    """
    If it already exists, we do not return it so that the operator does not
    take its ownership.
    """
    logger = logging.getLogger('kopf.objects')
    ns_name = cro_spec.get("namespace", "chaostoolkit-run")
    tpl = yaml.safe_load(configmap.data['chaostoolkit-ns.yaml'])
    tpl["metadata"]["name"] = ns_name
    logger.debug(f"Creating namespace with template:\n{tpl}")
    try:
        api.create_namespace(body=tpl)
        return ns_name, tpl
    except ApiException as e:
        if e.status == 409:
            logger.info(
                f"Namespace '{ns_name}' already exists. Let's continue...",
                exc_info=False)
            return ns_name, None
        else:
            raise kopf.PermanentError(f"Failed to create namespace: {str(e)}")
Пример #8
0
def upsert(client: CoreV1Api, log: BoundLogger,
           namespace: V1Namespace) -> V1Namespace:
    return common_k8s.upsert_resource(
        get(client, log, namespace), namespace, log, 'namespace',
        lambda: client.create_namespace(body=namespace), lambda: client.
        patch_namespace(namespace.metadata.name, body=namespace))
Пример #9
0
def create_user_namespace(
    api: client.CoreV1Api,
    userspace_dc: dynamic.DynamicClient,
    user_name: str,
    user_email: str,
    expected_user_namespaces: Dict[str, str],
    namespaces: List[str],
) -> None:
    env = os.environ.get("ORBIT_ENV", "")
    if not env:
        raise ValueError("Orbit Environment ORBIT_ENV is required")
    for team, user_ns in expected_user_namespaces.items():
        try:
            team_namespace = api.read_namespace(name=team).to_dict()
            team_uid = team_namespace.get("metadata", {}).get("uid", None)
            logger.info(f"Retrieved Team Namespace uid: {team_uid}")
        except Exception:
            logger.exception("Error retrieving Team Namespace")
            team_uid = None
        if user_ns not in namespaces:
            logger.info(f"User namespace {user_ns} doesnt exist. Creating...")
            kwargs = {
                "name": user_ns,
                "annotations": {"owner": user_email},
                "labels": {
                    "orbit/efs-id": EFS_FS_ID,
                    "orbit/env": os.environ.get("ORBIT_ENV"),
                    "orbit/space": "user",
                    "orbit/team": team,
                    "orbit/user": user_name,
                    # "istio-injection": "enabled",
                },
            }
            if team_uid:
                kwargs["owner_references"] = [
                    client.V1OwnerReference(api_version="v1", kind="Namespace", name=team, uid=team_uid)
                ]

            body = client.V1Namespace()
            body.metadata = client.V1ObjectMeta(**kwargs)

            try:
                # create userspace namespace resource
                api.create_namespace(body=body)
                logger.info(f"Created namespace {user_ns}")
            except ApiException as ae:
                logger.warning(f"Exception when trying to create user namespace {user_ns}")
                logger.warning(ae.body)

            try:
                # create userspace custom resource for the given user namespace
                logger.info(f"Creating userspace custom resource {user_ns}")
                create_userspace(
                    userspace_dc=userspace_dc,
                    name=user_ns,
                    env=env,
                    space="user",
                    team=team,
                    user=user_name,
                    team_efsid=EFS_FS_ID,
                    user_email=user_email,
                )
                logger.info(f"Created userspace custom resource {user_ns}")
            except ApiException as ae:
                logger.warning(f"Exception when trying to create userspace custom resource {user_ns}")
                logger.warning(ae.body)