def create_crd_from_yaml(api_extensions_v1_beta1: ApiextensionsV1beta1Api,
                         yaml_manifest) -> str:
    """
    Create a CRD based on yaml file.

    :param api_extensions_v1_beta1: ApiextensionsV1beta1Api
    :param yaml_manifest: an absolute path to file
    :return: str
    """
    print("Create CRD:")
    with open(yaml_manifest) as f:
        dep = yaml.safe_load(f)

    try:
        api_extensions_v1_beta1.create_custom_resource_definition(dep)
    except Exception as ex:
        # https://github.com/kubernetes-client/python/issues/376
        if ex.args[0] == 'Invalid value for `conditions`, must not be `None`':
            print(
                "There was an insignificant exception during the CRD creation. Continue..."
            )
        else:
            pytest.fail(f"An unexpected exception {ex} occurred. Exiting...")
    print(f"CRD created with name '{dep['metadata']['name']}'")
    return dep['metadata']['name']
def delete_crd(api_extensions_v1_beta1: ApiextensionsV1beta1Api, name) -> None:
    """
    Delete a CRD.

    :param api_extensions_v1_beta1: ApiextensionsV1beta1Api
    :param name:
    :return:
    """
    print(f"Delete a CRD: {name}")
    delete_options = client.V1DeleteOptions()
    api_extensions_v1_beta1.delete_custom_resource_definition(name, delete_options)
    ensure_item_removal(api_extensions_v1_beta1.read_custom_resource_definition, name)
    print(f"CRD was removed with name '{name}'")
Esempio n. 3
0
    def _cleanup(resource):
        k8s_v1beta1_client = ApiextensionsV1beta1Api(admin_mc.k8s_client)
        k8s_client = CustomObjectsApi(admin_mc.k8s_client)

        def clean():
            kind = resource["kind"]
            metadata = resource["metadata"]
            api_version = resource["apiVersion"]
            api_version_parts = api_version.split("/")
            if len(api_version_parts) != 2:
                raise ValueError("Error parsing ApiVersion [" + api_version +
                                 "]." + "Expected form \"group/version\"")

            group = api_version_parts[0]
            version = api_version_parts[1]

            crd_list = k8s_v1beta1_client.\
                list_custom_resource_definition().items
            crd = list(
                filter(
                    lambda x: x.spec.names.kind == kind and x.spec.group ==
                    group and x.spec.version == version, crd_list))[0]
            try:
                k8s_client.delete_namespaced_custom_object(
                    group, version, metadata["namespace"],
                    crd.spec.names.plural, metadata["name"], {})
            except ApiException as e:
                body = json.loads(e.body)
                if body["code"] not in WAIT_HTTP_ERROR_CODES:
                    raise e

        request.addfinalizer(clean)
def create_crd(api_extensions_v1_beta1: ApiextensionsV1beta1Api, body) -> None:
    """
    Create a CRD based on a dict

    :param api_extensions_v1_beta1: ApiextensionsV1beta1Api
    :param body: a dict
    """
    try:
        api_extensions_v1_beta1.create_custom_resource_definition(body)
    except ApiException as api_ex:
        raise api_ex
    except Exception as ex:
        # https://github.com/kubernetes-client/python/issues/376
        if ex.args[0] == "Invalid value for `conditions`, must not be `None`":
            print("There was an insignificant exception during the CRD creation. Continue...")
        else:
            pytest.fail(f"An unexpected exception {ex} occurred. Exiting...")
Esempio n. 5
0
    def __init__(self,
                 metadata: V1ObjectMeta,
                 spec: CustomResourceDefinitionSpec,
                 status: V1beta1CustomResourceDefinitionStatus = None):
        super().__init__(
            api_version=u'apiextensions.k8s.io/v1beta1',
            kind=None,
            metadata=metadata,
            spec=spec,
            status=status,
        )

        self.api = ApiextensionsV1beta1Api()
        self.loop = asyncio.get_event_loop()
Esempio n. 6
0
def try_creating_custom_objects(manifests: List[Manifest]):
    logging.info("Fetching CRDs available in the cluster...")
    try:
        custom_resources = (
            ApiextensionsV1beta1Api().list_custom_resource_definition().items)
    except ApiException as err:
        logging.error("Failed to fetch CRDs: %s", err.reason)
        raise

    available_kinds = {r.spec.names.kind.lower() for r in custom_resources}

    for m in manifests:
        logging.info("Found a custom manifest: %s %r", m.body["kind"], m.name)
        if m.body["kind"].lower() not in available_kinds:
            logging.error(
                "Unsupported custom manifest %r of kind %r is ignored. "
                "Supported custom resource types are: %s",
                m.name,
                m.body["kind"],
                available_kinds,
            )
            continue

        # By supporting only namespaced resources we don't have to manage
        # the cleanup - it will be handled by the deletion of the namespace.
        matching_resources = [
            r for r in custom_resources
            if r.spec.names.kind.lower() == m.body["kind"].lower()
            and r.spec.scope.lower() == "namespaced"
        ]
        if not matching_resources:
            logging.error(
                "Failed to match %r to a namespaced custom resource "
                "definition. Non-namespaced resources are not supported!",
                m.body["kind"],
            )
            continue

        _create_custom_object_with_plural(
            custom_object=m, plural=matching_resources[0].spec.names.plural)