io.fabric8.kubernetes.client.CustomResourceList Java Examples

The following examples show how to use io.fabric8.kubernetes.client.CustomResourceList. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IntegrationTestSupport.java    From java-operator-sdk with Apache License 2.0 6 votes vote down vote up
public void initialize(boolean updateStatus) {
    k8sClient = new DefaultKubernetesClient();

    log.info("Initializing integration test in namespace {}", TEST_NAMESPACE);

    CustomResourceDefinition crd = loadYaml(CustomResourceDefinition.class, "test-crd.yaml");
    k8sClient.customResourceDefinitions().createOrReplace(crd);

    controller = new TestCustomResourceController(k8sClient, updateStatus);
    Class doneableClass = getCustomResourceDoneableClass(controller);
    crOperations = k8sClient.customResources(crd, TestCustomResource.class, CustomResourceList.class, doneableClass);
    crOperations.inNamespace(TEST_NAMESPACE).delete(crOperations.list().getItems());

    if (k8sClient.namespaces().withName(TEST_NAMESPACE).get() == null) {
        k8sClient.namespaces().create(new NamespaceBuilder()
                .withMetadata(new ObjectMetaBuilder().withName(TEST_NAMESPACE).build()).build());
    }
    operator = new Operator(k8sClient);
    operator.registerController(controller, TEST_NAMESPACE);
    log.info("Operator is running with TestCustomeResourceController");
}
 
Example #2
Source File: Operator.java    From java-operator-sdk with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private <R extends CustomResource> void registerController(ResourceController<R> controller,
                                                           boolean watchAllNamespaces, Retry retry, String... targetNamespaces) throws OperatorException {
    Class<R> resClass = getCustomResourceClass(controller);
    CustomResourceDefinition crd = getCustomResourceDefinitionForController(controller);
    KubernetesDeserializer.registerCustomKind(getApiVersion(crd), getKind(crd), resClass);

    MixedOperation client = k8sClient.customResources(crd, resClass, CustomResourceList.class, getCustomResourceDoneableClass(controller));
    EventDispatcher eventDispatcher = new EventDispatcher(controller,
            getDefaultFinalizer(controller), new EventDispatcher.CustomResourceReplaceFacade(client));
    EventScheduler eventScheduler = new EventScheduler(eventDispatcher, retry, ControllerUtils.getGenerationEventProcessing(controller));
    registerWatches(controller, client, resClass, watchAllNamespaces, targetNamespaces, eventScheduler);
}
 
Example #3
Source File: Crds.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public static <T extends CustomResource, L extends CustomResourceList<T>, D extends Doneable<T>> MixedOperation<T, L, D, Resource<T, D>>
        operation(KubernetesClient client,
                  Class<T> cls,
                  Class<L> listCls,
                  Class<D> doneableCls) {
    return client.customResources(crd(cls), cls, listCls, doneableCls);
}
 
Example #4
Source File: Operator.java    From java-operator-sdk with Apache License 2.0 4 votes vote down vote up
public <T extends CustomResource, L extends CustomResourceList<T>, D extends CustomResourceDoneable<T>> CustomResourceOperationsImpl<T, L, D>
getCustomResourceClients(Class<T> customResourceClass) {
    return customResourceClients.get(customResourceClass);
}
 
Example #5
Source File: IntegrationTestSupport.java    From java-operator-sdk with Apache License 2.0 4 votes vote down vote up
public MixedOperation<TestCustomResource, CustomResourceList, CustomResourceDoneable, Resource<TestCustomResource, CustomResourceDoneable>> getCrOperations() {
    return crOperations;
}
 
Example #6
Source File: CrdDeployer.java    From abstract-operator with Apache License 2.0 4 votes vote down vote up
public CustomResourceDefinition initCrds(KubernetesClient client,
                                                String prefix,
                                                String entityName,
                                                String[] shortNames,
                                                String pluralName,
                                                String[] additionalPrinterColumnNames,
                                                String[] additionalPrinterColumnPaths,
                                                String[] additionalPrinterColumnTypes,
                                                Class<? extends EntityInfo> infoClass,
                                                boolean isOpenshift) {
    final String newPrefix = prefix.substring(0, prefix.length() - 1);
    CustomResourceDefinition crdToReturn;

    Serialization.jsonMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    List<CustomResourceDefinition> crds = client.customResourceDefinitions()
            .list()
            .getItems()
            .stream()
            .filter(p -> entityName.equals(p.getSpec().getNames().getKind()) && newPrefix.equals(p.getSpec().getGroup()))
            .collect(Collectors.toList());
    if (!crds.isEmpty()) {
        crdToReturn = crds.get(0);
        log.info("CustomResourceDefinition for {} has been found in the K8s, so we are skipping the creation.", entityName);
    } else {
        log.info("Creating CustomResourceDefinition for {}.", entityName);
        JSONSchemaProps schema = JSONSchemaReader.readSchema(infoClass);
        CustomResourceDefinitionFluent.SpecNested<CustomResourceDefinitionBuilder> builder;

        if (schema != null) {
            removeDefaultValues(schema);
            builder = getCRDBuilder(newPrefix,
                                    entityName,
                                    shortNames,
                                    pluralName)
                    .withNewValidation()
                    .withNewOpenAPIV3SchemaLike(schema)
                    .endOpenAPIV3Schema()
                    .endValidation();
        } else {
            builder = getCRDBuilder(newPrefix,
                                    entityName,
                                    shortNames,
                                    pluralName);
        }
        if (additionalPrinterColumnNames != null && additionalPrinterColumnNames.length > 0) {
            for (int i = 0; i < additionalPrinterColumnNames.length; i++) {
                builder = builder.addNewAdditionalPrinterColumn().withName(additionalPrinterColumnNames[i]).withJSONPath(additionalPrinterColumnPaths[i]).endAdditionalPrinterColumn();
            }
        }
        crdToReturn = builder.endSpec().build();
        try {
            if (schema != null) {
                // https://github.com/fabric8io/kubernetes-client/issues/1486
                crdToReturn.getSpec().getValidation().getOpenAPIV3Schema().setDependencies(null);
            }

            client.customResourceDefinitions().createOrReplace(crdToReturn);
        } catch (KubernetesClientException e) {
            // old version of K8s/openshift -> don't use schema validation
            log.warn("Consider upgrading the {}. Your version doesn't support schema validation for custom resources."
                    , isOpenshift ? "OpenShift" : "Kubernetes");
            crdToReturn = getCRDBuilder(newPrefix,
                                        entityName,
                                        shortNames,
                                        pluralName)
                    .endSpec()
                    .build();
            client.customResourceDefinitions().createOrReplace(crdToReturn);
        }
    }

    // register the new crd for json serialization
    io.fabric8.kubernetes.internal.KubernetesDeserializer.registerCustomKind(newPrefix + "/" + crdToReturn.getSpec().getVersion() + "#" + entityName, InfoClass.class);
    io.fabric8.kubernetes.internal.KubernetesDeserializer.registerCustomKind(newPrefix + "/" + crdToReturn.getSpec().getVersion() + "#" + entityName + "List", CustomResourceList.class);

    return crdToReturn;
}
 
Example #7
Source File: AbstractConnectOperator.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
/**
 * Updates the Status field of the KafkaConnect or KafkaConnector CR. It diffs the desired status against the current status and calls
 * the update only when there is any difference in non-timestamp fields.
 *
 * @param resource The CR of KafkaConnect or KafkaConnector
 * @param reconciliation Reconciliation information
 * @param desiredStatus The KafkaConnectStatus or KafkaConnectorStatus which should be set
 *
 * @return
 */
protected <T extends CustomResource & HasStatus<S>, S extends Status, L extends CustomResourceList<T>, D extends Doneable<T>> Future<Void>
    maybeUpdateStatusCommon(CrdOperator<KubernetesClient, T, L, D> resourceOperator,
                            T resource,
                            Reconciliation reconciliation,
                            S desiredStatus,
                            BiFunction<T, S, T> copyWithStatus) {
    Promise<Void> updateStatusPromise = Promise.promise();

    resourceOperator.getAsync(resource.getMetadata().getNamespace(), resource.getMetadata().getName()).onComplete(getRes -> {
        if (getRes.succeeded()) {
            T fetchedResource = getRes.result();

            if (fetchedResource != null) {
                if ((!(fetchedResource instanceof KafkaConnector))
                        && (!(fetchedResource instanceof KafkaMirrorMaker2))
                        && StatusUtils.isResourceV1alpha1(fetchedResource)) {
                    log.warn("{}: {} {} needs to be upgraded from version {} to 'v1beta1' to use the status field",
                            reconciliation, fetchedResource.getKind(), fetchedResource.getMetadata().getName(), fetchedResource.getApiVersion());
                    updateStatusPromise.complete();
                } else {
                    S currentStatus = fetchedResource.getStatus();

                    StatusDiff ksDiff = new StatusDiff(currentStatus, desiredStatus);

                    if (!ksDiff.isEmpty()) {
                        T resourceWithNewStatus = copyWithStatus.apply(fetchedResource, desiredStatus);

                        resourceOperator.updateStatusAsync(resourceWithNewStatus).onComplete(updateRes -> {
                            if (updateRes.succeeded()) {
                                log.debug("{}: Completed status update", reconciliation);
                                updateStatusPromise.complete();
                            } else {
                                log.error("{}: Failed to update status", reconciliation, updateRes.cause());
                                updateStatusPromise.fail(updateRes.cause());
                            }
                        });
                    } else {
                        log.debug("{}: Status did not change", reconciliation);
                        updateStatusPromise.complete();
                    }
                }
            } else {
                log.error("{}: Current {} resource not found", reconciliation, resource.getKind());
                updateStatusPromise.fail("Current " + resource.getKind() + " resource not found");
            }
        } else {
            log.error("{}: Failed to get the current {} resource and its status", reconciliation, resource.getKind(), getRes.cause());
            updateStatusPromise.fail(getRes.cause());
        }
    });

    return updateStatusPromise.future();
}
 
Example #8
Source File: ResourceManager.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
public static <T extends CustomResource, L extends CustomResourceList<T>, D extends Doneable<T>> void replaceCrdResource(Class<T> crdClass, Class<L> listClass, Class<D> doneableClass, String resourceName, Consumer<T> editor) {
    Resource<T, D> namedResource = Crds.operation(kubeClient().getClient(), crdClass, listClass, doneableClass).inNamespace(kubeClient().getNamespace()).withName(resourceName);
    T resource = namedResource.get();
    editor.accept(resource);
    namedResource.replace(resource);
}