Search in sources :

Example 6 with CustomResource

use of io.fabric8.kubernetes.client.CustomResource in project strimzi by strimzi.

the class Crds method crd.

@SuppressWarnings({ "checkstyle:JavaNCSS" })
private static CustomResourceDefinition crd(Class<? extends CustomResource> cls) {
    String scope, plural, singular, group, kind, listKind;
    List<String> versions;
    CustomResourceSubresourceStatus status = null;
    if (cls.equals(Kafka.class)) {
        scope = Kafka.SCOPE;
        plural = Kafka.RESOURCE_PLURAL;
        singular = Kafka.RESOURCE_SINGULAR;
        group = Kafka.RESOURCE_GROUP;
        kind = Kafka.RESOURCE_KIND;
        listKind = Kafka.RESOURCE_LIST_KIND;
        versions = Kafka.VERSIONS;
        status = new CustomResourceSubresourceStatus();
    } else if (cls.equals(KafkaConnect.class)) {
        scope = KafkaConnect.SCOPE;
        plural = KafkaConnect.RESOURCE_PLURAL;
        singular = KafkaConnect.RESOURCE_SINGULAR;
        group = KafkaConnect.RESOURCE_GROUP;
        kind = KafkaConnect.RESOURCE_KIND;
        listKind = KafkaConnect.RESOURCE_LIST_KIND;
        versions = KafkaConnect.VERSIONS;
        status = new CustomResourceSubresourceStatus();
    } else if (cls.equals(KafkaTopic.class)) {
        scope = KafkaTopic.SCOPE;
        plural = KafkaTopic.RESOURCE_PLURAL;
        singular = KafkaTopic.RESOURCE_SINGULAR;
        group = KafkaTopic.RESOURCE_GROUP;
        kind = KafkaTopic.RESOURCE_KIND;
        listKind = KafkaTopic.RESOURCE_LIST_KIND;
        versions = KafkaTopic.VERSIONS;
    } else if (cls.equals(KafkaUser.class)) {
        scope = KafkaUser.SCOPE;
        plural = KafkaUser.RESOURCE_PLURAL;
        singular = KafkaUser.RESOURCE_SINGULAR;
        group = KafkaUser.RESOURCE_GROUP;
        kind = KafkaUser.RESOURCE_KIND;
        listKind = KafkaUser.RESOURCE_LIST_KIND;
        versions = KafkaUser.VERSIONS;
        status = new CustomResourceSubresourceStatus();
    } else if (cls.equals(KafkaMirrorMaker.class)) {
        scope = KafkaMirrorMaker.SCOPE;
        plural = KafkaMirrorMaker.RESOURCE_PLURAL;
        singular = KafkaMirrorMaker.RESOURCE_SINGULAR;
        group = KafkaMirrorMaker.RESOURCE_GROUP;
        kind = KafkaMirrorMaker.RESOURCE_KIND;
        listKind = KafkaMirrorMaker.RESOURCE_LIST_KIND;
        versions = KafkaMirrorMaker.VERSIONS;
        status = new CustomResourceSubresourceStatus();
    } else if (cls.equals(KafkaBridge.class)) {
        scope = KafkaBridge.SCOPE;
        plural = KafkaBridge.RESOURCE_PLURAL;
        singular = KafkaBridge.RESOURCE_SINGULAR;
        group = KafkaBridge.RESOURCE_GROUP;
        kind = KafkaBridge.RESOURCE_KIND;
        listKind = KafkaBridge.RESOURCE_LIST_KIND;
        versions = KafkaBridge.VERSIONS;
        status = new CustomResourceSubresourceStatus();
    } else if (cls.equals(KafkaConnector.class)) {
        scope = KafkaConnector.SCOPE;
        plural = KafkaConnector.RESOURCE_PLURAL;
        singular = KafkaConnector.RESOURCE_SINGULAR;
        group = KafkaConnector.RESOURCE_GROUP;
        kind = KafkaConnector.RESOURCE_KIND;
        listKind = KafkaConnector.RESOURCE_LIST_KIND;
        versions = KafkaConnector.VERSIONS;
        status = new CustomResourceSubresourceStatus();
    } else if (cls.equals(KafkaMirrorMaker2.class)) {
        scope = KafkaMirrorMaker2.SCOPE;
        plural = KafkaMirrorMaker2.RESOURCE_PLURAL;
        singular = KafkaMirrorMaker2.RESOURCE_SINGULAR;
        group = KafkaMirrorMaker2.RESOURCE_GROUP;
        kind = KafkaMirrorMaker2.RESOURCE_KIND;
        listKind = KafkaMirrorMaker2.RESOURCE_LIST_KIND;
        versions = KafkaMirrorMaker2.VERSIONS;
        status = new CustomResourceSubresourceStatus();
    } else if (cls.equals(KafkaRebalance.class)) {
        scope = KafkaRebalance.SCOPE;
        plural = KafkaRebalance.RESOURCE_PLURAL;
        singular = KafkaRebalance.RESOURCE_SINGULAR;
        group = KafkaRebalance.RESOURCE_GROUP;
        kind = KafkaRebalance.RESOURCE_KIND;
        listKind = KafkaRebalance.RESOURCE_LIST_KIND;
        versions = KafkaRebalance.VERSIONS;
        status = new CustomResourceSubresourceStatus();
    } else if (cls.equals(StrimziPodSet.class)) {
        scope = StrimziPodSet.SCOPE;
        plural = StrimziPodSet.RESOURCE_PLURAL;
        singular = StrimziPodSet.RESOURCE_SINGULAR;
        group = StrimziPodSet.RESOURCE_GROUP;
        kind = StrimziPodSet.RESOURCE_KIND;
        listKind = StrimziPodSet.RESOURCE_LIST_KIND;
        versions = StrimziPodSet.VERSIONS;
        status = new CustomResourceSubresourceStatus();
    } else {
        throw new RuntimeException();
    }
    List<CustomResourceDefinitionVersion> crVersions = new ArrayList<>(versions.size());
    for (String apiVersion : versions) {
        crVersions.add(new CustomResourceDefinitionVersionBuilder().withName(apiVersion).withNewSubresources().withStatus(status).endSubresources().withNewSchema().withNewOpenAPIV3Schema().withType("object").withXKubernetesPreserveUnknownFields(true).endOpenAPIV3Schema().endSchema().withStorage("v1beta2".equals(apiVersion)).withServed(true).build());
    }
    return new CustomResourceDefinitionBuilder().withNewMetadata().withName(plural + "." + group).endMetadata().withNewSpec().withScope(scope).withGroup(group).withVersions(crVersions).withNewNames().withSingular(singular).withPlural(plural).withKind(kind).withListKind(listKind).endNames().endSpec().build();
}
Also used : CustomResourceDefinitionBuilder(io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinitionBuilder) StrimziPodSet(io.strimzi.api.kafka.model.StrimziPodSet) KafkaBridge(io.strimzi.api.kafka.model.KafkaBridge) ArrayList(java.util.ArrayList) KafkaConnect(io.strimzi.api.kafka.model.KafkaConnect) CustomResourceDefinitionVersionBuilder(io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinitionVersionBuilder) CustomResourceSubresourceStatus(io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceSubresourceStatus) KafkaMirrorMaker2(io.strimzi.api.kafka.model.KafkaMirrorMaker2) CustomResourceDefinitionVersion(io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinitionVersion) KafkaUser(io.strimzi.api.kafka.model.KafkaUser)

Example 7 with CustomResource

use of io.fabric8.kubernetes.client.CustomResource in project strimzi-kafka-operator by strimzi.

the class Crds method crd.

@SuppressWarnings({ "checkstyle:JavaNCSS" })
private static CustomResourceDefinition crd(Class<? extends CustomResource> cls) {
    String scope, plural, singular, group, kind, listKind;
    List<String> versions;
    CustomResourceSubresourceStatus status = null;
    if (cls.equals(Kafka.class)) {
        scope = Kafka.SCOPE;
        plural = Kafka.RESOURCE_PLURAL;
        singular = Kafka.RESOURCE_SINGULAR;
        group = Kafka.RESOURCE_GROUP;
        kind = Kafka.RESOURCE_KIND;
        listKind = Kafka.RESOURCE_LIST_KIND;
        versions = Kafka.VERSIONS;
        status = new CustomResourceSubresourceStatus();
    } else if (cls.equals(KafkaConnect.class)) {
        scope = KafkaConnect.SCOPE;
        plural = KafkaConnect.RESOURCE_PLURAL;
        singular = KafkaConnect.RESOURCE_SINGULAR;
        group = KafkaConnect.RESOURCE_GROUP;
        kind = KafkaConnect.RESOURCE_KIND;
        listKind = KafkaConnect.RESOURCE_LIST_KIND;
        versions = KafkaConnect.VERSIONS;
        status = new CustomResourceSubresourceStatus();
    } else if (cls.equals(KafkaTopic.class)) {
        scope = KafkaTopic.SCOPE;
        plural = KafkaTopic.RESOURCE_PLURAL;
        singular = KafkaTopic.RESOURCE_SINGULAR;
        group = KafkaTopic.RESOURCE_GROUP;
        kind = KafkaTopic.RESOURCE_KIND;
        listKind = KafkaTopic.RESOURCE_LIST_KIND;
        versions = KafkaTopic.VERSIONS;
    } else if (cls.equals(KafkaUser.class)) {
        scope = KafkaUser.SCOPE;
        plural = KafkaUser.RESOURCE_PLURAL;
        singular = KafkaUser.RESOURCE_SINGULAR;
        group = KafkaUser.RESOURCE_GROUP;
        kind = KafkaUser.RESOURCE_KIND;
        listKind = KafkaUser.RESOURCE_LIST_KIND;
        versions = KafkaUser.VERSIONS;
        status = new CustomResourceSubresourceStatus();
    } else if (cls.equals(KafkaMirrorMaker.class)) {
        scope = KafkaMirrorMaker.SCOPE;
        plural = KafkaMirrorMaker.RESOURCE_PLURAL;
        singular = KafkaMirrorMaker.RESOURCE_SINGULAR;
        group = KafkaMirrorMaker.RESOURCE_GROUP;
        kind = KafkaMirrorMaker.RESOURCE_KIND;
        listKind = KafkaMirrorMaker.RESOURCE_LIST_KIND;
        versions = KafkaMirrorMaker.VERSIONS;
        status = new CustomResourceSubresourceStatus();
    } else if (cls.equals(KafkaBridge.class)) {
        scope = KafkaBridge.SCOPE;
        plural = KafkaBridge.RESOURCE_PLURAL;
        singular = KafkaBridge.RESOURCE_SINGULAR;
        group = KafkaBridge.RESOURCE_GROUP;
        kind = KafkaBridge.RESOURCE_KIND;
        listKind = KafkaBridge.RESOURCE_LIST_KIND;
        versions = KafkaBridge.VERSIONS;
        status = new CustomResourceSubresourceStatus();
    } else if (cls.equals(KafkaConnector.class)) {
        scope = KafkaConnector.SCOPE;
        plural = KafkaConnector.RESOURCE_PLURAL;
        singular = KafkaConnector.RESOURCE_SINGULAR;
        group = KafkaConnector.RESOURCE_GROUP;
        kind = KafkaConnector.RESOURCE_KIND;
        listKind = KafkaConnector.RESOURCE_LIST_KIND;
        versions = KafkaConnector.VERSIONS;
        status = new CustomResourceSubresourceStatus();
    } else if (cls.equals(KafkaMirrorMaker2.class)) {
        scope = KafkaMirrorMaker2.SCOPE;
        plural = KafkaMirrorMaker2.RESOURCE_PLURAL;
        singular = KafkaMirrorMaker2.RESOURCE_SINGULAR;
        group = KafkaMirrorMaker2.RESOURCE_GROUP;
        kind = KafkaMirrorMaker2.RESOURCE_KIND;
        listKind = KafkaMirrorMaker2.RESOURCE_LIST_KIND;
        versions = KafkaMirrorMaker2.VERSIONS;
        status = new CustomResourceSubresourceStatus();
    } else if (cls.equals(KafkaRebalance.class)) {
        scope = KafkaRebalance.SCOPE;
        plural = KafkaRebalance.RESOURCE_PLURAL;
        singular = KafkaRebalance.RESOURCE_SINGULAR;
        group = KafkaRebalance.RESOURCE_GROUP;
        kind = KafkaRebalance.RESOURCE_KIND;
        listKind = KafkaRebalance.RESOURCE_LIST_KIND;
        versions = KafkaRebalance.VERSIONS;
        status = new CustomResourceSubresourceStatus();
    } else if (cls.equals(StrimziPodSet.class)) {
        scope = StrimziPodSet.SCOPE;
        plural = StrimziPodSet.RESOURCE_PLURAL;
        singular = StrimziPodSet.RESOURCE_SINGULAR;
        group = StrimziPodSet.RESOURCE_GROUP;
        kind = StrimziPodSet.RESOURCE_KIND;
        listKind = StrimziPodSet.RESOURCE_LIST_KIND;
        versions = StrimziPodSet.VERSIONS;
        status = new CustomResourceSubresourceStatus();
    } else {
        throw new RuntimeException();
    }
    List<CustomResourceDefinitionVersion> crVersions = new ArrayList<>(versions.size());
    for (String apiVersion : versions) {
        crVersions.add(new CustomResourceDefinitionVersionBuilder().withName(apiVersion).withNewSubresources().withStatus(status).endSubresources().withNewSchema().withNewOpenAPIV3Schema().withType("object").withXKubernetesPreserveUnknownFields(true).endOpenAPIV3Schema().endSchema().withStorage("v1beta2".equals(apiVersion)).withServed(true).build());
    }
    return new CustomResourceDefinitionBuilder().withNewMetadata().withName(plural + "." + group).endMetadata().withNewSpec().withScope(scope).withGroup(group).withVersions(crVersions).withNewNames().withSingular(singular).withPlural(plural).withKind(kind).withListKind(listKind).endNames().endSpec().build();
}
Also used : CustomResourceDefinitionBuilder(io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinitionBuilder) StrimziPodSet(io.strimzi.api.kafka.model.StrimziPodSet) KafkaBridge(io.strimzi.api.kafka.model.KafkaBridge) ArrayList(java.util.ArrayList) KafkaConnect(io.strimzi.api.kafka.model.KafkaConnect) CustomResourceDefinitionVersionBuilder(io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinitionVersionBuilder) CustomResourceSubresourceStatus(io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceSubresourceStatus) KafkaMirrorMaker2(io.strimzi.api.kafka.model.KafkaMirrorMaker2) CustomResourceDefinitionVersion(io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinitionVersion) KafkaUser(io.strimzi.api.kafka.model.KafkaUser)

Example 8 with CustomResource

use of io.fabric8.kubernetes.client.CustomResource in project strimzi-kafka-operator by strimzi.

the class AbstractConnectOperator method createConnectorWatch.

/**
 * Create a watch on {@code KafkaConnector} in the given {@code namespace}.
 * The watcher will:
 * <ul>
 * <li>{@linkplain #reconcileConnectors(Reconciliation, CustomResource, KafkaConnectStatus, boolean, String, OrderedProperties)} on the KafkaConnect
 * identified by {@code KafkaConnector.metadata.labels[strimzi.io/cluster]}.</li>
 * <li>The {@code KafkaConnector} status is updated with the result.</li>
 * </ul>
 * @param connectOperator The operator for {@code KafkaConnect}.
 * @param watchNamespaceOrWildcard The namespace to watch.
 * @param selectorLabels Selector labels for filtering the custom resources
 *
 * @return A future which completes when the watch has been set up.
 */
public static Future<Void> createConnectorWatch(AbstractConnectOperator<KubernetesClient, KafkaConnect, KafkaConnectList, Resource<KafkaConnect>, KafkaConnectSpec, KafkaConnectStatus> connectOperator, String watchNamespaceOrWildcard, Labels selectorLabels) {
    Optional<LabelSelector> selector = (selectorLabels == null || selectorLabels.toMap().isEmpty()) ? Optional.empty() : Optional.of(new LabelSelector(null, selectorLabels.toMap()));
    return Util.async(connectOperator.vertx, () -> {
        connectOperator.connectorOperator.watch(watchNamespaceOrWildcard, new Watcher<KafkaConnector>() {

            @Override
            public void eventReceived(Action action, KafkaConnector kafkaConnector) {
                String connectorName = kafkaConnector.getMetadata().getName();
                String connectorNamespace = kafkaConnector.getMetadata().getNamespace();
                String connectorKind = kafkaConnector.getKind();
                String connectName = kafkaConnector.getMetadata().getLabels() == null ? null : kafkaConnector.getMetadata().getLabels().get(Labels.STRIMZI_CLUSTER_LABEL);
                String connectNamespace = connectorNamespace;
                switch(action) {
                    case ADDED:
                    case DELETED:
                    case MODIFIED:
                        if (connectName != null) {
                            // Check whether a KafkaConnect exists
                            connectOperator.resourceOperator.getAsync(connectNamespace, connectName).compose(connect -> {
                                KafkaConnectApi apiClient = connectOperator.connectClientProvider.apply(connectOperator.vertx);
                                if (connect == null) {
                                    Reconciliation r = new Reconciliation("connector-watch", connectOperator.kind(), kafkaConnector.getMetadata().getNamespace(), connectName);
                                    updateStatus(r, noConnectCluster(connectNamespace, connectName), kafkaConnector, connectOperator.connectorOperator);
                                    LOGGER.infoCr(r, "{} {} in namespace {} was {}, but Connect cluster {} does not exist", connectorKind, connectorName, connectorNamespace, action, connectName);
                                    return Future.succeededFuture();
                                } else {
                                    // grab the lock and call reconcileConnectors()
                                    // (i.e. short circuit doing a whole KafkaConnect reconciliation).
                                    Reconciliation reconciliation = new Reconciliation("connector-watch", connectOperator.kind(), kafkaConnector.getMetadata().getNamespace(), connectName);
                                    if (!Util.matchesSelector(selector, connect)) {
                                        LOGGER.debugCr(reconciliation, "{} {} in namespace {} was {}, but Connect cluster {} does not match label selector {} and will be ignored", connectorKind, connectorName, connectorNamespace, action, connectName, selectorLabels);
                                        return Future.succeededFuture();
                                    } else if (connect.getSpec() != null && connect.getSpec().getReplicas() == 0) {
                                        LOGGER.infoCr(reconciliation, "{} {} in namespace {} was {}, but Connect cluster {} has 0 replicas", connectorKind, connectorName, connectorNamespace, action, connectName);
                                        updateStatus(reconciliation, zeroReplicas(connectNamespace, connectName), kafkaConnector, connectOperator.connectorOperator);
                                        return Future.succeededFuture();
                                    } else {
                                        LOGGER.infoCr(reconciliation, "{} {} in namespace {} was {}", connectorKind, connectorName, connectorNamespace, action);
                                        return connectOperator.withLock(reconciliation, LOCK_TIMEOUT_MS, () -> connectOperator.reconcileConnectorAndHandleResult(reconciliation, KafkaConnectResources.qualifiedServiceName(connectName, connectNamespace), apiClient, isUseResources(connect), kafkaConnector.getMetadata().getName(), action == Action.DELETED ? null : kafkaConnector).compose(reconcileResult -> {
                                            LOGGER.infoCr(reconciliation, "reconciled");
                                            return Future.succeededFuture(reconcileResult);
                                        }));
                                    }
                                }
                            });
                        } else {
                            updateStatus(new Reconciliation("connector-watch", connectOperator.kind(), kafkaConnector.getMetadata().getNamespace(), null), new InvalidResourceException("Resource lacks label '" + Labels.STRIMZI_CLUSTER_LABEL + "': No connect cluster in which to create this connector."), kafkaConnector, connectOperator.connectorOperator);
                        }
                        break;
                    case ERROR:
                        LOGGER.errorCr(new Reconciliation("connector-watch", connectorKind, connectName, connectorNamespace), "Failed {} {} in namespace {} ", connectorKind, connectorName, connectorNamespace);
                        break;
                    default:
                        LOGGER.errorCr(new Reconciliation("connector-watch", connectorKind, connectName, connectorNamespace), "Unknown action: {} {} in namespace {}", connectorKind, connectorName, connectorNamespace);
                }
            }

            @Override
            public void onClose(WatcherException e) {
                if (e != null) {
                    throw new KubernetesClientException(e.getMessage());
                }
            }
        });
        return null;
    });
}
Also used : KafkaConnectorList(io.strimzi.api.kafka.KafkaConnectorList) OrderedProperties(io.strimzi.operator.common.model.OrderedProperties) LabelSelector(io.fabric8.kubernetes.api.model.LabelSelector) CustomResourceList(io.fabric8.kubernetes.client.CustomResourceList) BiFunction(java.util.function.BiFunction) Watcher(io.fabric8.kubernetes.client.Watcher) Annotations(io.strimzi.operator.common.Annotations) KafkaConnector(io.strimzi.api.kafka.model.KafkaConnector) ClusterRoleBindingOperator(io.strimzi.operator.common.operator.resource.ClusterRoleBindingOperator) ResourceVisitor(io.strimzi.operator.common.model.ResourceVisitor) Resource(io.fabric8.kubernetes.client.dsl.Resource) PodDisruptionBudgetV1Beta1Operator(io.strimzi.operator.common.operator.resource.PodDisruptionBudgetV1Beta1Operator) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) KafkaConnectStatus(io.strimzi.api.kafka.model.status.KafkaConnectStatus) Map(java.util.Map) KafkaConnectorSpec(io.strimzi.api.kafka.model.KafkaConnectorSpec) ANNO_STRIMZI_IO_RESTART_TASK(io.strimzi.operator.common.Annotations.ANNO_STRIMZI_IO_RESTART_TASK) ResourceOperatorSupplier(io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier) JsonObject(io.vertx.core.json.JsonObject) Operator(io.strimzi.operator.common.Operator) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) Counter(io.micrometer.core.instrument.Counter) AbstractOperator(io.strimzi.operator.common.AbstractOperator) StatusUtils(io.strimzi.operator.common.operator.resource.StatusUtils) KafkaConnect(io.strimzi.api.kafka.model.KafkaConnect) LabelSelectorBuilder(io.fabric8.kubernetes.api.model.LabelSelectorBuilder) ConnectTimeoutException(io.netty.channel.ConnectTimeoutException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ValidationVisitor(io.strimzi.operator.common.model.ValidationVisitor) SecretOperator(io.strimzi.operator.common.operator.resource.SecretOperator) Set(java.util.Set) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) Future(io.vertx.core.Future) Collectors(java.util.stream.Collectors) NoSuchResourceException(io.strimzi.operator.cluster.model.NoSuchResourceException) KafkaMirrorMaker2(io.strimzi.api.kafka.model.KafkaMirrorMaker2) KafkaConnectCluster(io.strimzi.operator.cluster.model.KafkaConnectCluster) List(java.util.List) ANNO_STRIMZI_IO_RESTART(io.strimzi.operator.common.Annotations.ANNO_STRIMZI_IO_RESTART) Labels(io.strimzi.operator.common.model.Labels) Stream(java.util.stream.Stream) KafkaConnectorStatus(io.strimzi.api.kafka.model.status.KafkaConnectorStatus) Secret(io.fabric8.kubernetes.api.model.Secret) Optional(java.util.Optional) Condition(io.strimzi.api.kafka.model.status.Condition) KafkaConnectList(io.strimzi.api.kafka.KafkaConnectList) PodDisruptionBudgetOperator(io.strimzi.operator.common.operator.resource.PodDisruptionBudgetOperator) PlatformFeaturesAvailability(io.strimzi.operator.PlatformFeaturesAvailability) ClusterOperatorConfig(io.strimzi.operator.cluster.ClusterOperatorConfig) CustomResource(io.fabric8.kubernetes.client.CustomResource) BackOff(io.strimzi.operator.common.BackOff) NetworkPolicyOperator(io.strimzi.operator.common.operator.resource.NetworkPolicyOperator) LocalObjectReference(io.fabric8.kubernetes.api.model.LocalObjectReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) WatcherException(io.fabric8.kubernetes.client.WatcherException) ServiceOperator(io.strimzi.operator.common.operator.resource.ServiceOperator) CompositeFuture(io.vertx.core.CompositeFuture) Timer(io.micrometer.core.instrument.Timer) ServiceAccountOperator(io.strimzi.operator.common.operator.resource.ServiceAccountOperator) ConfigMapOperator(io.strimzi.operator.common.operator.resource.ConfigMapOperator) CrdOperator(io.strimzi.operator.common.operator.resource.CrdOperator) Status(io.strimzi.api.kafka.model.status.Status) ReconcileResult(io.strimzi.operator.common.operator.resource.ReconcileResult) LinkedHashSet(java.util.LinkedHashSet) KafkaConnectorBuilder(io.strimzi.api.kafka.model.KafkaConnectorBuilder) KafkaConnectorConfiguration(io.strimzi.operator.cluster.model.KafkaConnectorConfiguration) ReconciliationLogger(io.strimzi.operator.common.ReconciliationLogger) Collections.emptyMap(java.util.Collections.emptyMap) InvalidResourceException(io.strimzi.operator.cluster.model.InvalidResourceException) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) AbstractKafkaConnectSpec(io.strimzi.api.kafka.model.AbstractKafkaConnectSpec) ConnectorPlugin(io.strimzi.api.kafka.model.connect.ConnectorPlugin) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) Reconciliation(io.strimzi.operator.common.Reconciliation) ImagePullPolicy(io.strimzi.operator.cluster.model.ImagePullPolicy) StatusDiff(io.strimzi.operator.cluster.model.StatusDiff) Util(io.strimzi.operator.common.Util) TreeMap(java.util.TreeMap) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) NetworkPolicy(io.fabric8.kubernetes.api.model.networking.v1.NetworkPolicy) ServiceAccount(io.fabric8.kubernetes.api.model.ServiceAccount) KafkaConnectSpec(io.strimzi.api.kafka.model.KafkaConnectSpec) Collections(java.util.Collections) KafkaConnectResources(io.strimzi.api.kafka.model.KafkaConnectResources) LabelSelector(io.fabric8.kubernetes.api.model.LabelSelector) WatcherException(io.fabric8.kubernetes.client.WatcherException) InvalidResourceException(io.strimzi.operator.cluster.model.InvalidResourceException) Reconciliation(io.strimzi.operator.common.Reconciliation) KafkaConnector(io.strimzi.api.kafka.model.KafkaConnector) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 9 with CustomResource

use of io.fabric8.kubernetes.client.CustomResource in project strimzi-kafka-operator by strimzi.

the class CrdGenerator method buildSpec.

@SuppressWarnings("NPathComplexity")
private ObjectNode buildSpec(ApiVersion crdApiVersion, Crd.Spec crd, Class<? extends CustomResource> crdClass) {
    checkKubeVersionsSupportCrdVersion(crdApiVersion);
    ObjectNode result = nf.objectNode();
    result.put("group", crd.group());
    ArrayNode versions = nf.arrayNode();
    // Kube apiserver with CRD v1beta1 is picky about only using per-version subresources, schemas and printercolumns
    // if they actually differ across the versions. If they're the same, it insists these things are
    // declared top level
    // With CRD v1 they have to be per-version :face-with-rolling-eyes:
    Map<ApiVersion, ObjectNode> subresources = buildSubresources(crd);
    boolean perVersionSubResources = needsPerVersion("subresources", subresources);
    Map<ApiVersion, ObjectNode> schemas = buildSchemas(crd, crdClass);
    boolean perVersionSchemas = needsPerVersion("schemas", schemas);
    Map<ApiVersion, ArrayNode> printerColumns = buildPrinterColumns(crd);
    boolean perVersionPrinterColumns = needsPerVersion("additionalPrinterColumns", printerColumns);
    result.set("names", buildNames(crd.names()));
    result.put("scope", crd.scope());
    if (!perVersionPrinterColumns) {
        ArrayNode cols = printerColumns.values().iterator().next();
        if (!cols.isEmpty()) {
            result.set("additionalPrinterColumns", cols);
        }
    }
    if (!perVersionSubResources) {
        ObjectNode subresource = subresources.values().iterator().next();
        if (!subresource.isEmpty()) {
            result.set("subresources", subresource);
        }
    }
    if (conversionStrategy instanceof WebhookConversionStrategy) {
        // "Webhook": must be None if spec.preserveUnknownFields is true
        result.put("preserveUnknownFields", false);
    }
    result.set("conversion", buildConversion(crdApiVersion));
    for (Crd.Spec.Version version : crd.versions()) {
        ApiVersion crApiVersion = ApiVersion.parse(version.name());
        if (!shouldIncludeVersion(crApiVersion)) {
            continue;
        }
        ObjectNode versionNode = versions.addObject();
        versionNode.put("name", crApiVersion.toString());
        versionNode.put("served", servedVersion != null ? servedVersion.contains(crApiVersion) : version.served());
        versionNode.put("storage", storageVersion != null ? crApiVersion.equals(storageVersion) : version.storage());
        if (perVersionSubResources) {
            ObjectNode subresourcesForVersion = subresources.get(crApiVersion);
            if (!subresourcesForVersion.isEmpty()) {
                versionNode.set("subresources", subresourcesForVersion);
            }
        }
        if (perVersionPrinterColumns) {
            ArrayNode cols = printerColumns.get(crApiVersion);
            if (!cols.isEmpty()) {
                versionNode.set("additionalPrinterColumns", cols);
            }
        }
        if (perVersionSchemas) {
            versionNode.set("schema", schemas.get(crApiVersion));
        }
    }
    result.set("versions", versions);
    if (crdApiVersion.compareTo(V1) < 0 && targetKubeVersions.intersects(KubeVersion.parseRange("1.11-1.15"))) {
        result.put("version", Arrays.stream(crd.versions()).map(v -> ApiVersion.parse(v.name())).filter(this::shouldIncludeVersion).findFirst().map(ApiVersion::toString).orElseThrow());
    }
    if (!perVersionSchemas) {
        result.set("validation", schemas.values().iterator().next());
    }
    return result;
}
Also used : JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) Arrays(java.util.Arrays) YAMLGenerator(com.fasterxml.jackson.dataformat.yaml.YAMLGenerator) VersionRange(io.strimzi.api.annotations.VersionRange) Crd(io.strimzi.crdgenerator.annotations.Crd) Alternative(io.strimzi.crdgenerator.annotations.Alternative) Example(io.strimzi.crdgenerator.annotations.Example) YAMLMapper(com.fasterxml.jackson.dataformat.yaml.YAMLMapper) Locale(java.util.Locale) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) Property.properties(io.strimzi.crdgenerator.Property.properties) JsonNode(com.fasterxml.jackson.databind.JsonNode) Method(java.lang.reflect.Method) Collections.emptyList(java.util.Collections.emptyList) Collection(java.util.Collection) Property.hasAnyGetterAndAnySetter(io.strimzi.crdgenerator.Property.hasAnyGetterAndAnySetter) Pattern(io.strimzi.crdgenerator.annotations.Pattern) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) TextNode(com.fasterxml.jackson.databind.node.TextNode) Objects(java.util.Objects) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) MinimumItems(io.strimzi.crdgenerator.annotations.MinimumItems) Base64(java.util.Base64) List(java.util.List) JsonTypeInfo(com.fasterxml.jackson.annotation.JsonTypeInfo) Type(io.strimzi.crdgenerator.annotations.Type) JsonNodeFactory(com.fasterxml.jackson.databind.node.JsonNodeFactory) Modifier(java.lang.reflect.Modifier) Writer(java.io.Writer) Annotation(java.lang.annotation.Annotation) Minimum(io.strimzi.crdgenerator.annotations.Minimum) Property.sortedProperties(io.strimzi.crdgenerator.Property.sortedProperties) ApiVersion(io.strimzi.api.annotations.ApiVersion) Maximum(io.strimzi.crdgenerator.annotations.Maximum) AnnotatedElement(java.lang.reflect.AnnotatedElement) CustomResource(io.fabric8.kubernetes.client.CustomResource) JsonPropertyOrder(com.fasterxml.jackson.annotation.JsonPropertyOrder) HashMap(java.util.HashMap) Function(java.util.function.Function) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) KubeVersion(io.strimzi.api.annotations.KubeVersion) OutputStreamWriter(java.io.OutputStreamWriter) ContainerNode(com.fasterxml.jackson.databind.node.ContainerNode) Property.subtypes(io.strimzi.crdgenerator.Property.subtypes) Modifier.isAbstract(java.lang.reflect.Modifier.isAbstract) Collections.emptyMap(java.util.Collections.emptyMap) Files(java.nio.file.Files) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) Description(io.strimzi.crdgenerator.annotations.Description) Integer.parseInt(java.lang.Integer.parseInt) File(java.io.File) V1(io.strimzi.api.annotations.ApiVersion.V1) ParameterizedType(java.lang.reflect.ParameterizedType) TreeMap(java.util.TreeMap) OneOf(io.strimzi.crdgenerator.annotations.OneOf) JsonInclude(com.fasterxml.jackson.annotation.JsonInclude) Alternation(io.strimzi.crdgenerator.annotations.Alternation) ApiVersion(io.strimzi.api.annotations.ApiVersion) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode)

Example 10 with CustomResource

use of io.fabric8.kubernetes.client.CustomResource in project strimzi-kafka-operator by strimzi.

the class DocGenerator method main.

public static void main(String[] args) throws IOException, ClassNotFoundException {
    Linker linker = null;
    File out = null;
    List<Class<? extends CustomResource>> classes = new ArrayList<>();
    outer: for (int i = 0; i < args.length; i++) {
        String arg = args[i];
        if (arg.startsWith("-")) {
            if ("--linker".equals(arg)) {
                String className = args[++i];
                Class<? extends Linker> linkerClass = classInherits(Class.forName(className), Linker.class);
                if (linkerClass != null) {
                    try {
                        linker = linkerClass.getConstructor(String.class).newInstance(args[++i]);
                    } catch (ReflectiveOperationException e) {
                        throw new RuntimeException("--linker option can't be handled", e);
                    }
                } else {
                    System.err.println(className + " is not a subclass of " + Linker.class.getName());
                }
            } else {
                throw new RuntimeException("Unsupported option " + arg);
            }
        } else {
            if (out == null) {
                out = new File(arg);
            } else {
                String className = arg;
                Class<? extends CustomResource> cls = classInherits(Class.forName(className), CustomResource.class);
                if (cls != null) {
                    classes.add(cls);
                } else {
                    System.err.println(className + " is not a subclass of " + CustomResource.class.getName());
                }
            }
        }
    }
    ApiVersion crApiVersion = ApiVersion.V1BETA2;
    try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(out), StandardCharsets.UTF_8)) {
        writer.append("// This file is auto-generated by ").append(DocGenerator.class.getName()).append(".").append(NL);
        writer.append("// To change this documentation you need to edit the Java sources.").append(NL);
        writer.append(NL);
        DocGenerator dg = new DocGenerator(crApiVersion, 3, classes, writer, linker);
        for (Class<? extends CustomResource> c : classes) {
            dg.generate(c);
        }
        if (dg.numErrors > 0) {
            System.err.println("There were " + dg.numErrors + " errors");
            System.exit(1);
        }
    }
}
Also used : ApiVersion(io.strimzi.api.annotations.ApiVersion) CustomResource(io.fabric8.kubernetes.client.CustomResource) ArrayList(java.util.ArrayList) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) DescriptionFile(io.strimzi.crdgenerator.annotations.DescriptionFile) File(java.io.File)

Aggregations

CustomResource (io.fabric8.kubernetes.client.CustomResource)22 Collections.emptyMap (java.util.Collections.emptyMap)16 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)15 Condition (io.strimzi.api.kafka.model.status.Condition)14 HashSet (java.util.HashSet)14 ObjectMeta (io.fabric8.kubernetes.api.model.ObjectMeta)13 Group (io.fabric8.kubernetes.model.annotation.Group)12 Version (io.fabric8.kubernetes.model.annotation.Version)12 Spec (io.strimzi.api.kafka.model.Spec)12 Status (io.strimzi.api.kafka.model.status.Status)12 Labels (io.strimzi.operator.common.model.Labels)12 AbstractWatchableStatusedResourceOperator (io.strimzi.operator.common.operator.resource.AbstractWatchableStatusedResourceOperator)12 Future (io.vertx.core.Future)12 Promise (io.vertx.core.Promise)12 Vertx (io.vertx.core.Vertx)12 Collections (java.util.Collections)12 Set (java.util.Set)12 MixedOperation (io.fabric8.kubernetes.client.dsl.MixedOperation)10 MeterRegistry (io.micrometer.core.instrument.MeterRegistry)10 Tag (io.micrometer.core.instrument.Tag)10