Пример #1
0
def create_custom_resource_definition(body):
    api = get_extensions_v1beta_api()
    body_obj = client.V1beta1CustomResourceDefinition(
        spec=body['spec'], metadata=body['metadata'])
    try:
        api.create_custom_resource_definition(body_obj)
    except ValueError:
        # NOTE(ralonsoh): bug in kubernetes-client/python 6.0.0
        # https://github.com/kubernetes-client/python/issues/491
        pass
    except ApiException:
        raise exceptions.KubernetesApiException(
            action='create', resource='CustomResourceDefinition')
Пример #2
0
 def create_definition(self):
     names = client.V1beta1CustomResourceDefinitionNames(
         kind="Resource", plural=LOCK_PLURAL, singular=LOCK_SINGULAR)
     metadata = client.V1ObjectMeta(
         name="{}.{}".format(LOCK_PLURAL, LOCK_GROUP),
         resource_version=LOCK_VERSION)
     status = client.V1beta1CustomResourceDefinitionStatus(
         accepted_names=names,
         conditions=[],
         stored_versions=[LOCK_VERSION])
     spec = client.V1beta1CustomResourceDefinitionSpec(
         group=LOCK_GROUP,
         names=names,
         scope="Namespaced",
         version=LOCK_VERSION)
     crd = client.V1beta1CustomResourceDefinition(
         spec=spec,
         status=status,
         metadata=metadata,
         kind="CustomResourceDefinition")
     try:
         self.k8s.create_custom_resource_definition(crd)
     except ValueError as err:
         # Because of an issue with the Kubernetes code, the API server
         # may return `null` for the required field `conditions` in
         # kubernetes.client.V1beta1CustomResourceDefinitionStatus
         # This causes validation to fail which will raise the subsequent
         # ValueError even though the CRD was created successfully
         # https://github.com/kubernetes-client/gen/issues/52
         # TODO if this is fixed upstream this should be removed
         known_msg = "Invalid value for `conditions`, must not be `None`"
         known_err = ValueError(known_msg)
         if err.args != known_err.args:
             raise
         LOG.debug("Encountered known issue while creating CRD, continuing")
     except ApiException as err:
         # If a 409 is received then the definition already exists
         if err.status != 409:
             raise
Пример #3
0
 def _custom_resource_definition():
     singular = 'vcenter-template'
     plural = singular + 's'
     name = f'{plural}.{CustomResourceDefinitionLoader.API_GROUP}'
     return client.V1beta1CustomResourceDefinition(
         metadata={
             'name': name,
         },
         spec={
             'group': CustomResourceDefinitionLoader.API_GROUP,
             'version': 'v1',
             'versions': [{
                 'name': 'v1',
                 'served': True,
                 'storage': True
             }],
             'scope': 'Namespaced',
             'names': {
                 'singular': singular,
                 'plural': plural,
                 'kind': 'VCenterTemplate',
                 'shortNames': ['vct'],
             }
         })
def crud_crd_object(namespace, obj, action):
    """Create Custom Resource Definitino object"""
    # Using the API because of LP:1886694
    logging.info("Creating CRD object with K8s API")
    _load_kube_config()

    body = client.V1beta1CustomResourceDefinition(**obj)

    with client.ApiClient() as api_client:
        api_instance = client.ApiextensionsV1beta1Api(api_client)
        try:
            if action.lower() == "create":
                api_instance.create_custom_resource_definition(body,
                                                               pretty=True)
            elif action.lower() == "delete":
                api_instance.delete_custom_resource_definition(
                    name=obj["metadata"]["name"], pretty=True)
        except ApiException as err:
            if err.status == 409:
                # ignore "already exists" errors so that we can recover from
                # partially failed setups
                return
            else:
                raise
def create_crd_old():
    """
    Create IBM Spectrum Scale CSI Operator CRD (Custom Resource Defination) Object

    Args:
       None

    Returns:
       None

    Raises:
        Raises an ValueError exception but it is expected. hence we pass.

    """

    # input to crd_metadata
    crd_labels = {
        "app.kubernetes.io/instance": "ibm-spectrum-scale-csi-operator",
        "app.kubernetes.io/managed-by": "ibm-spectrum-scale-csi-operator",
        "app.kubernetes.io/name": "ibm-spectrum-scale-csi-operator",
        "release": "ibm-spectrum-scale-csi-operator"
    }

    # input to crd_body
    crd_metadata = client.V1ObjectMeta(name="csiscaleoperators.csi.ibm.com",
                                       labels=crd_labels)

    crd_names = client.V1beta1CustomResourceDefinitionNames(
        kind="CSIScaleOperator",
        list_kind="CSIScaleOperatorList",
        plural="csiscaleoperators",
        singular="csiscaleoperator")

    crd_subresources = client.V1beta1CustomResourceSubresources(status={})

    # input to crd_validation     json input
    filepath = "../../operator/deploy/crds/csiscaleoperators.csi.ibm.com.crd.yaml"
    try:
        with open(filepath, "r") as f:
            loadcrd_yaml = yaml.full_load(f.read())
    except yaml.YAMLError as exc:
        print("Error in configuration file:", exc)
        assert False
    properties = loadcrd_yaml['spec']['validation']['openAPIV3Schema'][
        'properties']

    crd_open_apiv3_schema = client.V1beta1JSONSchemaProps(
        properties=properties, type="object")
    crd_validation = client.V1beta1CustomResourceValidation(
        open_apiv3_schema=crd_open_apiv3_schema)
    crd_versions = [
        client.V1beta1CustomResourceDefinitionVersion(name="v1",
                                                      served=True,
                                                      storage=True)
    ]

    crd_spec = client.V1beta1CustomResourceDefinitionSpec(
        group="csi.ibm.com",
        names=crd_names,
        scope="Namespaced",
        subresources=crd_subresources,
        validation=crd_validation,
        version="v1",
        versions=crd_versions)

    crd_body = client.V1beta1CustomResourceDefinition(
        api_version="apiextensions.k8s.io/v1beta1",
        kind="CustomResourceDefinition",
        metadata=crd_metadata,
        spec=crd_spec)

    crd_api_instance = client.ApiextensionsV1beta1Api()
    try:
        LOGGER.info("creating crd")
        crd_api_response = crd_api_instance.create_custom_resource_definition(
            crd_body, pretty=True)
        LOGGER.debug(str(crd_api_response))
    except ValueError:
        LOGGER.info(
            "while there is valuerror expection,but CRD created successfully")
Пример #6
0
        }))

crd_spec = client.V1beta1CustomResourceDefinitionSpec(
    group=GROUP,
    version='v1',
    scope='Namespaced',
    names=client.V1beta1CustomResourceDefinitionNames(plural=RESOURCE_NAME,
                                                      singular='crontab',
                                                      kind='CronTab',
                                                      short_names=['ct']),
    validation=crd_validation,
)

crd = client.V1beta1CustomResourceDefinition(
    api_version='apiextensions.k8s.io/v1beta1',
    kind='CustomResourceDefinition',
    metadata=crd_metadata,
    spec=crd_spec,
    status=None)

api_instance = client.ApiextensionsV1beta1Api()

result_list = api_instance.list_custom_resource_definition()
for item in result_list.items:
    if item.metadata.name == crd.metadata.name:
        print('CRD is already present')
        print(item.metadata.name)
    else:
        create_crd(api_instance, crd)

if len(result_list.items) == 0:
    create_crd(api_instance, crd)