Search in sources :

Example 1 with CustomResourceDefinition

use of io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceDefinition in project fabric8-maven-plugin by fabric8io.

the class ApplyService method applyCustomResourceDefinition.

public void applyCustomResourceDefinition(CustomResourceDefinition entity, String sourceName) {
    String namespace = getNamespace(entity);
    String id = getName(entity);
    Objects.requireNonNull(id, "No name for " + entity + " " + sourceName);
    if (isServicesOnlyMode()) {
        log.debug("Only processing Services right now so ignoring Custom Resource Definition: " + namespace + ":" + id);
        return;
    }
    CustomResourceDefinition old = kubernetesClient.customResourceDefinitions().withName(id).get();
    if (isRunning(old)) {
        if (UserConfigurationCompare.configEqual(entity, old)) {
            log.info("Custom Resource Definition has not changed so not doing anything");
        } else {
            if (isRecreateMode()) {
                log.info("Deleting Custom Resource Definition: " + id);
                kubernetesClient.customResourceDefinitions().withName(id).delete();
                doCreateCustomResourceDefinition(entity, sourceName);
            } else {
                log.info("Updating a Custom Resource Definition from " + sourceName + " name " + getName(entity));
                try {
                    HasMetadata answer = patchService.compareAndPatchEntity(namespace, entity, old);
                    log.info("Updated Custom Resource Definition result: " + getName(answer));
                } catch (Exception e) {
                    onApplyError("Failed to update Custom Resource Definition from " + sourceName + ". " + e + ". " + entity, e);
                }
            }
        }
    } else {
        if (!isAllowCreate()) {
            log.warn("Creation disabled so not creating a Custom Resource Definition from " + sourceName + " name " + getName(entity));
        } else {
            doCreateCustomResourceDefinition(entity, sourceName);
        }
    }
}
Also used : HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) CustomResourceDefinition(io.fabric8.kubernetes.api.model.apiextensions.CustomResourceDefinition) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException)

Example 2 with CustomResourceDefinition

use of io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceDefinition in project fabric8-maven-plugin by fabric8io.

the class ApplyService method applyEntity.

/**
 * Applies the given DTOs onto the Kubernetes master
 */
private void applyEntity(Object dto, String sourceName) throws Exception {
    if (dto instanceof Pod) {
        applyPod((Pod) dto, sourceName);
    } else if (dto instanceof ReplicationController) {
        applyReplicationController((ReplicationController) dto, sourceName);
    } else if (dto instanceof Service) {
        applyService((Service) dto, sourceName);
    } else if (dto instanceof Route) {
        applyRoute((Route) dto, sourceName);
    } else if (dto instanceof BuildConfig) {
        applyBuildConfig((BuildConfig) dto, sourceName);
    } else if (dto instanceof DeploymentConfig) {
        DeploymentConfig resource = (DeploymentConfig) dto;
        OpenShiftClient openShiftClient = getOpenShiftClient();
        if (openShiftClient != null) {
            applyResource(resource, sourceName, openShiftClient.deploymentConfigs());
        } else {
            log.warn("Not connected to OpenShift cluster so cannot apply entity " + dto);
        }
    } else if (dto instanceof RoleBinding) {
        applyRoleBinding((RoleBinding) dto, sourceName);
    } else if (dto instanceof Role) {
        Role resource = (Role) dto;
        OpenShiftClient openShiftClient = getOpenShiftClient();
        if (openShiftClient != null) {
            applyResource(resource, sourceName, openShiftClient.rbac().roles());
        } else {
            log.warn("Not connected to OpenShift cluster so cannot apply entity " + dto);
        }
    } else if (dto instanceof ImageStream) {
        applyImageStream((ImageStream) dto, sourceName);
    } else if (dto instanceof OAuthClient) {
        applyOAuthClient((OAuthClient) dto, sourceName);
    } else if (dto instanceof Template) {
        applyTemplate((Template) dto, sourceName);
    } else if (dto instanceof ServiceAccount) {
        applyServiceAccount((ServiceAccount) dto, sourceName);
    } else if (dto instanceof Secret) {
        applySecret((Secret) dto, sourceName);
    } else if (dto instanceof ConfigMap) {
        applyResource((ConfigMap) dto, sourceName, kubernetesClient.configMaps());
    } else if (dto instanceof DaemonSet) {
        applyResource((DaemonSet) dto, sourceName, kubernetesClient.apps().daemonSets());
    } else if (dto instanceof Deployment) {
        applyResource((Deployment) dto, sourceName, kubernetesClient.extensions().deployments());
    } else if (dto instanceof ReplicaSet) {
        applyResource((ReplicaSet) dto, sourceName, kubernetesClient.extensions().replicaSets());
    } else if (dto instanceof StatefulSet) {
        applyResource((StatefulSet) dto, sourceName, kubernetesClient.apps().statefulSets());
    } else if (dto instanceof Ingress) {
        applyResource((Ingress) dto, sourceName, kubernetesClient.extensions().ingresses());
    } else if (dto instanceof PersistentVolumeClaim) {
        applyPersistentVolumeClaim((PersistentVolumeClaim) dto, sourceName);
    } else if (dto instanceof CustomResourceDefinition) {
        applyCustomResourceDefinition((CustomResourceDefinition) dto, sourceName);
    } else if (dto instanceof Job) {
        applyJob((Job) dto, sourceName);
    } else if (dto instanceof HasMetadata) {
        HasMetadata entity = (HasMetadata) dto;
        try {
            log.info("Applying " + getKind(entity) + " " + getName(entity) + " from " + sourceName);
            kubernetesClient.resource(entity).inNamespace(getNamespace(entity)).createOrReplace();
        } catch (Exception e) {
            onApplyError("Failed to create " + getKind(entity) + " from " + sourceName + ". " + e, e);
        }
    } else {
        throw new IllegalArgumentException("Unknown entity type " + dto);
    }
}
Also used : ServiceAccount(io.fabric8.kubernetes.api.model.ServiceAccount) OAuthClient(io.fabric8.openshift.api.model.OAuthClient) DoneableImageStream(io.fabric8.openshift.api.model.DoneableImageStream) ImageStream(io.fabric8.openshift.api.model.ImageStream) Deployment(io.fabric8.kubernetes.api.model.apps.Deployment) Template(io.fabric8.openshift.api.model.Template) ReplicationController(io.fabric8.kubernetes.api.model.ReplicationController) BuildConfig(io.fabric8.openshift.api.model.BuildConfig) RoleBinding(io.fabric8.kubernetes.api.model.rbac.RoleBinding) Job(io.fabric8.kubernetes.api.model.batch.Job) ReplicaSet(io.fabric8.kubernetes.api.model.apps.ReplicaSet) Route(io.fabric8.openshift.api.model.Route) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) Pod(io.fabric8.kubernetes.api.model.Pod) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) CustomResourceDefinition(io.fabric8.kubernetes.api.model.apiextensions.CustomResourceDefinition) Service(io.fabric8.kubernetes.api.model.Service) Ingress(io.fabric8.kubernetes.api.model.extensions.Ingress) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) Role(io.fabric8.kubernetes.api.model.rbac.Role) Secret(io.fabric8.kubernetes.api.model.Secret) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) DaemonSet(io.fabric8.kubernetes.api.model.apps.DaemonSet) PersistentVolumeClaim(io.fabric8.kubernetes.api.model.PersistentVolumeClaim) DeploymentConfig(io.fabric8.openshift.api.model.DeploymentConfig) StatefulSet(io.fabric8.kubernetes.api.model.apps.StatefulSet)

Example 3 with CustomResourceDefinition

use of io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceDefinition in project java-operator-sdk by java-operator-sdk.

the class Controller method start.

/**
 * Registers the specified controller with this operator, overriding its default configuration by
 * the specified one (usually created via
 * {@link io.javaoperatorsdk.operator.api.config.ControllerConfigurationOverrider#override(ControllerConfiguration)},
 * passing it the controller's original configuration.
 *
 * @throws OperatorException if a problem occurred during the registration process
 */
public void start() throws OperatorException {
    final Class<R> resClass = configuration.getResourceClass();
    final String controllerName = configuration.getName();
    final var crdName = configuration.getResourceTypeName();
    final var specVersion = "v1";
    // fail early if we're missing the current namespace information
    failOnMissingCurrentNS();
    try {
        // check that the custom resource is known by the cluster if configured that way
        // todo: check proper CRD spec version based on config
        final CustomResourceDefinition crd;
        if (configurationService().checkCRDAndValidateLocalModel() && CustomResource.class.isAssignableFrom(resClass)) {
            crd = kubernetesClient.apiextensions().v1().customResourceDefinitions().withName(crdName).get();
            if (crd == null) {
                throwMissingCRDException(crdName, specVersion, controllerName);
            }
            // Apply validations that are not handled by fabric8
            CustomResourceUtils.assertCustomResource(resClass, crd);
        }
        eventSourceManager = new EventSourceManager<>(this);
        if (reconciler instanceof EventSourceInitializer) {
            ((EventSourceInitializer<R>) reconciler).prepareEventSources(new EventSourceContext<>(eventSourceManager.getControllerResourceEventSource(), configurationService(), kubernetesClient)).forEach(eventSourceManager::registerEventSource);
        }
        eventSourceManager.start();
    } catch (MissingCRDException e) {
        throwMissingCRDException(crdName, specVersion, controllerName);
    }
}
Also used : EventSourceInitializer(io.javaoperatorsdk.operator.api.reconciler.EventSourceInitializer) MissingCRDException(io.javaoperatorsdk.operator.MissingCRDException) EventSourceContext(io.javaoperatorsdk.operator.api.reconciler.EventSourceContext) CustomResource(io.fabric8.kubernetes.client.CustomResource) CustomResourceDefinition(io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinition)

Example 4 with CustomResourceDefinition

use of io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceDefinition in project entando-k8s-controller-coordinator by entando-k8s.

the class CrdManagementTest method testCrdRegistration.

@Test
@Description("All information related to my custom resource, the capabilities it supports and its controller images should be extracted" + " from my CustomResourceDefinition's annotations")
void testCrdRegistration() throws IOException {
    step("Given I have started the Entando Operator", () -> entandoControllerCoordinator.onStartup(new StartupEvent()));
    ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
    final CustomResourceDefinition value = objectMapper.readValue(Thread.currentThread().getContextClassLoader().getResource("mycrds.test.org.crd.yaml"), CustomResourceDefinition.class);
    final MetadataNested<CustomResourceDefinitionBuilder> builder = new CustomResourceDefinitionBuilder(value).editMetadata();
    step("And I have a CustomResourceDefinition with", () -> {
        step(format("the %s label ", LabelNames.CRD_OF_INTEREST.getName()), () -> {
            builder.addToLabels(LabelNames.CRD_OF_INTEREST.getName(), "MyCRD");
        });
        step(format("and the %s annotation ", AnnotationNames.CONTROLLER_IMAGE), () -> {
            builder.addToAnnotations(AnnotationNames.CONTROLLER_IMAGE.getName(), "test/my-controller");
        });
        attachment("CustomResourceDefinition", objectMapper.writeValueAsString(builder.endMetadata().build()));
    });
    step("When I register my CustomResourceDefinition", () -> {
        final CustomResourceDefinition crd = client.getCluster().putCustomResourceDefinition(builder.endMetadata().build());
        attachment("CustomResourceDefinition", objectMapper.writeValueAsString(crd));
    });
    step("Then my custom resource definition is mapped in the " + CoordinatorUtils.ENTANDO_CRD_NAMES_CONFIGMAP_NAME + " ConfigMap", () -> {
        assertThat(client.findOrCreateControllerConfigMap(CoordinatorUtils.ENTANDO_CRD_NAMES_CONFIGMAP_NAME).getData()).containsEntry("MyCRD.test.org", "mycrds.test.org");
    });
    step("Then my controller image is registered in the EntandoControllerCoordinator", () -> {
        final SerializedEntandoResource resource = new SerializedEntandoResource();
        resource.setDefinition(CustomResourceDefinitionContext.fromCrd(builder.endMetadata().build()));
        assertThat(entandoControllerCoordinator.getControllerImageFor(resource)).isEqualTo("test/my-controller");
    });
}
Also used : CustomResourceDefinitionBuilder(io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceDefinitionBuilder) SerializedEntandoResource(org.entando.kubernetes.controller.spi.client.SerializedEntandoResource) CustomResourceDefinition(io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceDefinition) StartupEvent(io.quarkus.runtime.StartupEvent) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Description(io.qameta.allure.Description) Test(org.junit.jupiter.api.Test)

Example 5 with CustomResourceDefinition

use of io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceDefinition in project entando-k8s-controller-coordinator by entando-k8s.

the class CrdManagementTest method testCapabilityEvent.

@Test
@Description("Capabilities that my controller image supports should also result in my controller image to be executed against the " + "ProvidedCapability")
void testCapabilityEvent() throws IOException {
    step("Given I prepared a namespace scoped deployment of the EntandoOperator", () -> System.setProperty(EntandoOperatorConfigProperty.ENTANDO_NAMESPACES_TO_OBSERVE.getJvmSystemProperty(), MY_NAMESPACE));
    step("Given I have started the Entando Operator", () -> entandoControllerCoordinator.onStartup(new StartupEvent()));
    ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
    final CustomResourceDefinition value = objectMapper.readValue(Thread.currentThread().getContextClassLoader().getResource("mycrds.test.org.crd.yaml"), CustomResourceDefinition.class);
    final MetadataNested<CustomResourceDefinitionBuilder> builder = new CustomResourceDefinitionBuilder(value).editMetadata();
    step("And I have a CustomResourceDefinition with", () -> {
        step(format("the %s label ", LabelNames.CRD_OF_INTEREST.getName()), () -> {
            builder.addToLabels(LabelNames.CRD_OF_INTEREST.getName(), "MyCRD");
        });
        step(format("and the %s annotation ", AnnotationNames.CONTROLLER_IMAGE.getName()), () -> {
            builder.addToAnnotations(AnnotationNames.CONTROLLER_IMAGE.getName(), "test/my-controller");
        });
        step(format("and the %s annotation ", AnnotationNames.SUPPORTED_CAPABILITIES), () -> {
            builder.addToAnnotations(AnnotationNames.SUPPORTED_CAPABILITIES.getName(), "mysql.dbms");
        });
    });
    step("And I have registered my custom resource definition", () -> {
        client.getCluster().putCustomResourceDefinition(builder.endMetadata().build());
    });
    final ProvidedCapability providedCapability = new ProvidedCapabilityBuilder().withNewMetadata().withName("my-capability").withNamespace(MY_NAMESPACE).endMetadata().withNewSpec().withCapability(StandardCapability.DBMS).withImplementation(StandardCapabilityImplementation.MYSQL).endSpec().build();
    step("When I create a new ProvidedCapability requiring the capability associated with my CustomResourceDefinition ", () -> client.createOrPatchEntandoResource(CoordinatorTestUtils.toSerializedResource(providedCapability)));
    step(format("Then a controller pod has been created with the image that I specified in the %s annotation", AnnotationNames.CONTROLLER_IMAGE.getName()), () -> {
        await().atMost(10, TimeUnit.SECONDS).ignoreExceptions().until(() -> client.loadPod(AbstractK8SClientDouble.CONTROLLER_NAMESPACE, CoordinatorUtils.podLabelsFor(providedCapability)) != null);
        assertThat(client.loadPod(AbstractK8SClientDouble.CONTROLLER_NAMESPACE, CoordinatorUtils.podLabelsFor(providedCapability)).getSpec().getContainers().get(0).getImage()).contains("test/my-controller");
    });
}
Also used : CustomResourceDefinitionBuilder(io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceDefinitionBuilder) CustomResourceDefinition(io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceDefinition) StartupEvent(io.quarkus.runtime.StartupEvent) ProvidedCapability(org.entando.kubernetes.model.capability.ProvidedCapability) ProvidedCapabilityBuilder(org.entando.kubernetes.model.capability.ProvidedCapabilityBuilder) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Description(io.qameta.allure.Description) Test(org.junit.jupiter.api.Test)

Aggregations

CustomResourceDefinition (io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinition)60 Test (org.junit.jupiter.api.Test)49 CustomResourceDefinition (io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceDefinition)30 Description (io.qameta.allure.Description)12 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)11 IOException (java.io.IOException)11 ObjectMetaBuilder (io.fabric8.kubernetes.api.model.ObjectMetaBuilder)10 CustomResourceDefinitionBuilder (io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceDefinitionBuilder)10 Resource (io.fabric8.kubernetes.client.dsl.Resource)10 CustomResourceDefinitionContext (io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext)10 ArrayList (java.util.ArrayList)10 BeforeEach (org.junit.jupiter.api.BeforeEach)10 CustomResource (io.fabric8.kubernetes.client.CustomResource)9 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)7 YAMLFactory (com.fasterxml.jackson.dataformat.yaml.YAMLFactory)7 StartupEvent (io.quarkus.runtime.StartupEvent)7 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)6 ConfigMapBuilder (io.fabric8.kubernetes.api.model.ConfigMapBuilder)6 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)6 ServiceAccount (io.fabric8.kubernetes.api.model.ServiceAccount)6