repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/ChildTestResource2.java | integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/ChildTestResource2.java | package io.quarkiverse.operatorsdk.it;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Version;
@Group("example.com")
@Version("v2")
public class ChildTestResource2 extends TestResource {
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/IgnoredByAnnotationReconciler.java | integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/IgnoredByAnnotationReconciler.java | package io.quarkiverse.operatorsdk.it;
import io.javaoperatorsdk.operator.api.reconciler.Context;
import io.javaoperatorsdk.operator.api.reconciler.Ignore;
import io.javaoperatorsdk.operator.api.reconciler.Reconciler;
import io.javaoperatorsdk.operator.api.reconciler.UpdateControl;
@Ignore
public class IgnoredByAnnotationReconciler implements Reconciler<TestResource> {
@Override
public UpdateControl<TestResource> reconcile(TestResource testResource, Context context) {
return UpdateControl.noUpdate();
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/DependentDefiningReconciler.java | integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/DependentDefiningReconciler.java | package io.quarkiverse.operatorsdk.it;
import io.fabric8.kubernetes.api.model.ConfigMap;
import io.javaoperatorsdk.operator.api.reconciler.Context;
import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration;
import io.javaoperatorsdk.operator.api.reconciler.Reconciler;
import io.javaoperatorsdk.operator.api.reconciler.UpdateControl;
import io.javaoperatorsdk.operator.api.reconciler.Workflow;
import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent;
// Note that this reconciler implementation and its dependents are not meant to be realistic but
// rather exercise some of the features
@Workflow(dependents = {
@Dependent(type = ReadOnlyDependentResource.class, name = ReadOnlyDependentResource.NAME, readyPostcondition = ReadOnlyDependentResource.ReadOnlyReadyCondition.class),
@Dependent(type = CRUDDependentResource.class, name = "crud", dependsOn = "read-only")
})
@ControllerConfiguration(name = DependentDefiningReconciler.NAME)
public class DependentDefiningReconciler implements Reconciler<ConfigMap> {
public static final String NAME = "dependent";
@Override
public UpdateControl<ConfigMap> reconcile(ConfigMap configMap, Context context) {
return UpdateControl.noUpdate();
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/AnnotatedDependentReconciler.java | integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/AnnotatedDependentReconciler.java | package io.quarkiverse.operatorsdk.it;
import static io.quarkiverse.operatorsdk.it.AnnotatedDependentReconciler.NAME;
import io.fabric8.kubernetes.api.model.Service;
import io.javaoperatorsdk.operator.api.reconciler.Context;
import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration;
import io.javaoperatorsdk.operator.api.reconciler.Reconciler;
import io.javaoperatorsdk.operator.api.reconciler.UpdateControl;
import io.javaoperatorsdk.operator.api.reconciler.Workflow;
import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent;
@Workflow(dependents = @Dependent(type = AnnotatedDependentResource.class))
@ControllerConfiguration(name = NAME)
public class AnnotatedDependentReconciler implements Reconciler<Service> {
public static final String NAME = "annotated-dependent";
@Override
public UpdateControl<Service> reconcile(Service service, Context<Service> context)
throws Exception {
return null;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/CustomRateLimiter.java | integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/CustomRateLimiter.java | package io.quarkiverse.operatorsdk.it;
import java.time.Duration;
import java.util.Optional;
import io.javaoperatorsdk.operator.api.config.AnnotationConfigurable;
import io.javaoperatorsdk.operator.processing.event.rate.RateLimiter;
@SuppressWarnings("rawtypes")
public class CustomRateLimiter implements RateLimiter, AnnotationConfigurable<CustomRateConfiguration> {
private int value;
@Override
public Optional<Duration> isLimited(RateLimitState rateLimitState) {
return Optional.empty();
}
@Override
public RateLimitState initState() {
return null;
}
@Override
public void initFrom(CustomRateConfiguration customRateConfiguration) {
this.value = customRateConfiguration.value();
}
@SuppressWarnings("unused")
// make it visible for JSON serialization
public int getValue() {
return value;
}
/*
* Needed to allow proper byte recording as custom implementation configuration is now done at build time, thus requiring
* configuration results to be recorded to be replayed at runtime.
*/
@SuppressWarnings("unused")
public void setValue(int value) {
this.value = value;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/ChildTestResource.java | integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/ChildTestResource.java | package io.quarkiverse.operatorsdk.it;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Version;
@Group("example.com")
@Version("v1")
public class ChildTestResource extends TestResource {
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/EmptyCR.java | integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/EmptyCR.java | package io.quarkiverse.operatorsdk.it;
import io.fabric8.kubernetes.client.CustomResource;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Version;
import io.quarkiverse.operatorsdk.it.EmptyCR.EmptySpec;
@Group("josdk.quarkiverse.io")
@Version("v1alpha1")
public class EmptyCR extends CustomResource<EmptySpec, Void> {
static class EmptySpec {
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/Keycloak.java | integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/Keycloak.java | package io.quarkiverse.operatorsdk.it;
import io.fabric8.kubernetes.client.CustomResource;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Version;
@Group("org.keycloak")
@Version("v1alpha2")
public class Keycloak extends CustomResource<Void, Void> {
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/CRUDDependentResource.java | integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/CRUDDependentResource.java | package io.quarkiverse.operatorsdk.it;
import io.fabric8.kubernetes.api.model.ConfigMap;
import io.javaoperatorsdk.operator.api.config.informer.Informer;
import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource;
import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent;
import io.javaoperatorsdk.operator.processing.event.source.filter.OnAddFilter;
import io.quarkiverse.operatorsdk.it.CRUDDependentResource.TestOnAddFilter;
@KubernetesDependent(informer = @Informer(labelSelector = CRUDDependentResource.LABEL_SELECTOR, onAddFilter = TestOnAddFilter.class))
public class CRUDDependentResource extends CRUDKubernetesDependentResource<ConfigMap, ConfigMap> {
public static class TestOnAddFilter implements OnAddFilter<ConfigMap> {
@Override
public boolean accept(ConfigMap configMap) {
return true;
}
}
public static final String LABEL_SELECTOR = "environment=production,foo=bar";
public CRUDDependentResource() {
super(ConfigMap.class);
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/OperatorSDKResource.java | integration-tests/basic/src/main/java/io/quarkiverse/operatorsdk/it/OperatorSDKResource.java | package io.quarkiverse.operatorsdk.it;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.client.informers.cache.ItemStore;
import io.javaoperatorsdk.operator.api.config.ControllerConfiguration;
import io.javaoperatorsdk.operator.api.config.Version;
import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceSpec;
import io.javaoperatorsdk.operator.api.config.workflow.WorkflowSpec;
import io.javaoperatorsdk.operator.api.reconciler.Reconciler;
import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResourceConfig;
import io.javaoperatorsdk.operator.processing.dependent.workflow.ManagedWorkflow;
import io.javaoperatorsdk.operator.processing.event.rate.RateLimiter;
import io.javaoperatorsdk.operator.processing.retry.Retry;
import io.quarkiverse.operatorsdk.runtime.DependentResourceSpecMetadata;
import io.quarkiverse.operatorsdk.runtime.QuarkusConfigurationService;
import io.quarkiverse.operatorsdk.runtime.QuarkusControllerConfiguration;
import io.quarkus.runtime.annotations.RegisterForReflection;
@SuppressWarnings("unused")
@Path("/operator")
public class OperatorSDKResource {
@Inject
Instance<Reconciler<? extends HasMetadata>> controllers;
@Inject
QuarkusConfigurationService configurationService;
@GET
@Path("config")
public JSONConfiguration config() {
return new JSONConfiguration(configurationService);
}
@GET
@Path("{name}")
public boolean exists(@PathParam("name") String name) {
return configurationService.getKnownReconcilerNames().contains(name);
}
@GET
@Path("controllers")
@Produces("application/json")
public Set<String> getControllerNames() {
return config().getKnownControllerNames();
}
@GET
@Path("{name}/config")
public JSONControllerConfiguration getConfig(@PathParam("name") String name) {
return getControllerConfigurationByName(name)
.map(JSONControllerConfiguration::new)
.orElse(null);
}
private Optional<? extends QuarkusControllerConfiguration<? extends HasMetadata>> getControllerConfigurationByName(
String name) {
return controllers.stream()
.map(c -> configurationService.getConfigurationFor(c))
.filter(c -> c.getName().equals(name))
.findFirst();
}
@GET
@Path("{name}/workflow")
public JSONWorkflow getWorkflow(@PathParam("name") String name) {
return new JSONWorkflow(configurationService.workflowByName(name));
}
@GET
@Path("{name}/dependents/{dependent}")
public JSONKubernetesResourceConfig getDependentConfig(@PathParam("name") String name,
@PathParam("dependent") String dependent) {
final DependentResourceSpecMetadata<?, ?, ?> dr = configurationService.getDependentByName(name, dependent);
if (dr == null) {
return null;
}
return dr.getConfiguration()
.filter(KubernetesDependentResourceConfig.class::isInstance)
.map(KubernetesDependentResourceConfig.class::cast)
.map(JSONKubernetesResourceConfig::new)
.orElse(null);
}
static class JSONConfiguration {
private final QuarkusConfigurationService conf;
public JSONConfiguration(QuarkusConfigurationService conf) {
this.conf = conf;
}
public Set<String> getKnownControllerNames() {
return conf.getKnownReconcilerNames();
}
public Version getVersion() {
return conf.getVersion();
}
@JsonProperty("validate")
public boolean validate() {
return conf.checkCRDAndValidateLocalModel();
}
@JsonProperty("maxThreads")
public int concurrentReconciliationThreads() {
return conf.concurrentReconciliationThreads();
}
@JsonProperty("timeout")
public int timeout() {
return conf.getTerminationTimeoutSeconds();
}
@JsonProperty("applyCRDs")
public boolean apply() {
return conf.getCRDGenerationInfo().isApplyCRDs();
}
@JsonProperty("metrics")
public String metrics() {
return conf.getMetrics().getClass().getName();
}
@JsonProperty("registryBound")
public boolean registryBound() {
final var metrics = conf.getMetrics();
return metrics instanceof TestMetrics && ((TestMetrics) metrics).isRegistryBound();
}
@JsonProperty("leaderConfig")
public String leaderConfig() {
return conf.getLeaderElectionConfiguration().map(lec -> lec.getClass().getName()).orElse(null);
}
@JsonProperty("useSSA")
public boolean useSSA() {
return conf.ssaBasedCreateUpdateMatchForDependentResources();
}
}
static class JSONControllerConfiguration {
private final ControllerConfiguration<?> conf;
public JSONControllerConfiguration(ControllerConfiguration<?> conf) {
this.conf = conf;
}
public String getName() {
return conf.getName();
}
@JsonProperty("crdName")
public String getCRDName() {
return conf.getResourceTypeName();
}
public String getFinalizer() {
return conf.getFinalizerName();
}
public boolean isGenerationAware() {
return conf.isGenerationAware();
}
public String getCustomResourceClass() {
return conf.getResourceClass().getCanonicalName();
}
public String getAssociatedControllerClassName() {
return conf.getAssociatedReconcilerClassName();
}
public String[] getNamespaces() {
return conf.getInformerConfig().getNamespaces().toArray(new String[0]);
}
@JsonProperty("watchAllNamespaces")
public boolean watchAllNamespaces() {
return conf.getInformerConfig().watchAllNamespaces();
}
@JsonProperty("watchCurrentNamespace")
public boolean watchCurrentNamespace() {
return conf.getInformerConfig().watchCurrentNamespace();
}
public Retry getRetry() {
return conf.getRetry();
}
public String getLabelSelector() {
return conf.getInformerConfig().getLabelSelector();
}
public List<JSONDependentResourceSpec> getDependents() {
final var dependents = conf.getWorkflowSpec().map(WorkflowSpec::getDependentResourceSpecs)
.orElse(Collections.emptyList());
final var result = new ArrayList<JSONDependentResourceSpec>(dependents.size());
return dependents.stream()
.map(JSONDependentResourceSpec::new)
.collect(Collectors.toList());
}
@JsonProperty("maxReconciliationIntervalSeconds")
public long maxReconciliationIntervalSeconds() {
return conf.maxReconciliationInterval().map(Duration::getSeconds).orElseThrow();
}
@SuppressWarnings("rawtypes")
public RateLimiter getRateLimiter() {
return conf.getRateLimiter();
}
public ItemStore<?> getItemStore() {
return conf.getInformerConfig().getItemStore();
}
}
static class JSONDependentResourceSpec {
private final DependentResourceSpec<?, ?, ?> spec;
JSONDependentResourceSpec(DependentResourceSpec<?, ?, ?> spec) {
this.spec = spec;
}
public String getDependentClass() {
return spec.getDependentResourceClass().getCanonicalName();
}
public Object getDependentConfig() {
final var c = spec.getConfiguration().orElse(null);
if (c instanceof KubernetesDependentResourceConfig) {
return new JSONKubernetesResourceConfig((KubernetesDependentResourceConfig<?>) c);
} else {
return c;
}
}
public String getName() {
return spec.getName();
}
}
// needed for native tests, see https://quarkus.io/guides/writing-native-applications-tips#registering-for-reflection
@RegisterForReflection
static class JSONKubernetesResourceConfig {
private final KubernetesDependentResourceConfig<?> config;
JSONKubernetesResourceConfig(KubernetesDependentResourceConfig<?> config) {
this.config = config;
}
public String getOnAddFilter() {
return Optional.ofNullable(config.informerConfig().getOnAddFilter())
.map(f -> f.getClass().getCanonicalName())
.orElse(null);
}
public String getLabelSelector() {
return config.informerConfig().getLabelSelector();
}
}
static class JSONWorkflow {
private final ManagedWorkflow<?> workflow;
@SuppressWarnings("rawtypes")
JSONWorkflow(ManagedWorkflow workflow) {
this.workflow = workflow;
}
public boolean isCleaner() {
return workflow.hasCleaner();
}
public boolean isEmpty() {
return workflow.isEmpty();
}
public Map<String, JSONDRSpec> getDependents() {
return workflow.getOrderedSpecs().stream()
.collect(Collectors.toMap(DependentResourceSpec::getName, JSONDRSpec::new));
}
}
@SuppressWarnings("rawtypes")
static class JSONDRSpec {
private final DependentResourceSpec spec;
JSONDRSpec(DependentResourceSpec spec) {
this.spec = spec;
}
public String getType() {
return spec.getDependentResourceClass().getName();
}
public String getReadyCondition() {
final var readyCondition = spec.getReadyCondition();
return readyCondition == null ? null : readyCondition.getClass().getName();
}
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/pingpong/src/test/java/io/quarkiverse/operatorsdk/samples/pingpong/PingPongReconcilerTest.java | samples/pingpong/src/test/java/io/quarkiverse/operatorsdk/samples/pingpong/PingPongReconcilerTest.java | package io.quarkiverse.operatorsdk.samples.pingpong;
import static java.util.concurrent.TimeUnit.MINUTES;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.notNullValue;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import io.fabric8.kubernetes.api.model.ObjectMetaBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.javaoperatorsdk.operator.Operator;
import io.quarkus.test.junit.QuarkusTest;
@QuarkusTest
class PingPongReconcilerTest {
private static final String PING_REQUEST_NAME = "myping1";
private static final String PONG_REQUEST_NAME = PING_REQUEST_NAME + "-pong";
@Inject
Operator operator;
@Inject
KubernetesClient client;
@Test
void canReconcile() {
operator.start();
final Ping testRequest = new Ping();
testRequest.setMetadata(new ObjectMetaBuilder()
.withName(PING_REQUEST_NAME)
.withNamespace(client.getNamespace())
.build());
// act
client.resource(testRequest).create();
// assert ping reconciler
await().ignoreException(NullPointerException.class).atMost(5, MINUTES).untilAsserted(() -> {
Ping updatedRequest = client.resource(testRequest).get();
assertThat(updatedRequest.getStatus(), is(notNullValue()));
assertThat(updatedRequest.getStatus().getState(), is(Status.State.PROCESSED));
});
var createdPongs = client.resources(Pong.class)
.inNamespace(testRequest.getMetadata().getNamespace())
.list();
assertThat(createdPongs.getItems(), is(not(empty())));
assertThat(createdPongs.getItems().get(0).getMetadata().getName(), is(PONG_REQUEST_NAME));
// assert pong reconciler
await().ignoreException(NullPointerException.class).atMost(5, MINUTES).untilAsserted(() -> {
Pong updatedRequest = client.resources(Pong.class)
.inNamespace(testRequest.getMetadata().getNamespace())
.withName(PONG_REQUEST_NAME).get();
assertThat(updatedRequest.getStatus(), is(notNullValue()));
assertThat(updatedRequest.getStatus().getState(), is(Status.State.PROCESSED));
});
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/pingpong/src/test/java/io/quarkiverse/operatorsdk/samples/pingpong/AssertGeneratedResourcesIT.java | samples/pingpong/src/test/java/io/quarkiverse/operatorsdk/samples/pingpong/AssertGeneratedResourcesIT.java | package io.quarkiverse.operatorsdk.samples.pingpong;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.FileInputStream;
import java.util.List;
import org.junit.jupiter.api.Test;
import io.fabric8.kubernetes.client.KubernetesClientBuilder;
import io.fabric8.openshift.api.model.operatorhub.v1alpha1.ClusterServiceVersion;
import io.fabric8.openshift.api.model.operatorhub.v1alpha1.StrategyDeploymentPermissions;
class AssertGeneratedResourcesIT {
@Test
void verifyPingPongClusterServiceVersion() {
try (final var client = new KubernetesClientBuilder().build()) {
final var csv = client.getKubernetesSerialization().unmarshal(new FileInputStream(
"target/bundle/pingpong-operator/manifests/pingpong-operator.clusterserviceversion.yaml"),
ClusterServiceVersion.class);
// should have only one cluster rule permission
List<StrategyDeploymentPermissions> clusterPermissions = csv.getSpec().getInstall().getSpec()
.getClusterPermissions();
assertEquals(1, clusterPermissions.size());
List<StrategyDeploymentPermissions> permissions = csv.getSpec().getInstall().getSpec().getPermissions();
assertEquals(1, permissions.size());
} catch (Exception e) {
fail(e);
}
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/pingpong/src/main/java/io/quarkiverse/operatorsdk/samples/pingpong/PingReconciler.java | samples/pingpong/src/main/java/io/quarkiverse/operatorsdk/samples/pingpong/PingReconciler.java | /**
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.quarkiverse.operatorsdk.samples.pingpong;
import static io.javaoperatorsdk.operator.api.reconciler.Constants.WATCH_CURRENT_NAMESPACE;
import static io.quarkiverse.operatorsdk.samples.pingpong.PingPongOperatorCSVMetadata.BUNDLE_NAME;
import jakarta.inject.Inject;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.javaoperatorsdk.operator.api.config.informer.Informer;
import io.javaoperatorsdk.operator.api.reconciler.Context;
import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration;
import io.javaoperatorsdk.operator.api.reconciler.Reconciler;
import io.javaoperatorsdk.operator.api.reconciler.UpdateControl;
import io.quarkiverse.operatorsdk.annotations.CSVMetadata;
@CSVMetadata(bundleName = BUNDLE_NAME)
@ControllerConfiguration(informer = @Informer(namespaces = WATCH_CURRENT_NAMESPACE))
@SuppressWarnings("unused")
public class PingReconciler implements Reconciler<Ping> {
@Inject
KubernetesClient client;
@Override
public UpdateControl<Ping> reconcile(Ping ping, Context<Ping> context) {
Status status = ping.getStatus();
if (status != null && Status.State.PROCESSED == status.getState()) {
return UpdateControl.noUpdate();
}
final String expectedPongResource = ping.getMetadata().getName() + "-pong";
final var pongs = client.resources(Pong.class);
final var existing = pongs.withName(expectedPongResource).get();
if (existing == null) {
Pong pong = new Pong();
pong.getMetadata().setName(expectedPongResource);
pongs.resource(pong).create();
}
ping.setStatus(new Status(Status.State.PROCESSED));
return UpdateControl.patchStatus(ping);
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/pingpong/src/main/java/io/quarkiverse/operatorsdk/samples/pingpong/Pong.java | samples/pingpong/src/main/java/io/quarkiverse/operatorsdk/samples/pingpong/Pong.java | /**
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.quarkiverse.operatorsdk.samples.pingpong;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import io.fabric8.kubernetes.api.model.Namespaced;
import io.fabric8.kubernetes.client.CustomResource;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Version;
@Group("samples.javaoperatorsdk.io")
@Version("v1alpha1")
@JsonInclude(Include.NON_NULL)
public class Pong extends CustomResource<Void, Status> implements Namespaced {
public Pong() {
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/pingpong/src/main/java/io/quarkiverse/operatorsdk/samples/pingpong/Status.java | samples/pingpong/src/main/java/io/quarkiverse/operatorsdk/samples/pingpong/Status.java | package io.quarkiverse.operatorsdk.samples.pingpong;
public class Status {
public enum State {
PROCESSED,
UNKNOWN
}
private Status.State state = Status.State.UNKNOWN;
public Status() {
}
public Status(Status.State state) {
this.state = state;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/pingpong/src/main/java/io/quarkiverse/operatorsdk/samples/pingpong/PingPongOperatorCSVMetadata.java | samples/pingpong/src/main/java/io/quarkiverse/operatorsdk/samples/pingpong/PingPongOperatorCSVMetadata.java | package io.quarkiverse.operatorsdk.samples.pingpong;
import io.quarkiverse.operatorsdk.annotations.CSVMetadata;
import io.quarkiverse.operatorsdk.annotations.SharedCSVMetadata;
@CSVMetadata(bundleName = PingPongOperatorCSVMetadata.BUNDLE_NAME)
@SuppressWarnings("unused")
public class PingPongOperatorCSVMetadata implements SharedCSVMetadata {
public static final String BUNDLE_NAME = "pingpong-operator";
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/pingpong/src/main/java/io/quarkiverse/operatorsdk/samples/pingpong/Ping.java | samples/pingpong/src/main/java/io/quarkiverse/operatorsdk/samples/pingpong/Ping.java | /**
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.quarkiverse.operatorsdk.samples.pingpong;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import io.fabric8.kubernetes.api.model.Namespaced;
import io.fabric8.kubernetes.client.CustomResource;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Version;
@Group("samples.javaoperatorsdk.io")
@Version("v1alpha1")
@JsonInclude(Include.NON_NULL)
public class Ping extends CustomResource<Void, Status> implements Namespaced {
public Ping() {
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/pingpong/src/main/java/io/quarkiverse/operatorsdk/samples/pingpong/PongReconciler.java | samples/pingpong/src/main/java/io/quarkiverse/operatorsdk/samples/pingpong/PongReconciler.java | /**
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.quarkiverse.operatorsdk.samples.pingpong;
import static io.javaoperatorsdk.operator.api.reconciler.Constants.WATCH_CURRENT_NAMESPACE;
import static io.quarkiverse.operatorsdk.samples.pingpong.PingPongOperatorCSVMetadata.BUNDLE_NAME;
import io.javaoperatorsdk.operator.api.config.informer.Informer;
import io.javaoperatorsdk.operator.api.reconciler.Context;
import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration;
import io.javaoperatorsdk.operator.api.reconciler.Reconciler;
import io.javaoperatorsdk.operator.api.reconciler.UpdateControl;
import io.quarkiverse.operatorsdk.annotations.CSVMetadata;
@CSVMetadata(bundleName = BUNDLE_NAME)
@SuppressWarnings("unused")
@ControllerConfiguration(informer = @Informer(namespaces = WATCH_CURRENT_NAMESPACE))
public class PongReconciler implements Reconciler<Pong> {
@Override
public UpdateControl<Pong> reconcile(Pong pong, Context<Pong> context) {
Status status = pong.getStatus();
if (status != null && Status.State.PROCESSED == status.getState()) {
return UpdateControl.noUpdate();
}
pong.setStatus(new Status(Status.State.PROCESSED));
return UpdateControl.patchStatus(pong);
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/joke/src/test/java/io/quarkiverse/operatorsdk/samples/joke/JokeRequestReconcilerTest.java | samples/joke/src/test/java/io/quarkiverse/operatorsdk/samples/joke/JokeRequestReconcilerTest.java | package io.quarkiverse.operatorsdk.samples.joke;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.notNullValue;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import java.util.Map;
import jakarta.inject.Inject;
import org.eclipse.microprofile.rest.client.inject.RestClient;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import io.fabric8.kubernetes.api.model.ObjectMetaBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.quarkiverse.operatorsdk.samples.joke.JokeRequestSpec.Category;
import io.quarkiverse.operatorsdk.samples.joke.JokeRequestStatus.State;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
@QuarkusTest
class JokeRequestReconcilerTest {
@InjectMock
@RestClient
JokeService jokeService;
@Inject
KubernetesClient client;
@Test
void canReconcile() {
// arrange
final JokeModel joke = new JokeModel();
joke.id = 1;
joke.joke = "Hello";
joke.flags = Map.of();
Mockito.when(jokeService.getRandom(eq(Category.Any), anyString(), anyBoolean(), anyString())).thenReturn(joke);
final JokeRequest testRequest = new JokeRequest();
testRequest.setMetadata(new ObjectMetaBuilder()
.withName("myjoke1")
.withNamespace(client.getNamespace())
.build());
testRequest.setSpec(new JokeRequestSpec());
testRequest.getSpec().setCategory(Category.Any);
// act
client.resource(testRequest).create();
// assert
await().ignoreException(NullPointerException.class).atMost(300, SECONDS).untilAsserted(() -> {
JokeRequest updatedRequest = client.resources(JokeRequest.class)
.inNamespace(testRequest.getMetadata().getNamespace())
.withName(testRequest.getMetadata().getName())
.get();
assertThat(updatedRequest.getStatus(), is(notNullValue()));
assertThat(updatedRequest.getStatus().getState(), equalTo(State.CREATED));
});
var createdJokes = client.resources(Joke.class).inNamespace(testRequest.getMetadata().getNamespace())
.list();
assertThat(createdJokes.getItems(), is(not(empty())));
assertThat(createdJokes.getItems().get(0).getJoke(), is("Hello"));
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/joke/src/main/java/io/quarkiverse/operatorsdk/samples/joke/JokeRequestReconciler.java | samples/joke/src/main/java/io/quarkiverse/operatorsdk/samples/joke/JokeRequestReconciler.java | /**
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.quarkiverse.operatorsdk.samples.joke;
import static io.javaoperatorsdk.operator.api.reconciler.Constants.WATCH_CURRENT_NAMESPACE;
import java.util.Arrays;
import java.util.stream.Collectors;
import jakarta.inject.Inject;
import org.eclipse.microprofile.rest.client.inject.RestClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.javaoperatorsdk.operator.api.config.informer.Informer;
import io.javaoperatorsdk.operator.api.reconciler.Context;
import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration;
import io.javaoperatorsdk.operator.api.reconciler.Reconciler;
import io.javaoperatorsdk.operator.api.reconciler.UpdateControl;
import io.quarkiverse.operatorsdk.annotations.CSVMetadata;
import io.quarkiverse.operatorsdk.annotations.CSVMetadata.Icon;
import io.quarkiverse.operatorsdk.annotations.RBACRule;
import io.quarkiverse.operatorsdk.samples.joke.JokeRequestSpec.ExcludedTopic;
import io.quarkiverse.operatorsdk.samples.joke.JokeRequestStatus.State;
@CSVMetadata(bundleName = "joke-operator", requiredCRDs = @CSVMetadata.RequiredCRD(kind = "Joke", name = Joke.NAME, version = Joke.VERSION), icon = @Icon(fileName = "icon.png", mediatype = "image/png"))
@ControllerConfiguration(informer = @Informer(namespaces = WATCH_CURRENT_NAMESPACE))
@RBACRule(apiGroups = Joke.GROUP, resources = "jokes", verbs = RBACRule.ALL)
@SuppressWarnings("unused")
public class JokeRequestReconciler implements Reconciler<JokeRequest> {
@Inject
@RestClient
JokeService jokes;
@Inject
KubernetesClient client;
@Override
public UpdateControl<JokeRequest> reconcile(JokeRequest jr, Context<JokeRequest> context) {
final var spec = jr.getSpec();
// if the joke has already been created, ignore
JokeRequestStatus status = jr.getStatus();
if (status != null && State.CREATED == status.getState()) {
return UpdateControl.noUpdate();
}
try {
final JokeModel fromApi = jokes.getRandom(spec.getCategory(),
String.join(",", Arrays.stream(spec.getExcluded()).map(ExcludedTopic::name).toArray(String[]::new)),
spec.isSafe(), "single");
status = JokeRequestStatus.from(fromApi);
if (!status.isError()) {
// create the joke
final var joke = new Joke(fromApi.id, fromApi.joke, fromApi.category, fromApi.safe,
fromApi.lang);
final var flags = fromApi.flags.entrySet().stream().collect(Collectors.toMap(
entry -> "joke_flag_" + entry.getKey(),
entry -> entry.getValue().toString()));
joke.getMetadata().setLabels(flags);
// if we don't already have created this joke on the cluster, do so
final var jokes = client.resources(Joke.class);
final var jokeResource = jokes.withName("" + fromApi.id);
final var existing = jokeResource.get();
if (existing != null) {
status.setMessage("Joke " + fromApi.id + " already exists");
status.setState(State.ALREADY_PRESENT);
} else {
jokes.resource(joke).create();
status.setMessage("Joke " + fromApi.id + " created");
status.setState(State.CREATED);
}
}
} catch (Exception e) {
status = new JokeRequestStatus();
status.setMessage("Error querying API: " + e.getMessage());
status.setState(State.ERROR);
status.setError(true);
}
jr.setStatus(status);
return UpdateControl.patchStatus(jr);
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/joke/src/main/java/io/quarkiverse/operatorsdk/samples/joke/JokeService.java | samples/joke/src/main/java/io/quarkiverse/operatorsdk/samples/joke/JokeService.java | /**
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.quarkiverse.operatorsdk.samples.joke;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
import org.jboss.resteasy.reactive.RestPath;
import org.jboss.resteasy.reactive.RestQuery;
import io.quarkiverse.operatorsdk.samples.joke.JokeRequestSpec.Category;
@ApplicationScoped
@RegisterRestClient(configKey = "joke-api")
public interface JokeService {
@GET
@Path("/{category}/any")
@Produces("application/json")
JokeModel getRandom(@RestPath Category category, @RestQuery(value = "blacklistFlags") String excluded,
@RestQuery(value = "safe-mode") boolean safe, @DefaultValue("single") @RestQuery String type);
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/joke/src/main/java/io/quarkiverse/operatorsdk/samples/joke/JokeModel.java | samples/joke/src/main/java/io/quarkiverse/operatorsdk/samples/joke/JokeModel.java | /**
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.quarkiverse.operatorsdk.samples.joke;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class JokeModel {
/*
* "error": true,
* "internalError": false,
* "code": 106,
* "message": "No matching joke found",
* "causedBy": [
* "No jokes were found that match your provided filter(s)."
* ],
* "additionalInfo": "The specified ID range is invalid. Got: \"foo\" but max possible ID range is: \"0-303\".",
* "timestamp": 1615998352457
*/
public boolean error;
public boolean internalError;
public String message;
public String[] causedBy;
public String additionalInfo;
public String category;
public String joke;
public Map<String, Boolean> flags;
public int id;
public boolean safe;
public String lang;
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/joke/src/main/java/io/quarkiverse/operatorsdk/samples/joke/JokeRequestSpec.java | samples/joke/src/main/java/io/quarkiverse/operatorsdk/samples/joke/JokeRequestSpec.java | /**
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.quarkiverse.operatorsdk.samples.joke;
public class JokeRequestSpec {
public enum Category {
Any,
Misc,
Programming,
Dark,
Pun,
Spooky,
Christmas
}
public enum ExcludedTopic {
nsfw,
religious,
political,
racist,
sexist,
explicit
}
private Category category = Category.Any;
private ExcludedTopic[] excluded = new ExcludedTopic[] { ExcludedTopic.nsfw, ExcludedTopic.racist, ExcludedTopic.sexist };
private boolean safe;
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public ExcludedTopic[] getExcluded() {
return excluded;
}
public void setExcluded(ExcludedTopic[] excluded) {
this.excluded = excluded;
}
public boolean isSafe() {
return safe;
}
public void setSafe(boolean safe) {
this.safe = safe;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/joke/src/main/java/io/quarkiverse/operatorsdk/samples/joke/JokeRequest.java | samples/joke/src/main/java/io/quarkiverse/operatorsdk/samples/joke/JokeRequest.java | /**
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.quarkiverse.operatorsdk.samples.joke;
import io.fabric8.kubernetes.api.model.Namespaced;
import io.fabric8.kubernetes.client.CustomResource;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.ShortNames;
import io.fabric8.kubernetes.model.annotation.Version;
@Group("samples.javaoperatorsdk.io")
@Version("v1alpha1")
@ShortNames("jr")
public class JokeRequest extends CustomResource<JokeRequestSpec, JokeRequestStatus> implements Namespaced {
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/joke/src/main/java/io/quarkiverse/operatorsdk/samples/joke/Joke.java | samples/joke/src/main/java/io/quarkiverse/operatorsdk/samples/joke/Joke.java | /**
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.quarkiverse.operatorsdk.samples.joke;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import io.fabric8.kubernetes.api.model.Namespaced;
import io.fabric8.kubernetes.client.CustomResource;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Version;
@Group(Joke.GROUP)
@Version(Joke.VERSION)
@JsonInclude(Include.NON_NULL)
public class Joke extends CustomResource<Void, Void> implements Namespaced {
public static final String GROUP = "samples.javaoperatorsdk.io";
public static final String VERSION = "v1alpha1";
public static final String NAME = "jokes." + GROUP;
private String joke;
private String category;
private boolean safe;
private String lang;
private int id;
public Joke() {
}
public Joke(int id, String joke, String category, boolean safe, String lang) {
this.id = id;
getMetadata().setName("" + id);
this.joke = joke;
this.category = category;
this.safe = safe;
this.lang = lang;
}
public int getId() {
return id;
}
public String getJoke() {
return joke;
}
public void setJoke(String joke) {
this.joke = joke;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public boolean isSafe() {
return safe;
}
public void setSafe(boolean safe) {
this.safe = safe;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/joke/src/main/java/io/quarkiverse/operatorsdk/samples/joke/JokeRequestStatus.java | samples/joke/src/main/java/io/quarkiverse/operatorsdk/samples/joke/JokeRequestStatus.java | /**
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.quarkiverse.operatorsdk.samples.joke;
public class JokeRequestStatus {
public enum State {
CREATED,
ALREADY_PRESENT,
PROCESSING,
ERROR,
UNKNOWN
}
private State state = State.UNKNOWN;
private boolean error;
private String message;
public static JokeRequestStatus from(JokeModel model) {
final var status = new JokeRequestStatus();
if (model.error) {
status.error = true;
status.message = model.message + ": " + model.additionalInfo;
status.state = State.ERROR;
} else {
status.error = false;
status.state = State.PROCESSING;
}
return status;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public boolean isError() {
return error;
}
public void setError(boolean error) {
this.error = error;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/mysql-schema/src/test/java/io/quarkiverse/operatorsdk/samples/mysqlschema/MySQLSchemaOperatorE2ETest.java | samples/mysql-schema/src/test/java/io/quarkiverse/operatorsdk/samples/mysqlschema/MySQLSchemaOperatorE2ETest.java | package io.quarkiverse.operatorsdk.samples.mysqlschema;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.Optional;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.fabric8.kubernetes.api.model.ObjectMetaBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.javaoperatorsdk.operator.Operator;
import io.quarkiverse.operatorsdk.samples.mysqlschema.schema.Schema;
import io.quarkiverse.operatorsdk.samples.mysqlschema.schema.SchemaService;
import io.quarkus.logging.Log;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectSpy;
@QuarkusTest
class MySQLSchemaOperatorE2ETest {
private static final String DB_NAME = "mydb1";
private static final String ENCODING = "utf8";
@InjectSpy
SchemaService schemaService;
@Inject
Operator operator;
@Inject
KubernetesClient client;
@BeforeEach
void startOperator() {
operator.start();
}
@AfterEach
void stopOperator() {
operator.stop();
}
@Test
void test() {
final Optional<Schema> maybeSchema = schemaService.getSchema(DB_NAME);
if (maybeSchema.isPresent()) {
fail("Schema " + DB_NAME + " should not already exist");
}
MySQLSchema testSchema = new MySQLSchema();
testSchema.setMetadata(new ObjectMetaBuilder()
.withName(DB_NAME)
.withNamespace(client.getNamespace())
.build());
testSchema.setSpec(new SchemaSpec());
testSchema.getSpec().setEncoding(ENCODING);
Log.infof("Creating test MySQLSchema object: %s", testSchema);
client.resource(testSchema).serverSideApply();
Log.info("Waiting 10 seconds for expected resources to be created and updated");
await().pollDelay(9, SECONDS).atMost(10, SECONDS).untilAsserted(() -> {
MySQLSchema updatedSchema = client.resources(MySQLSchema.class)
.inNamespace(testSchema.getMetadata().getNamespace())
.withName(testSchema.getMetadata().getName()).get();
assertThat(updatedSchema.getStatus(), is(notNullValue()));
assertThat(updatedSchema.getStatus().getStatus(), equalTo("CREATED"));
assertThat(updatedSchema.getStatus().getSecretName(), is(notNullValue()));
assertThat(updatedSchema.getStatus().getUserName(), is(notNullValue()));
assertThat(updatedSchema.getStatus().getUrl(), startsWith("jdbc:mysql://"));
});
verify(schemaService, times(1)).createSchemaAndRelatedUser(any(), eq(DB_NAME), eq(ENCODING), anyString(),
anyString());
client.resource(testSchema).delete();
await()
.atMost(10, SECONDS)
.ignoreExceptions()
.untilAsserted(
() -> {
MySQLSchema updatedSchema = client
.resources(MySQLSchema.class)
.inNamespace(testSchema.getMetadata().getNamespace())
.withName(testSchema.getMetadata().getName())
.get();
assertThat(updatedSchema, is(nullValue()));
});
verify(schemaService, times(1)).deleteSchemaAndRelatedUser(any(), eq(DB_NAME), anyString());
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/mysql-schema/src/main/java/io/quarkiverse/operatorsdk/samples/mysqlschema/MySQLSchema.java | samples/mysql-schema/src/main/java/io/quarkiverse/operatorsdk/samples/mysqlschema/MySQLSchema.java | package io.quarkiverse.operatorsdk.samples.mysqlschema;
import io.fabric8.kubernetes.api.model.Namespaced;
import io.fabric8.kubernetes.client.CustomResource;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Version;
@Group("mysql.sample.javaoperatorsdk")
@Version("v1")
public class MySQLSchema extends CustomResource<SchemaSpec, SchemaStatus> implements Namespaced {
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/mysql-schema/src/main/java/io/quarkiverse/operatorsdk/samples/mysqlschema/SchemaSpec.java | samples/mysql-schema/src/main/java/io/quarkiverse/operatorsdk/samples/mysqlschema/SchemaSpec.java | package io.quarkiverse.operatorsdk.samples.mysqlschema;
public class SchemaSpec {
private String encoding;
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/mysql-schema/src/main/java/io/quarkiverse/operatorsdk/samples/mysqlschema/MySQLSchemaReconciler.java | samples/mysql-schema/src/main/java/io/quarkiverse/operatorsdk/samples/mysqlschema/MySQLSchemaReconciler.java | package io.quarkiverse.operatorsdk.samples.mysqlschema;
import static io.quarkiverse.operatorsdk.samples.mysqlschema.dependent.SchemaDependentResource.decode;
import static io.quarkiverse.operatorsdk.samples.mysqlschema.dependent.SecretDependentResource.MYSQL_SECRET_USERNAME;
import jakarta.inject.Inject;
import io.fabric8.kubernetes.api.model.Secret;
import io.javaoperatorsdk.operator.api.reconciler.Context;
import io.javaoperatorsdk.operator.api.reconciler.ErrorStatusUpdateControl;
import io.javaoperatorsdk.operator.api.reconciler.Reconciler;
import io.javaoperatorsdk.operator.api.reconciler.UpdateControl;
import io.javaoperatorsdk.operator.api.reconciler.Workflow;
import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent;
import io.quarkiverse.operatorsdk.samples.mysqlschema.dependent.SchemaDependentResource;
import io.quarkiverse.operatorsdk.samples.mysqlschema.dependent.SecretDependentResource;
import io.quarkiverse.operatorsdk.samples.mysqlschema.schema.Schema;
import io.quarkiverse.operatorsdk.samples.mysqlschema.schema.SchemaService;
import io.quarkus.logging.Log;
@Workflow(dependents = {
@Dependent(type = SecretDependentResource.class, name = SecretDependentResource.DEPENDENT_NAME),
@Dependent(type = SchemaDependentResource.class, dependsOn = SecretDependentResource.DEPENDENT_NAME)
})
@SuppressWarnings("unused")
public class MySQLSchemaReconciler implements Reconciler<MySQLSchema> {
@Inject
SchemaService schemaService;
@Override
public UpdateControl<MySQLSchema> reconcile(MySQLSchema schema, Context<MySQLSchema> context) {
// we only need to update the status if we just built the schema, i.e. when it's
// present in the context
return context.getSecondaryResource(Secret.class)
.map(secret -> context.getSecondaryResource(Schema.class)
.map(s -> {
updateStatusPojo(schema, secret.getMetadata().getName(),
decode(secret.getData().get(MYSQL_SECRET_USERNAME)));
Log.infof("Schema %s created - updating CR status", s.getName());
return UpdateControl.patchStatus(schema);
}).orElse(UpdateControl.noUpdate()))
.orElse(UpdateControl.noUpdate());
}
@Override
public ErrorStatusUpdateControl<MySQLSchema> updateErrorStatus(MySQLSchema schema,
Context<MySQLSchema> context, Exception e) {
Log.error("updateErrorStatus", e);
SchemaStatus status = new SchemaStatus();
status.setUrl(null);
status.setUserName(null);
status.setSecretName(null);
status.setStatus("ERROR: " + e.getMessage());
schema.setStatus(status);
return ErrorStatusUpdateControl.patchStatus(schema);
}
private void updateStatusPojo(MySQLSchema schema, String secretName, String userName) {
SchemaStatus status = new SchemaStatus();
status.setUrl(schemaService.getjdbcURL(schema));
status.setUserName(userName);
status.setSecretName(secretName);
status.setStatus("CREATED");
schema.setStatus(status);
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/mysql-schema/src/main/java/io/quarkiverse/operatorsdk/samples/mysqlschema/SchemaStatus.java | samples/mysql-schema/src/main/java/io/quarkiverse/operatorsdk/samples/mysqlschema/SchemaStatus.java | package io.quarkiverse.operatorsdk.samples.mysqlschema;
public class SchemaStatus {
private String url;
private String status;
private String userName;
private String secretName;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSecretName() {
return secretName;
}
public void setSecretName(String secretName) {
this.secretName = secretName;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/mysql-schema/src/main/java/io/quarkiverse/operatorsdk/samples/mysqlschema/schema/Schema.java | samples/mysql-schema/src/main/java/io/quarkiverse/operatorsdk/samples/mysqlschema/schema/Schema.java | package io.quarkiverse.operatorsdk.samples.mysqlschema.schema;
import java.io.Serializable;
import java.util.Objects;
import io.javaoperatorsdk.operator.processing.ResourceIDProvider;
public class Schema implements Serializable, ResourceIDProvider<String> {
private final String name;
private final String characterSet;
public Schema(String name, String characterSet) {
this.name = name;
this.characterSet = characterSet;
}
public String getName() {
return name;
}
public String getCharacterSet() {
return characterSet;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Schema schema = (Schema) o;
return Objects.equals(name, schema.name) && Objects.equals(characterSet, schema.characterSet);
}
@Override
public int hashCode() {
return Objects.hash(name, characterSet);
}
@Override
public String toString() {
return "Schema{" + "name='" + name + '\'' + ", characterSet='" + characterSet + "'}";
}
@Override
public String resourceId() {
// in this case, we use the naming mechanism as the resource identifying mechanism for ResourceIDProvider
// so we use the implementation provided by getName
return getName();
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/mysql-schema/src/main/java/io/quarkiverse/operatorsdk/samples/mysqlschema/schema/SchemaService.java | samples/mysql-schema/src/main/java/io/quarkiverse/operatorsdk/samples/mysqlschema/schema/SchemaService.java | package io.quarkiverse.operatorsdk.samples.mysqlschema.schema;
import static java.lang.String.format;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Optional;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import io.agroal.api.AgroalDataSource;
import io.quarkiverse.operatorsdk.samples.mysqlschema.MySQLSchema;
import io.quarkus.logging.Log;
@ApplicationScoped
public class SchemaService {
@Inject
AgroalDataSource defaultDataSource;
public Optional<Schema> getSchema(String name) {
try (Connection connection = getConnection()) {
return getSchema(connection, name);
} catch (SQLException e) {
throw new IllegalStateException(e);
}
}
public Schema createSchemaAndRelatedUser(Connection connection, String schemaName,
String encoding,
String userName,
String password) {
try {
try (Statement statement = connection.createStatement()) {
statement.execute(
format(
"CREATE SCHEMA `%1$s` DEFAULT CHARACTER SET %2$s",
schemaName, encoding));
}
if (!userExists(connection, userName)) {
try (Statement statement = connection.createStatement()) {
statement.execute(format("CREATE USER '%1$s' IDENTIFIED BY '%2$s'", userName, password));
}
}
try (Statement statement = connection.createStatement()) {
statement.execute(
format("GRANT ALL ON `%1$s`.* TO '%2$s'", schemaName, userName));
}
return new Schema(schemaName, encoding);
} catch (SQLException e) {
throw new IllegalStateException(e);
}
}
public void deleteSchemaAndRelatedUser(Connection connection, String schemaName,
String userName) {
try {
try (Statement statement = connection.createStatement()) {
statement.execute(format("DROP DATABASE `%1$s`", schemaName));
}
Log.infof("Deleted Schema '%s'", schemaName);
if (userName != null) {
try (Statement statement = connection.createStatement()) {
statement.execute(format("DROP USER '%1$s'", userName));
}
Log.infof("Deleted User '%s'", userName);
}
} catch (SQLException e) {
throw new IllegalStateException(e);
}
}
private boolean userExists(Connection connection, String username) {
try (PreparedStatement ps = connection.prepareStatement(
"SELECT 1 FROM mysql.user WHERE user = ?")) {
ps.setString(1, username);
try (ResultSet resultSet = ps.executeQuery()) {
return resultSet.next();
}
} catch (SQLException e) {
throw new IllegalStateException(e);
}
}
public Optional<Schema> getSchema(Connection connection, String schemaName) {
try (PreparedStatement ps = connection.prepareStatement(
"SELECT * FROM information_schema.schemata WHERE schema_name = ?")) {
ps.setString(1, schemaName);
try (ResultSet resultSet = ps.executeQuery()) {
// CATALOG_NAME, SCHEMA_NAME, DEFAULT_CHARACTER_SET_NAME,
// DEFAULT_COLLATION_NAME, SQL_PATH
var exists = resultSet.next();
if (!exists) {
return Optional.empty();
} else {
return Optional.of(new Schema(resultSet.getString("SCHEMA_NAME"),
resultSet.getString("DEFAULT_CHARACTER_SET_NAME")));
}
}
} catch (SQLException e) {
throw new IllegalStateException(e);
}
}
public Connection getConnection() {
try {
Log.infof("Connecting to '%s' with user '%s'",
defaultDataSource.getConfiguration().connectionPoolConfiguration().connectionFactoryConfiguration()
.jdbcUrl(),
defaultDataSource.getConfiguration().connectionPoolConfiguration().connectionFactoryConfiguration()
.principal().getName());
return defaultDataSource.getConnection();
} catch (SQLException e) {
throw new IllegalStateException(e);
}
}
public String getjdbcURL(MySQLSchema schema) {
String jdbcUrl = defaultDataSource.getConfiguration().connectionPoolConfiguration().connectionFactoryConfiguration()
.jdbcUrl();
String hostname = jdbcUrl.split("//")[1].split("/")[0];
return format(
"jdbc:mysql://%1$s/%2$s", hostname, schema.getMetadata().getName());
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/mysql-schema/src/main/java/io/quarkiverse/operatorsdk/samples/mysqlschema/dependent/ResourcePollerConfig.java | samples/mysql-schema/src/main/java/io/quarkiverse/operatorsdk/samples/mysqlschema/dependent/ResourcePollerConfig.java | package io.quarkiverse.operatorsdk.samples.mysqlschema.dependent;
public class ResourcePollerConfig {
private final int pollPeriod;
public ResourcePollerConfig(int pollPeriod) {
this.pollPeriod = pollPeriod;
}
public int getPollPeriod() {
return pollPeriod;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/mysql-schema/src/main/java/io/quarkiverse/operatorsdk/samples/mysqlschema/dependent/SecretDependentResource.java | samples/mysql-schema/src/main/java/io/quarkiverse/operatorsdk/samples/mysqlschema/dependent/SecretDependentResource.java | package io.quarkiverse.operatorsdk.samples.mysqlschema.dependent;
import java.util.Base64;
import jakarta.enterprise.context.ApplicationScoped;
import org.apache.commons.lang3.RandomStringUtils;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.SecretBuilder;
import io.javaoperatorsdk.operator.api.reconciler.Context;
import io.javaoperatorsdk.operator.processing.dependent.Creator;
import io.javaoperatorsdk.operator.processing.dependent.Matcher.Result;
import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource;
import io.quarkiverse.operatorsdk.samples.mysqlschema.MySQLSchema;
@ApplicationScoped
public class SecretDependentResource extends KubernetesDependentResource<Secret, MySQLSchema>
implements Creator<Secret, MySQLSchema> {
public static final String DEPENDENT_NAME = "secret-dependent";
public static final String SECRET_FORMAT = "%s-secret";
public static final String USERNAME_FORMAT = "%s-user";
public static final String MYSQL_SECRET_USERNAME = "mysql.secret.user.name";
public static final String MYSQL_SECRET_PASSWORD = "mysql.secret.user.password";
// todo: automatically generate
public SecretDependentResource() {
super(Secret.class);
}
private static String encode(String value) {
return Base64.getEncoder().encodeToString(value.getBytes());
}
@Override
protected Secret desired(MySQLSchema schema, Context<MySQLSchema> context) {
final var password = RandomStringUtils.insecure().nextAlphanumeric(16); // NOSONAR: we don't need cryptographically-strong randomness here
final var name = schema.getMetadata().getName();
final var secretName = getSecretName(name);
final var userName = String.format(USERNAME_FORMAT, name);
return new SecretBuilder()
.withNewMetadata()
.withName(secretName)
.withNamespace(schema.getMetadata().getNamespace())
.endMetadata()
.addToData(MYSQL_SECRET_USERNAME, encode(userName))
.addToData(MYSQL_SECRET_PASSWORD, encode(password))
.build();
}
private String getSecretName(String name) {
return String.format(SECRET_FORMAT, name);
}
@Override
public Result<Secret> match(Secret actual, MySQLSchema primary, Context context) {
final var desiredSecretName = getSecretName(primary.getMetadata().getName());
return Result.nonComputed(actual.getMetadata().getName().equals(desiredSecretName));
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/mysql-schema/src/main/java/io/quarkiverse/operatorsdk/samples/mysqlschema/dependent/SchemaDependentResource.java | samples/mysql-schema/src/main/java/io/quarkiverse/operatorsdk/samples/mysqlschema/dependent/SchemaDependentResource.java | package io.quarkiverse.operatorsdk.samples.mysqlschema.dependent;
import static io.quarkiverse.operatorsdk.samples.mysqlschema.dependent.SecretDependentResource.MYSQL_SECRET_PASSWORD;
import static io.quarkiverse.operatorsdk.samples.mysqlschema.dependent.SecretDependentResource.MYSQL_SECRET_USERNAME;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.Duration;
import java.util.Base64;
import java.util.Optional;
import java.util.Set;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import io.fabric8.kubernetes.api.model.Secret;
import io.javaoperatorsdk.operator.api.reconciler.Context;
import io.javaoperatorsdk.operator.api.reconciler.dependent.Deleter;
import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.ConfiguredDependentResource;
import io.javaoperatorsdk.operator.processing.dependent.Creator;
import io.javaoperatorsdk.operator.processing.dependent.external.PerResourcePollingDependentResource;
import io.quarkiverse.operatorsdk.samples.mysqlschema.MySQLSchema;
import io.quarkiverse.operatorsdk.samples.mysqlschema.schema.Schema;
import io.quarkiverse.operatorsdk.samples.mysqlschema.schema.SchemaService;
import io.quarkus.logging.Log;
@ApplicationScoped
public class SchemaDependentResource
extends PerResourcePollingDependentResource<Schema, MySQLSchema, String>
implements
ConfiguredDependentResource<ResourcePollerConfig>,
Creator<Schema, MySQLSchema>,
Deleter<MySQLSchema> {
@Inject
SchemaService schemaService;
public SchemaDependentResource() {
super(Schema.class);
}
@Override
public void configureWith(ResourcePollerConfig config) {
if (config != null) {
setPollingPeriod(Duration.ofSeconds(config.getPollPeriod()));
}
}
@Override
public Optional<ResourcePollerConfig> configuration() {
return Optional.of(new ResourcePollerConfig((int) getPollingPeriod().toSeconds()));
}
@Override
public Schema desired(MySQLSchema primary, Context<MySQLSchema> context) {
return new Schema(primary.getMetadata().getName(), primary.getSpec().getEncoding());
}
@Override
public Schema create(Schema target, MySQLSchema mySQLSchema, Context<MySQLSchema> context) {
Log.infof("Creating Schema: %s", target);
try (Connection connection = schemaService.getConnection()) {
final var secret = context.getSecondaryResource(Secret.class).orElseThrow();
var username = decode(secret.getData().get(MYSQL_SECRET_USERNAME));
var password = decode(secret.getData().get(MYSQL_SECRET_PASSWORD));
return schemaService.createSchemaAndRelatedUser(
connection,
target.getName(),
target.getCharacterSet(), username, password);
} catch (SQLException e) {
Log.error("Error while creating Schema", e);
throw new IllegalStateException(e);
}
}
@Override
public void delete(MySQLSchema primary, Context<MySQLSchema> context) {
Log.info("Delete schema");
try (Connection connection = schemaService.getConnection()) {
var userName = primary.getStatus() != null ? primary.getStatus().getUserName() : null;
schemaService.deleteSchemaAndRelatedUser(connection, primary.getMetadata().getName(),
userName);
} catch (SQLException e) {
throw new RuntimeException("Error while trying to delete Schema", e);
}
}
@Override
public Optional<Schema> getSecondaryResource(MySQLSchema primary, Context<MySQLSchema> context) {
try (Connection connection = schemaService.getConnection()) {
return schemaService.getSchema(connection, primary.getMetadata().getName());
} catch (SQLException e) {
throw new RuntimeException("Error while trying read Schema", e);
}
}
@Override
public Set<Schema> fetchResources(MySQLSchema primaryResource) {
return getSecondaryResource(primaryResource, null).map(Set::of).orElse(Set.of());
}
public static String decode(String value) {
return new String(Base64.getDecoder().decode(value.getBytes()));
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/external-crd/src/test/java/io/quarkiverse/operatorsdk/it/ExternalCRDTest.java | samples/external-crd/src/test/java/io/quarkiverse/operatorsdk/it/ExternalCRDTest.java | package io.quarkiverse.operatorsdk.it;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinition;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.javaoperatorsdk.operator.Operator;
import io.quarkus.test.junit.QuarkusTest;
@QuarkusTest
public class ExternalCRDTest {
@Inject
KubernetesClient unused; // needed to start kube dev service
@Inject
Operator operator;
@Test
void externalCRDIsDeployed() {
// start the operator
operator.start();
// external CRD should be deployed
var externalCRD = operator.getKubernetesClient()
.resources(CustomResourceDefinition.class)
.withName("externals.halkyon.io")
.get();
Assertions.assertNotNull(externalCRD);
operator.stop();
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/external-crd/src/main/java/io/quarkiverse/operatorsdk/ExternalCRDReconciler.java | samples/external-crd/src/main/java/io/quarkiverse/operatorsdk/ExternalCRDReconciler.java | package io.quarkiverse.operatorsdk;
import io.fabric8.kubernetes.api.model.Pod;
import io.javaoperatorsdk.operator.api.reconciler.Context;
import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration;
import io.javaoperatorsdk.operator.api.reconciler.Reconciler;
import io.javaoperatorsdk.operator.api.reconciler.UpdateControl;
@ControllerConfiguration(name = ExternalCRDReconciler.NAME)
public class ExternalCRDReconciler implements Reconciler<Pod> {
public static final String NAME = "externalcrd";
@Override
public UpdateControl<Pod> reconcile(Pod pod, Context<Pod> context) {
return null;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/exposedapp/src/test/java/io/halkyon/ExposedAppReconcilerTest.java | samples/exposedapp/src/test/java/io/halkyon/ExposedAppReconcilerTest.java | package io.halkyon;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import java.util.concurrent.TimeUnit;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import io.fabric8.kubernetes.api.model.ObjectMetaBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.quarkus.test.junit.QuarkusTest;
@QuarkusTest
class ExposedAppReconcilerTest {
public static final String TEST_APP = "test-app";
@Inject
protected KubernetesClient client;
@Test
void reconcileShouldWork() {
final var app = new ExposedApp();
final var metadata = new ObjectMetaBuilder()
.withName(TEST_APP)
.withNamespace(client.getNamespace())
.build();
app.setMetadata(metadata);
app.getSpec().setImageRef("group/imageName:tag");
client.resource(app).create();
await().ignoreException(NullPointerException.class).atMost(10, TimeUnit.SECONDS).untilAsserted(() -> {
// check that we create the deployment
final var deployment = client.apps().deployments()
.inNamespace(metadata.getNamespace())
.withName(metadata.getName()).get();
final var maybeFirstContainer = deployment.getSpec().getTemplate().getSpec().getContainers()
.stream()
.findFirst();
assertThat(maybeFirstContainer.isPresent(), is(true));
final var firstContainer = maybeFirstContainer.get();
assertThat(firstContainer.getImage(), is(app.getSpec().getImageRef()));
// check that the service is created
final var service = client.services()
.inNamespace(metadata.getNamespace())
.withName(metadata.getName()).get();
final var port = service.getSpec().getPorts().get(0).getPort();
assertThat(port, is(8080));
// check that the ingress is created
final var ingress = client.network().v1().ingresses()
.inNamespace(metadata.getNamespace()).withName(metadata.getName()).get();
// not using nginx controller on k3s
/*
* final var annotations = ingress.getMetadata().getAnnotations();
* assertThat(annotations.size(), is(2));
* assertThat(annotations.get("kubernetes.io/ingress.class"), is("nginx"));
*/
final var rules = ingress.getSpec().getRules();
assertThat(rules.size(), is(1));
final var paths = rules.get(0).getHttp().getPaths();
assertThat(paths.size(), is(1));
final var path = paths.get(0);
assertThat(path.getPath(), is("/"));
assertThat(path.getPathType(), is("Prefix"));
final var serviceBackend = path.getBackend().getService();
assertThat(serviceBackend.getName(), is(service.getMetadata().getName()));
assertThat(serviceBackend.getPort().getNumber(), is(port));
});
client.resource(app).delete();
await().atMost(60, TimeUnit.SECONDS).untilAsserted(() -> {
assertThat(client.apps().deployments()
.inNamespace(metadata.getNamespace())
.withName(metadata.getName()).get(), nullValue());
assertThat(client.services()
.inNamespace(metadata.getNamespace())
.withName(metadata.getName()).get(), nullValue());
assertThat(client.network().v1().ingresses()
.inNamespace(metadata.getNamespace())
.withName(metadata.getName()).get(), nullValue());
});
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/exposedapp/src/test/java/io/halkyon/HelmDeploymentE2EIT.java | samples/exposedapp/src/test/java/io/halkyon/HelmDeploymentE2EIT.java | package io.halkyon;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import jakarta.annotation.PostConstruct;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
import org.junit.jupiter.api.extension.ExecutionCondition;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.ExtensionContext;
import io.fabric8.kubernetes.api.model.Namespace;
import io.fabric8.kubernetes.api.model.ObjectMetaBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.javaoperatorsdk.operator.api.reconciler.Constants;
import io.quarkus.test.junit.QuarkusTest;
@QuarkusTest
@ExtendWith(HelmDeploymentE2EIT.RunOnlyIfHelmIsAvailableCondition.class)
class HelmDeploymentE2EIT {
final static Logger log = Logger.getLogger(HelmDeploymentE2EIT.class);
static class RunOnlyIfHelmIsAvailableCondition implements ExecutionCondition {
private static boolean helmIsAvailable = false;
RunOnlyIfHelmIsAvailableCondition() {
try {
Process exec = Runtime.getRuntime().exec("helm");
if (exec.waitFor() == 0) {
helmIsAvailable = true;
}
} catch (Exception e) {
// ignore
}
}
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
if (helmIsAvailable) {
return ConditionEvaluationResult.enabled("Helm is available");
} else {
log.info("Helm is not available, skipping this test");
return ConditionEvaluationResult.disabled("Helm is not available");
}
}
}
public static final String TEST_RESOURCE = "test1";
public static final String DEPLOYMENT_NAME = "quarkus-operator-sdk-samples-exposedapp";
public static final String DEFAULT_NAMESPACE = "default";
public static final String WATCH_NAMESPACES_KEY = "app.envs.QUARKUS_OPERATOR_SDK_CONTROLLERS_EXPOSEDAPP_NAMESPACES";
@Inject
KubernetesClient client;
private String namespace;
private File kubeConfigFile;
@PostConstruct
public void init() {
kubeConfigFile = KubeUtils.generateConfigFromClient(client);
}
@AfterEach
void cleanup() {
deleteHelmDeployment();
}
@Test
void testClusterWideDeployment() {
deployWithHelm();
log.info("Deploying test resource in clusterscopetest namespace");
namespace = "clusterscopetest";
createNamespace(namespace);
client.resource(testResource(namespace)).create();
checkResourceProcessed(namespace);
ensureResourceDeleted(testResource(namespace));
}
@Test
void testWatchingCurrentNamespace() {
deployWithHelm(WATCH_NAMESPACES_KEY, Constants.WATCH_CURRENT_NAMESPACE);
namespace = "own-ns-test";
createNamespace(namespace);
client.resource(testResource(namespace)).create();
checkResourceNotProcessed(namespace);
// resource is reconciled in default namespace where controller runs
client.resource(testResource(DEFAULT_NAMESPACE)).create();
checkResourceProcessed(DEFAULT_NAMESPACE);
ensureResourceDeleted(testResource(namespace));
ensureResourceDeleted(testResource(DEFAULT_NAMESPACE));
}
@Test
void testWatchingSetOfNamespaces() {
String excludedNS = "excludedns1";
String ns1 = "testns1";
String ns2 = "testns2";
createNamespace(excludedNS);
createNamespace(ns1);
createNamespace(ns2);
deployWithHelm(WATCH_NAMESPACES_KEY, ns1 + "\\," + ns2);
client.resource(testResource(excludedNS)).create();
checkResourceNotProcessed(excludedNS);
client.resource(testResource(ns1)).create();
client.resource(testResource(ns2)).create();
checkResourceProcessed(ns1);
checkResourceProcessed(ns2);
ensureResourceDeleted(testResource(ns1));
ensureResourceDeleted(testResource(ns2));
ensureResourceDeleted(testResource(excludedNS));
}
private void ensureResourceDeleted(ExposedApp resource) {
client.resource(resource).delete();
await().atMost(15, TimeUnit.SECONDS).untilAsserted(() -> {
var exposedApp = client.resources(ExposedApp.class)
.inNamespace(resource.getMetadata().getNamespace())
.withName(resource.getMetadata().getName()).get();
assertThat(exposedApp, is(nullValue()));
});
}
private void checkResourceNotProcessed(String namespace) {
await("Resource not reconciled in other namespace")
.pollDelay(Duration.ofSeconds(5)).untilAsserted(() -> {
var exposedApp = client.resources(ExposedApp.class)
.inNamespace(namespace)
.withName(TEST_RESOURCE).get();
assertThat(exposedApp, is(notNullValue()));
assertThat(exposedApp.getStatus().getMessage(), equalTo("reconciled-not-exposed"));
});
}
private void checkResourceProcessed(String namespace) {
await().atMost(15, TimeUnit.SECONDS).untilAsserted(() -> {
var exposedApp = client.resources(ExposedApp.class)
.inNamespace(namespace)
.withName(TEST_RESOURCE).get();
assertThat(exposedApp, is(notNullValue()));
assertThat(exposedApp.getStatus().getMessage(), anyOf(equalTo("exposed"), equalTo("reconciled-not-exposed")));
});
}
ExposedApp testResource(String namespace) {
var app = new ExposedApp();
app.setMetadata(new ObjectMetaBuilder()
.withName(TEST_RESOURCE)
.withNamespace(namespace)
.build());
app.setSpec(new ExposedAppSpec());
app.getSpec().setImageRef("nginx:1.14.2");
return app;
}
private void createNamespace(String namespace) {
var ns = new Namespace();
ns.setMetadata(new ObjectMetaBuilder()
.withName(namespace)
.build());
if (client.namespaces().resource(ns).get() == null) {
client.namespaces().resource(ns).create();
}
}
private void deployWithHelm(String... values) {
StringBuilder command = createHelmCommand("helm install exposedapp target/helm/kubernetes/" + DEPLOYMENT_NAME);
for (int i = 0; i < values.length; i = i + 2) {
command.append(" --set ").append(values[i]).append("=").append(values[i + 1]);
}
execHelmCommand(command.toString());
client.apps().deployments().inNamespace(DEFAULT_NAMESPACE).withName(DEPLOYMENT_NAME)
.waitUntilReady(120, TimeUnit.SECONDS);
}
private StringBuilder createHelmCommand(String command) {
return new StringBuilder()
.append(command)
.append(" --kubeconfig ").append(kubeConfigFile.getPath());
}
private void deleteHelmDeployment() {
execHelmCommand(createHelmCommand("helm delete exposedapp").toString());
await().untilAsserted(() -> {
var deployment = client.apps().deployments().inNamespace(DEFAULT_NAMESPACE).withName(DEPLOYMENT_NAME).get();
assertThat(deployment, is(nullValue()));
});
// CRDs are not deleted automatically by helm, so we need to delete them manually
client.apiextensions().v1().customResourceDefinitions().withName("exposedapps.halkyon.io").delete();
}
private static void execHelmCommand(String command) {
log.infof("Executing command: %s", command);
execHelmCommand(command, false);
}
private static void execHelmCommand(String command, boolean silent) {
try {
var process = Runtime.getRuntime().exec(command);
var exitCode = process.waitFor();
if (exitCode != 0) {
log.infof("Error with helm: %s", new String(process.getErrorStream().readAllBytes()));
if (!silent) {
throw new IllegalStateException("Helm exit code: " + exitCode);
}
}
} catch (IOException | InterruptedException e) {
throw new IllegalStateException(e);
}
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/exposedapp/src/test/java/io/halkyon/NativeExposedAppReconcilerIT.java | samples/exposedapp/src/test/java/io/halkyon/NativeExposedAppReconcilerIT.java | package io.halkyon;
import org.junit.jupiter.api.Disabled;
import io.quarkus.test.junit.QuarkusIntegrationTest;
@QuarkusIntegrationTest
@Disabled("Currently not possible to inject the dev service-provided k8s client in native app")
public class NativeExposedAppReconcilerIT extends ExposedAppReconcilerTest {
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/exposedapp/src/test/java/io/halkyon/KubeUtils.java | samples/exposedapp/src/test/java/io/halkyon/KubeUtils.java | package io.halkyon;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import io.fabric8.kubernetes.api.model.AuthInfo;
import io.fabric8.kubernetes.api.model.Cluster;
import io.fabric8.kubernetes.api.model.Config;
import io.fabric8.kubernetes.api.model.Context;
import io.fabric8.kubernetes.api.model.NamedAuthInfo;
import io.fabric8.kubernetes.api.model.NamedCluster;
import io.fabric8.kubernetes.api.model.NamedContext;
import io.fabric8.kubernetes.client.KubernetesClient;
public class KubeUtils {
public static final String HELM_TEST = "helmtest";
public static File generateConfigFromClient(KubernetesClient client) {
try {
var actualConfig = client.getConfiguration();
Config res = new Config();
res.setApiVersion("v1");
res.setKind("Config");
res.setClusters(createCluster(actualConfig));
res.setContexts(createContext(actualConfig));
res.setUsers(createUser(actualConfig));
res.setCurrentContext(HELM_TEST);
File targetFile = new File("target", "devservice-kubeconfig.yaml");
String yaml = client.getKubernetesSerialization().asYaml(res);
Files.writeString(targetFile.toPath(), yaml);
return targetFile;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static List<NamedAuthInfo> createUser(io.fabric8.kubernetes.client.Config actualConfig) {
var user = new NamedAuthInfo();
user.setName(HELM_TEST);
user.setUser(new AuthInfo());
user.getUser().setClientCertificateData(actualConfig.getClientCertData());
user.getUser().setClientKeyData(actualConfig.getClientKeyData());
user.getUser().setPassword(actualConfig.getPassword());
return List.of(user);
}
private static List<NamedContext> createContext(io.fabric8.kubernetes.client.Config actualConfig) {
var context = new NamedContext();
context.setName(HELM_TEST);
context.setContext(new Context());
context.getContext().setCluster(HELM_TEST);
context.getContext().setUser(HELM_TEST);
context.getContext().setNamespace(actualConfig.getNamespace());
return List.of(context);
}
private static List<NamedCluster> createCluster(io.fabric8.kubernetes.client.Config actualConfig) {
var cluster = new NamedCluster();
cluster.setName(HELM_TEST);
cluster.setCluster(new Cluster());
cluster.getCluster().setServer(actualConfig.getMasterUrl());
cluster.getCluster().setCertificateAuthorityData(actualConfig.getCaCertData());
return List.of(cluster);
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/exposedapp/src/main/java/io/halkyon/ExposedApp.java | samples/exposedapp/src/main/java/io/halkyon/ExposedApp.java | package io.halkyon;
import io.fabric8.kubernetes.api.model.Namespaced;
import io.fabric8.kubernetes.client.CustomResource;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Version;
@Version("v1alpha1")
@Group("halkyon.io")
public class ExposedApp extends CustomResource<ExposedAppSpec, ExposedAppStatus> implements Namespaced {
@Override
protected ExposedAppSpec initSpec() {
return new ExposedAppSpec();
}
@Override
protected ExposedAppStatus initStatus() {
return new ExposedAppStatus();
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/exposedapp/src/main/java/io/halkyon/ExposedAppReconciler.java | samples/exposedapp/src/main/java/io/halkyon/ExposedAppReconciler.java | package io.halkyon;
import static io.javaoperatorsdk.operator.api.reconciler.Constants.WATCH_ALL_NAMESPACES;
import java.time.Duration;
import java.util.Map;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.ObjectMetaBuilder;
import io.fabric8.kubernetes.api.model.networking.v1.Ingress;
import io.javaoperatorsdk.operator.api.config.informer.Informer;
import io.javaoperatorsdk.operator.api.reconciler.*;
import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent;
import io.javaoperatorsdk.operator.processing.dependent.workflow.WorkflowReconcileResult;
import io.quarkiverse.operatorsdk.annotations.CSVMetadata;
import io.quarkus.logging.Log;
@Workflow(dependents = {
@Dependent(type = DeploymentDependent.class),
@Dependent(name = "service", type = ServiceDependent.class),
@Dependent(type = IngressDependent.class, readyPostcondition = IngressDependent.class)
})
@ControllerConfiguration(informer = @Informer(namespaces = WATCH_ALL_NAMESPACES), name = "exposedapp")
@CSVMetadata(displayName = "ExposedApp operator", description = "A sample operator that shows how to use JOSDK's main features with the Quarkus extension")
public class ExposedAppReconciler implements Reconciler<ExposedApp>,
ContextInitializer<ExposedApp> {
static final String APP_LABEL = "app.kubernetes.io/name";
static final String LABELS_CONTEXT_KEY = "labels";
public ExposedAppReconciler() {
}
@Override
public void initContext(ExposedApp exposedApp, Context context) {
final var labels = Map.of(APP_LABEL, exposedApp.getMetadata().getName());
context.managedWorkflowAndDependentResourceContext().put(LABELS_CONTEXT_KEY, labels);
}
@Override
public UpdateControl<ExposedApp> reconcile(ExposedApp exposedApp, Context<ExposedApp> context) {
final var name = exposedApp.getMetadata().getName();
// retrieve the workflow reconciliation result and re-schedule if we have dependents that are not yet ready
final var wrs = context.managedWorkflowAndDependentResourceContext().getWorkflowReconcileResult();
if (wrs.map(WorkflowReconcileResult::allDependentResourcesReady).orElse(false)) {
final var url = IngressDependent.getExposedURL(
context.getSecondaryResource(Ingress.class).orElseThrow());
exposedApp.setStatus(new ExposedAppStatus(url, exposedApp.getSpec().getEndpoint()));
Log.infof("App %s is exposed and ready to be used at %s", name, exposedApp.getStatus().getHost());
return UpdateControl.patchStatus(exposedApp);
} else {
exposedApp.setStatus(new ExposedAppStatus(null, null));
final var duration = Duration.ofSeconds(1);
Log.infof("App %s is not ready yet, rescheduling reconciliation after %ss", name, duration.toSeconds());
return UpdateControl.patchStatus(exposedApp).rescheduleAfter(duration);
}
}
static ObjectMeta createMetadata(ExposedApp resource, Map<String, String> labels) {
final var metadata = resource.getMetadata();
return new ObjectMetaBuilder()
.withName(metadata.getName())
.withNamespace(metadata.getNamespace())
.withLabels(labels)
.build();
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/exposedapp/src/main/java/io/halkyon/ExposedAppSpec.java | samples/exposedapp/src/main/java/io/halkyon/ExposedAppSpec.java | package io.halkyon;
import java.util.Collections;
import java.util.Map;
public class ExposedAppSpec {
// Add Spec information here
private String imageRef;
private Map<String, String> env;
private String endpoint;
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getImageRef() {
return imageRef;
}
public void setImageRef(String imageRef) {
this.imageRef = imageRef;
}
public Map<String, String> getEnv() {
return env == null ? Collections.emptyMap() : env;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/exposedapp/src/main/java/io/halkyon/IngressDependent.java | samples/exposedapp/src/main/java/io/halkyon/IngressDependent.java | package io.halkyon;
import static io.halkyon.ExposedAppReconciler.LABELS_CONTEXT_KEY;
import static io.halkyon.ExposedAppReconciler.createMetadata;
import java.util.Map;
import io.fabric8.kubernetes.api.model.networking.v1.Ingress;
import io.fabric8.kubernetes.api.model.networking.v1.IngressBuilder;
import io.javaoperatorsdk.operator.api.reconciler.Context;
import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource;
import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource;
import io.javaoperatorsdk.operator.processing.dependent.workflow.Condition;
public class IngressDependent extends CRUDKubernetesDependentResource<Ingress, ExposedApp> implements
Condition<Ingress, ExposedApp> {
// todo: automatically generate
public IngressDependent() {
super(Ingress.class);
}
@Override
@SuppressWarnings("unchecked")
public Ingress desired(ExposedApp exposedApp, Context context) {
final var labels = (Map<String, String>) context.managedWorkflowAndDependentResourceContext()
.getMandatory(LABELS_CONTEXT_KEY, Map.class);
final var metadata = createMetadata(exposedApp, labels);
/*
* metadata.setAnnotations(Map.of(
* "nginx.ingress.kubernetes.io/rewrite-target", "/",
* "kubernetes.io/ingress.class", "nginx"));
*/
return new IngressBuilder()
.withMetadata(metadata)
.withNewSpec()
.addNewRule()
.withNewHttp()
.addNewPath()
.withPath("/")
.withPathType("Prefix")
.withNewBackend()
.withNewService()
.withName(metadata.getName())
.withNewPort().withNumber(8080).endPort()
.endService()
.endBackend()
.endPath()
.endHttp()
.endRule()
.endSpec()
.build();
}
/**
* Assumes Ingress is ready as determined by {@link #isMet(DependentResource, ExposedApp, Context)}
*
* @param ingress the ingress
* @return the URL exposed by the specified Ingress
*/
static String getExposedURL(Ingress ingress) {
final var status = ingress.getStatus();
final var ingresses = status.getLoadBalancer().getIngress();
var ing = ingresses.get(0);
String hostname = ing.getHostname();
return "https://" + (hostname != null ? hostname : ing.getIp());
}
@Override
public boolean isMet(DependentResource<Ingress, ExposedApp> dependentResource,
ExposedApp exposedApp, Context<ExposedApp> context) {
return context.getSecondaryResource(Ingress.class).map(in -> {
final var status = in.getStatus();
if (status != null) {
final var ingresses = status.getLoadBalancer().getIngress();
// only set the status if the ingress is ready to provide the info we need
return ingresses != null && !ingresses.isEmpty();
}
return false;
}).orElse(false);
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/exposedapp/src/main/java/io/halkyon/ServiceDependent.java | samples/exposedapp/src/main/java/io/halkyon/ServiceDependent.java | package io.halkyon;
import static io.halkyon.ExposedAppReconciler.LABELS_CONTEXT_KEY;
import static io.halkyon.ExposedAppReconciler.createMetadata;
import java.util.Map;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServiceBuilder;
import io.javaoperatorsdk.operator.api.reconciler.Context;
import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource;
public class ServiceDependent extends CRUDKubernetesDependentResource<Service, ExposedApp> {
// todo: automatically generate
public ServiceDependent() {
super(Service.class);
}
@Override
@SuppressWarnings("unchecked")
public Service desired(ExposedApp exposedApp, Context context) {
final var labels = (Map<String, String>) context.managedWorkflowAndDependentResourceContext()
.getMandatory(LABELS_CONTEXT_KEY, Map.class);
return new ServiceBuilder()
.withMetadata(createMetadata(exposedApp, labels))
.withNewSpec()
.addNewPort()
.withName("http")
.withPort(8080)
.withNewTargetPort().withValue(8080).endTargetPort()
.endPort()
.withSelector(labels)
.withType("ClusterIP")
.endSpec()
.build();
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/exposedapp/src/main/java/io/halkyon/DeploymentDependent.java | samples/exposedapp/src/main/java/io/halkyon/DeploymentDependent.java | package io.halkyon;
import static io.halkyon.ExposedAppReconciler.LABELS_CONTEXT_KEY;
import static io.halkyon.ExposedAppReconciler.createMetadata;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.fabric8.kubernetes.api.model.EnvVar;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder;
import io.javaoperatorsdk.operator.api.reconciler.Context;
import io.javaoperatorsdk.operator.processing.dependent.Matcher;
import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource;
public class DeploymentDependent extends CRUDKubernetesDependentResource<Deployment, ExposedApp>
implements Matcher<Deployment, ExposedApp> {
// todo: automatically generate
public DeploymentDependent() {
super(Deployment.class);
}
@SuppressWarnings("unchecked")
public Deployment desired(ExposedApp exposedApp, Context context) {
final var labels = (Map<String, String>) context.managedWorkflowAndDependentResourceContext()
.getMandatory(LABELS_CONTEXT_KEY, Map.class);
final var name = exposedApp.getMetadata().getName();
final var spec = exposedApp.getSpec();
final var imageRef = spec.getImageRef();
final var env = spec.getEnv();
var containerBuilder = new DeploymentBuilder()
.withMetadata(createMetadata(exposedApp, labels))
.withNewSpec()
.withNewSelector().withMatchLabels(labels).endSelector()
.withNewTemplate()
.withNewMetadata().withLabels(labels).endMetadata()
.withNewSpec()
.addNewContainer()
.withName(name).withImage(imageRef);
// add env variables
if (env != null) {
env.forEach((key, value) -> containerBuilder.addNewEnv()
.withName(key.toUpperCase())
.withValue(value)
.endEnv());
}
return containerBuilder
.addNewPort()
.withName("http").withProtocol("TCP").withContainerPort(8080)
.endPort()
.endContainer()
.endSpec()
.endTemplate()
.endSpec()
.build();
}
@Override
public Result<Deployment> match(Deployment actual, ExposedApp primary, Context<ExposedApp> context) {
final var desiredSpec = primary.getSpec();
final var container = actual.getSpec().getTemplate().getSpec().getContainers()
.stream()
.findFirst();
return Result.nonComputed(container.map(c -> c.getImage().equals(desiredSpec.getImageRef())
&& desiredSpec.getEnv().equals(convert(c.getEnv()))).orElse(false));
}
private Map<String, String> convert(List<EnvVar> envVars) {
final var result = new HashMap<String, String>(envVars.size());
envVars.forEach(e -> result.put(e.getName(), e.getValue()));
return result;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/samples/exposedapp/src/main/java/io/halkyon/ExposedAppStatus.java | samples/exposedapp/src/main/java/io/halkyon/ExposedAppStatus.java | package io.halkyon;
@SuppressWarnings("unused")
public class ExposedAppStatus {
private String host;
private String message;
public ExposedAppStatus() {
message = "processing";
}
public ExposedAppStatus(String hostname, String endpoint) {
if (hostname == null || endpoint == null) {
this.message = "reconciled-not-exposed";
} else {
this.message = "exposed";
this.host = endpoint != null && !endpoint.isBlank() ? hostname + '/' + endpoint : hostname;
}
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/common/src/main/java/io/quarkiverse/operatorsdk/common/ClassLoadingUtils.java | common/src/main/java/io/quarkiverse/operatorsdk/common/ClassLoadingUtils.java | package io.quarkiverse.operatorsdk.common;
import java.lang.reflect.InvocationTargetException;
public class ClassLoadingUtils {
private ClassLoadingUtils() {
}
@SuppressWarnings({ "unchecked", "unused" })
public static <T> Class<T> loadClass(String className, Class<T> expected) {
try {
return (Class<T>) Thread.currentThread().getContextClassLoader().loadClass(className);
} catch (Exception e) {
throw new IllegalArgumentException("Couldn't find class " + className, e);
}
}
public static <T> T instantiate(Class<T> toInstantiate) {
try {
final var constructor = toInstantiate.getConstructor();
constructor.setAccessible(true);
return constructor.newInstance();
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new IllegalArgumentException("Couldn't instantiate " + toInstantiate.getName(),
e);
}
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/common/src/main/java/io/quarkiverse/operatorsdk/common/Files.java | common/src/main/java/io/quarkiverse/operatorsdk/common/Files.java | package io.quarkiverse.operatorsdk.common;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.spi.FileSystemProvider;
import java.util.Collections;
import java.util.Map;
import io.quarkus.qute.Qute;
import io.quarkus.qute.TemplateException;
import io.quarkus.qute.TemplateInstance;
public class Files {
private static final String API_TEMPLATES_PATH = "templates/cli/api";
private static final String ROOT_TARGET_DIR = "src/main/java/";
private Files() {
}
public interface MessageWriter {
default void write(String message) {
write(message, null, false);
}
default void error(String message) {
error(message, null);
}
default void error(String message, Exception e) {
write(message, e, true);
}
default void write(String message, Exception e, boolean forError) {
final var writer = forError ? System.err : System.out;
writer.println(formatMessageWithException(message, e));
}
default String formatMessageWithException(String message, Exception e) {
return message + (e != null ? ": " + exceptionAsString(e) : "");
}
}
public static boolean generateAPIFiles(String group, String version, String kind, MessageWriter messager) {
final var packageName = reversePeriodSeparatedString(group);
final var finalKind = capitalizeIfNeeded(kind);
final var targetDir = ROOT_TARGET_DIR + packageName.replace('.', '/') + "/";
try {
java.nio.file.Files.createDirectories(Paths.get(targetDir));
} catch (IOException e) {
messager.error("Couldn't create target directory " + targetDir, e);
return false;
}
final var apiTemplatesDir = Thread.currentThread().getContextClassLoader().getResource(API_TEMPLATES_PATH);
if (apiTemplatesDir == null) {
messager.error("Couldn't find " + API_TEMPLATES_PATH + " directory in resources");
return false;
}
// make sure we can get the files from a jar, which, for some reason, doesn't work directly
// see https://stackoverflow.com/questions/22605666/java-access-files-in-jar-causes-java-nio-file-filesystemnotfoundexception
final URI apiTemplatesDirURI;
try {
apiTemplatesDirURI = apiTemplatesDir.toURI();
} catch (URISyntaxException e) {
messager.error("Couldn't convert " + apiTemplatesDir + " path to URI", e);
return false;
}
if ("jar".equals(apiTemplatesDirURI.getScheme())) {
for (FileSystemProvider provider : FileSystemProvider.installedProviders()) {
if (provider.getScheme().equalsIgnoreCase("jar")) {
try {
provider.getFileSystem(apiTemplatesDirURI);
} catch (FileSystemNotFoundException e) {
// if for some reason, there's no file system for our jar, initialize it first
try {
provider.newFileSystem(apiTemplatesDirURI, Collections.emptyMap());
} catch (IOException ex) {
messager.error("Couldn't initialize FileSystem instance to read resources", e);
return false;
}
}
}
}
}
final var data = Map.<String, Object> of("packageName", packageName,
"group", group,
"version", version,
"kind", finalKind);
final var apiTemplatesPath = Paths.get(apiTemplatesDirURI);
try (var paths = java.nio.file.Files.walk(apiTemplatesPath)) {
paths.filter(f -> java.nio.file.Files.isRegularFile(f) && f.getFileName().toString().endsWith(".qute"))
.forEach(path -> {
try {
final var templateAsString = java.nio.file.Files.readString(path);
final var templateInstance = Qute.fmt(templateAsString)
.dataMap(data).instance();
generateFile(path, templateInstance, finalKind, targetDir, messager);
} catch (TemplateException e) {
throw new RuntimeException("Couldn't render " + path + " template", e.getCause());
} catch (Exception e) {
throw new RuntimeException(e);
}
});
} catch (Exception e) {
messager.error(e.getCause().getMessage(), e);
return false;
}
return true;
}
private static String exceptionAsString(Exception e) {
var stringWriter = new StringWriter();
e.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.toString();
}
private static void generateFile(Path path, TemplateInstance templateInstance, String kind, String targetDir,
MessageWriter messager)
throws IOException {
final var id = path.getFileName().toString();
var className = getClassNameFor(id, kind);
final var file = new File(targetDir + className + ".java");
if (file.exists()) {
throw new IllegalArgumentException(file + " already exists");
}
try (var writer = new PrintWriter(file, StandardCharsets.UTF_8)) {
writer.print(templateInstance.render());
}
messager.write("Generated " + file);
}
private static String getClassNameFor(String id, String kind) {
id = id.substring(0, id.lastIndexOf('.'));
return "resource".equals(id) ? kind : kind + capitalizeIfNeeded(id);
}
private static String reversePeriodSeparatedString(String input) {
String[] splitString = input.split("\\.");
StringBuilder sb = new StringBuilder();
for (int i = splitString.length - 1; i >= 0; i--) {
sb.append(splitString[i]);
if (i > 0) {
sb.append(".");
}
}
return sb.toString();
}
private static String capitalizeIfNeeded(String input) {
final var firstChar = input.charAt(0);
return Character.isUpperCase(firstChar) ? input : Character.toUpperCase(firstChar) + input.substring(1);
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/common/src/main/java/io/quarkiverse/operatorsdk/common/CLIConstants.java | common/src/main/java/io/quarkiverse/operatorsdk/common/CLIConstants.java | package io.quarkiverse.operatorsdk.common;
public class CLIConstants {
public static final String API_DESCRIPTION = "Creates a Kubernetes API based on a Fabric8 CustomResource along with the associated JOSDK Reconciler";
public static final char API_KIND_SHORT = 'k';
public static final String API_KIND = "kind";
public static final String API_KIND_DESCRIPTION = "Your API's kind, used to generate a CustomResource class with associated spec, status and Reconciler classes";
public static final char API_VERSION_SHORT = 'v';
public static final String API_VERSION = "version";
public static final String API_VERSION_DESCRIPTION = "Your API's version, e.g. v1beta1";
public static final char API_GROUP_SHORT = 'g';
public static final String API_GROUP = "group";
public static final String API_GROUP_DESCRIPTION = "Your API's group, e.g. halkyon.io, this will also be used, reversed, as package name for the generated classes";
private CLIConstants() {
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/helm/deployment/src/test/java/io/quarkiverse/operatorsdk/helm/deployment/test/HelmChartGeneratorTest.java | helm/deployment/src/test/java/io/quarkiverse/operatorsdk/helm/deployment/test/HelmChartGeneratorTest.java | package io.quarkiverse.operatorsdk.helm.deployment.test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import java.io.File;
import java.nio.file.Path;
import java.util.Objects;
import org.hamcrest.io.FileMatchers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.quarkiverse.operatorsdk.helm.deployment.test.sources.SimpleCR;
import io.quarkiverse.operatorsdk.helm.deployment.test.sources.SimpleReconciler;
import io.quarkiverse.operatorsdk.helm.deployment.test.sources.SimpleSpec;
import io.quarkiverse.operatorsdk.helm.deployment.test.sources.SimpleStatus;
import io.quarkus.test.ProdBuildResults;
import io.quarkus.test.ProdModeTestResults;
import io.quarkus.test.QuarkusProdModeTest;
class HelmChartGeneratorTest {
private static final String APP_NAME = "helm-chart-test";
@RegisterExtension
static final QuarkusProdModeTest config = new QuarkusProdModeTest()
.setApplicationName(APP_NAME)
.withApplicationRoot(
(jar) -> jar.addClasses(SimpleReconciler.class, SimpleCR.class, SimpleSpec.class, SimpleStatus.class));
@ProdBuildResults
private ProdModeTestResults prodModeTestResults;
@Test
void generatesHelmChart() {
Path buildDir = prodModeTestResults.getBuildDir();
var helmDir = buildDir.resolve("helm")
.resolve("kubernetes")
.resolve(APP_NAME).toFile();
assertThat(new File(helmDir, "Chart.yaml"), FileMatchers.anExistingFile());
assertThat(new File(helmDir, "values.yaml"), FileMatchers.anExistingFile());
assertThat(Objects.requireNonNull(new File(helmDir, "templates").listFiles()).length,
greaterThanOrEqualTo(7));
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/helm/deployment/src/test/java/io/quarkiverse/operatorsdk/helm/deployment/test/HelmChartWatchAllNamespacesGeneratorTest.java | helm/deployment/src/test/java/io/quarkiverse/operatorsdk/helm/deployment/test/HelmChartWatchAllNamespacesGeneratorTest.java | package io.quarkiverse.operatorsdk.helm.deployment.test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.hasSize;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
import org.hamcrest.io.FileMatchers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.quarkiverse.operatorsdk.common.FileUtils;
import io.quarkiverse.operatorsdk.helm.deployment.test.sources.SimpleCR;
import io.quarkiverse.operatorsdk.helm.deployment.test.sources.SimpleSpec;
import io.quarkiverse.operatorsdk.helm.deployment.test.sources.SimpleStatus;
import io.quarkiverse.operatorsdk.helm.deployment.test.sources.WatchAllNamespacesReconciler;
import io.quarkus.test.ProdBuildResults;
import io.quarkus.test.ProdModeTestResults;
import io.quarkus.test.QuarkusProdModeTest;
class HelmChartWatchAllNamespacesGeneratorTest {
private static final String APP_NAME = "helm-chart-test-all-namespaces";
@RegisterExtension
static final QuarkusProdModeTest config = new QuarkusProdModeTest()
.setApplicationName(APP_NAME)
.withApplicationRoot(
(jar) -> jar.addClasses(WatchAllNamespacesReconciler.class, SimpleCR.class,
SimpleSpec.class, SimpleStatus.class))
// Generate some custom resources to test that they get properly included in the Helm chart
// ServiceAccount
.overrideConfigKey("quarkus.kubernetes.rbac.service-accounts.service-account-custom.namespace", "custom-ns")
// Role
.overrideConfigKey("quarkus.kubernetes.rbac.roles.role-custom.policy-rules.0.api-groups", "extensions,apps")
.overrideConfigKey("quarkus.kubernetes.rbac.roles.role-custom.policy-rules.0.resources", "deployments")
.overrideConfigKey("quarkus.kubernetes.rbac.roles.role-custom.policy-rules.0.verbs", "get,watch,list")
// RoleBinding
.overrideConfigKey("quarkus.kubernetes.rbac.role-bindings.role-binding-custom.subjects.service-account-custom.kind",
"ServiceAccount")
.overrideConfigKey(
"quarkus.kubernetes.rbac.role-bindings.role-binding-custom.subjects.service-account-custom.namespace",
"custom-ns")
.overrideConfigKey("quarkus.kubernetes.rbac.role-bindings.role-binding-custom.role-name", "role-custom")
// ClusterRole
.overrideConfigKey("quarkus.kubernetes.rbac.cluster-roles.cluster-role-custom.policy-rules.0.api-groups",
"extensions,apps")
.overrideConfigKey("quarkus.kubernetes.rbac.cluster-roles.cluster-role-custom.policy-rules.0.resources",
"deployments")
.overrideConfigKey("quarkus.kubernetes.rbac.cluster-roles.cluster-role-custom.policy-rules.0.verbs",
"get,watch,list")
// ClusterRoleBinding
.overrideConfigKey(
"quarkus.kubernetes.rbac.cluster-role-bindings.cluster-role-binding-custom.subjects.manager.kind", "Group")
.overrideConfigKey(
"quarkus.kubernetes.rbac.cluster-role-bindings.cluster-role-binding-custom.subjects.manager.api-group",
"rbac.authorization.k8s.io")
.overrideConfigKey("quarkus.kubernetes.rbac.cluster-role-bindings.cluster-role-binding-custom.role-name",
"custom-cluster-role");
@ProdBuildResults
private ProdModeTestResults prodModeTestResults;
@Test
void generatesHelmChart() throws IOException {
Path buildDir = prodModeTestResults.getBuildDir();
var helmDir = buildDir.resolve("helm")
.resolve("kubernetes")
.resolve(APP_NAME).toFile();
assertThat(new File(helmDir, "Chart.yaml"), FileMatchers.anExistingFile());
assertThat(new File(helmDir, "values.yaml"), FileMatchers.anExistingFile());
File templatesDir = new File(helmDir, "templates");
assertThat(Objects.requireNonNull(templatesDir.listFiles()).length, equalTo(8));
File kubernetesYml = prodModeTestResults.getBuildDir().resolve("kubernetes").resolve("kubernetes.yml").toFile();
assertThat(kubernetesYml, FileMatchers.anExistingFile());
String kubernetesYmlContents = Files.readString(kubernetesYml.toPath());
@SuppressWarnings("unchecked")
List<HasMetadata> resource = (List<HasMetadata>) FileUtils.unmarshalFrom(
kubernetesYmlContents.getBytes(StandardCharsets.UTF_8));
assertThat(resource, hasSize(11));
assertThat(resource, containsInAnyOrder(
hasProperty("kind", equalTo("ServiceAccount")),
hasProperty("kind", equalTo("ClusterRole")),
hasProperty("kind", equalTo("ClusterRole")),
hasProperty("kind", equalTo("ClusterRole")),
hasProperty("kind", equalTo("ClusterRoleBinding")),
hasProperty("kind", equalTo("ClusterRoleBinding")),
hasProperty("kind", equalTo("ClusterRoleBinding")),
hasProperty("kind", equalTo("Role")),
hasProperty("kind", equalTo("RoleBinding")),
hasProperty("kind", equalTo("Service")),
hasProperty("kind", equalTo("Deployment"))));
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/helm/deployment/src/test/java/io/quarkiverse/operatorsdk/helm/deployment/test/sources/SimpleSpec.java | helm/deployment/src/test/java/io/quarkiverse/operatorsdk/helm/deployment/test/sources/SimpleSpec.java | package io.quarkiverse.operatorsdk.helm.deployment.test.sources;
public class SimpleSpec {
public String value;
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/helm/deployment/src/test/java/io/quarkiverse/operatorsdk/helm/deployment/test/sources/SimpleStatus.java | helm/deployment/src/test/java/io/quarkiverse/operatorsdk/helm/deployment/test/sources/SimpleStatus.java | package io.quarkiverse.operatorsdk.helm.deployment.test.sources;
public class SimpleStatus {
public String value;
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/helm/deployment/src/test/java/io/quarkiverse/operatorsdk/helm/deployment/test/sources/WatchAllNamespacesReconciler.java | helm/deployment/src/test/java/io/quarkiverse/operatorsdk/helm/deployment/test/sources/WatchAllNamespacesReconciler.java | package io.quarkiverse.operatorsdk.helm.deployment.test.sources;
import static io.javaoperatorsdk.operator.api.reconciler.Constants.WATCH_ALL_NAMESPACES;
import io.javaoperatorsdk.operator.api.config.informer.Informer;
import io.javaoperatorsdk.operator.api.reconciler.Context;
import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration;
import io.javaoperatorsdk.operator.api.reconciler.Reconciler;
import io.javaoperatorsdk.operator.api.reconciler.UpdateControl;
@ControllerConfiguration(name = WatchAllNamespacesReconciler.NAME, informer = @Informer(namespaces = WATCH_ALL_NAMESPACES))
public class WatchAllNamespacesReconciler implements Reconciler<SimpleCR> {
public static final String NAME = "all-namespaces-reconciler";
@Override
public UpdateControl<SimpleCR> reconcile(SimpleCR simpleCR, Context<SimpleCR> context) {
return null;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/helm/deployment/src/test/java/io/quarkiverse/operatorsdk/helm/deployment/test/sources/SimpleReconciler.java | helm/deployment/src/test/java/io/quarkiverse/operatorsdk/helm/deployment/test/sources/SimpleReconciler.java | package io.quarkiverse.operatorsdk.helm.deployment.test.sources;
import io.javaoperatorsdk.operator.api.reconciler.Context;
import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration;
import io.javaoperatorsdk.operator.api.reconciler.Reconciler;
import io.javaoperatorsdk.operator.api.reconciler.UpdateControl;
import io.quarkiverse.operatorsdk.annotations.RBACRoleRef;
import io.quarkiverse.operatorsdk.annotations.RBACRule;
import io.quarkiverse.operatorsdk.annotations.RBACVerbs;
@ControllerConfiguration(name = SimpleReconciler.NAME)
@RBACRule(verbs = RBACVerbs.UPDATE, apiGroups = SimpleReconciler.CERTIFICATES_K8S_IO_GROUP, resources = SimpleReconciler.ADDITIONAL_UPDATE_RESOURCE)
@RBACRule(verbs = SimpleReconciler.SIGNERS_VERB, apiGroups = SimpleReconciler.CERTIFICATES_K8S_IO_GROUP, resources = SimpleReconciler.SIGNERS_RESOURCE, resourceNames = SimpleReconciler.SIGNERS_RESOURCE_NAMES)
@RBACRoleRef(name = SimpleReconciler.ROLE_REF_NAME, kind = RBACRoleRef.RoleKind.ClusterRole)
public class SimpleReconciler implements Reconciler<SimpleCR> {
public static final String NAME = "simple";
public static final String CERTIFICATES_K8S_IO_GROUP = "certificates.k8s.io";
public static final String ADDITIONAL_UPDATE_RESOURCE = "certificatesigningrequests/approval";
public static final String SIGNERS_VERB = "approve";
public static final String SIGNERS_RESOURCE = "signers";
public static final String SIGNERS_RESOURCE_NAMES = "kubernetes.io/kubelet-serving";
public static final String ROLE_REF_NAME = "system:auth-delegator";
@Override
public UpdateControl<SimpleCR> reconcile(SimpleCR simpleCR, Context<SimpleCR> context) {
return null;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/helm/deployment/src/test/java/io/quarkiverse/operatorsdk/helm/deployment/test/sources/SimpleCR.java | helm/deployment/src/test/java/io/quarkiverse/operatorsdk/helm/deployment/test/sources/SimpleCR.java | package io.quarkiverse.operatorsdk.helm.deployment.test.sources;
import io.fabric8.kubernetes.client.CustomResource;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Kind;
import io.fabric8.kubernetes.model.annotation.Version;
@Group("example.com")
@Version(value = SimpleCR.VERSION, storage = false)
@Kind(SimpleCR.KIND)
public class SimpleCR extends CustomResource<SimpleSpec, SimpleStatus> {
public static final String VERSION = "v1";
public static final String KIND = "SimpleCR";
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/helm/deployment/src/main/java/io/quarkiverse/operatorsdk/helm/deployment/HelmAugmentationProcessor.java | helm/deployment/src/main/java/io/quarkiverse/operatorsdk/helm/deployment/HelmAugmentationProcessor.java | package io.quarkiverse.operatorsdk.helm.deployment;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.jboss.logging.Logger;
import io.quarkiverse.helm.deployment.HelmChartConfig;
import io.quarkiverse.helm.spi.CustomHelmOutputDirBuildItem;
import io.quarkiverse.helm.spi.HelmChartBuildItem;
import io.quarkiverse.operatorsdk.common.FileUtils;
import io.quarkiverse.operatorsdk.deployment.GeneratedCRDInfoBuildItem;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.Produce;
import io.quarkus.deployment.pkg.builditem.ArtifactResultBuildItem;
import io.quarkus.deployment.pkg.builditem.OutputTargetBuildItem;
import io.quarkus.kubernetes.spi.KubernetesClusterRoleBindingBuildItem;
/**
* This processor copies the generated CRDs into the Helm chart output directories.
* <p>
* It is required to be in a separate extension because we want to include the Helm
* processing conditionally, based on the presence of the quarkus-helm extension. If
* the user includes the quarkus-helm extension, this processor will be executed
* and the CRDs will be copied into the Helm chart output directories. See the
* quarkus-extension-maven-plugin configuration in the runtime modules of this and
* the operator-sdk core extensions where this is configured.
*/
public class HelmAugmentationProcessor {
private static final Logger log = Logger.getLogger(HelmAugmentationProcessor.class);
public static final String CRD_DIR = "crds";
@BuildStep
@Produce(ArtifactResultBuildItem.class)
void addCRDsToHelmChart(
List<HelmChartBuildItem> helmChartBuildItems,
HelmChartConfig helmChartConfig,
@SuppressWarnings("OptionalUsedAsFieldOrParameterType") Optional<CustomHelmOutputDirBuildItem> customHelmOutputDirBuildItem,
OutputTargetBuildItem outputTargetBuildItem,
GeneratedCRDInfoBuildItem generatedCRDInfoBuildItem,
List<KubernetesClusterRoleBindingBuildItem> clusterRoleBindingBuildItems) {
log.infof("Adding CRDs to the following Helm charts - %s", helmChartBuildItems);
outputWarningIfNeeded(clusterRoleBindingBuildItems);
final var helmOutputDirectory = customHelmOutputDirBuildItem
.map(CustomHelmOutputDirBuildItem::getOutputDir)
.orElse(outputTargetBuildItem.getOutputDirectory().resolve(helmChartConfig.outputDirectory()));
var crdInfos = generatedCRDInfoBuildItem.getCRDGenerationInfo().getCrds().getCRDNameToInfoMappings().values();
helmChartBuildItems.forEach(helmChartBuildItem -> {
final var crdDir = helmOutputDirectory
.resolve(helmChartBuildItem.getDeploymentTarget())
.resolve(helmChartBuildItem.getName())
.resolve(CRD_DIR);
FileUtils.ensureDirectoryExists(crdDir.toFile());
crdInfos.forEach(crdInfo -> {
try {
var generateCrdPath = Path.of(crdInfo.getFilePath());
// replace needed since tests might generate files multiple times
Files.copy(generateCrdPath, crdDir.resolve(generateCrdPath.getFileName().toString()), REPLACE_EXISTING);
} catch (IOException e) {
throw new IllegalStateException(e);
}
});
});
}
private static void outputWarningIfNeeded(List<KubernetesClusterRoleBindingBuildItem> clusterRoleBindingBuildItems) {
clusterRoleBindingBuildItems
.forEach(clusterRoleBindingBuildItem -> Arrays.stream(clusterRoleBindingBuildItem.getSubjects())
.forEach(subject -> {
if (subject.getNamespace() == null) {
log.warnf(
"ClusterRoleBinding '%s' REQUIRES a namespace for the operator ServiceAccount, which has NOT been provided. "
+
"You can specify the ServiceAccount's namespace using the " +
"'quarkus.kubernetes.rbac.service-accounts.<service account name>.namespace=<service account namespace>'"
+
"property (or, alternatively, 'quarkus.kubernetes.namespace', though using this property will use the specified "
+
"namespace for ALL your resources. The Helm chart generated by this extension will most likely fail to install if "
+
"the namespace is not provided.",
clusterRoleBindingBuildItem.getName());
}
}));
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/test/java/io/quarkiverse/operatorsdk/runtime/QuarkusFieldSelectorTest.java | core/runtime/src/test/java/io/quarkiverse/operatorsdk/runtime/QuarkusFieldSelectorTest.java | package io.quarkiverse.operatorsdk.runtime;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Test;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.CustomResource;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Version;
import io.javaoperatorsdk.operator.api.config.informer.FieldSelector;
class QuarkusFieldSelectorTest {
@Test
void shouldCreateFieldSelector() {
assertEquals(new FieldSelector.Field("spec.nodeName", "someName", true), QuarkusFieldSelector
.from("spec.nodeName != someName", QuarkusFieldSelector.knownValidFields.get(Pod.class.getName()), Pod.class));
assertEquals(new FieldSelector.Field("metadata.name", "goo"),
QuarkusFieldSelector.from("metadata.name=goo", null, HasMetadata.class));
}
@Test
void invalidSelectorShouldThrowException() {
assertThrows(IllegalArgumentException.class, () -> QuarkusFieldSelector.from("foo", null, Pod.class));
assertThrows(IllegalArgumentException.class, () -> QuarkusFieldSelector.from("foo=", null, Pod.class));
assertThrows(IllegalArgumentException.class, () -> QuarkusFieldSelector.from("foo=!", null, Pod.class));
assertThrows(IllegalArgumentException.class, () -> QuarkusFieldSelector.from("foo==", null, Pod.class));
assertThrows(IllegalArgumentException.class, () -> QuarkusFieldSelector.from("foo!=", null, Pod.class));
assertThrows(IllegalArgumentException.class, () -> QuarkusFieldSelector.from("foo != ", null, Pod.class));
assertThrows(IllegalArgumentException.class, () -> QuarkusFieldSelector.from("foo = ", null, Pod.class));
assertThrows(IllegalArgumentException.class, () -> QuarkusFieldSelector.from("foo == ", null, Pod.class));
assertThrows(IllegalArgumentException.class, () -> QuarkusFieldSelector.from("foo == value ", null, Pod.class));
}
@Test
void getValidFieldNamesFor() {
final var configuration = mock(BuildTimeConfigurationService.class);
final var crds = new CRDInfos();
crds.addCRDInfo(new CRDInfo(CRDUtils.crdNameFor(External.class), CRDUtils.DEFAULT_CRD_SPEC_VERSION,
"src/test/resources/external.crd.yml", Set.of()));
when(configuration.getCrdInfo()).thenReturn(new CRDGenerationInfo(false, false, crds, Set.of()));
assertEquals(Set.of("spec"), QuarkusFieldSelector.getValidFieldNamesOrNullIfDefault(External.class, configuration));
}
@Test
void chainedSelectorsShouldWork() {
assertEquals(
List.of(new FieldSelector.Field("metadata.name", "value"),
new FieldSelector.Field("status.phase", "ready", true)),
QuarkusFieldSelector.from(List.of("metadata.name=value", "status.phase != ready"), Pod.class, null)
.getFields());
}
@Group("halkyon.io")
@Version("v1")
private static class External extends CustomResource<Void, Void> {
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/CRDConfiguration.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/CRDConfiguration.java | package io.quarkiverse.operatorsdk.runtime;
import java.util.List;
import java.util.Optional;
import io.fabric8.kubernetes.client.CustomResource;
import io.quarkus.runtime.annotations.ConfigGroup;
import io.smallrye.config.WithDefault;
import io.smallrye.config.WithName;
@ConfigGroup
public interface CRDConfiguration {
String DEFAULT_OUTPUT_DIRECTORY = "kubernetes";
String DEFAULT_VALIDATE = "true";
String DEFAULT_VERSIONS = "v1";
String DEFAULT_USE_V1_CRD_GENERATOR = "false";
/**
* Whether the operator should check that the CRD is properly deployed and that the associated
* {@link CustomResource} implementation matches its information before registering the associated
* controller.
*/
@WithDefault(DEFAULT_VALIDATE)
Boolean validate();
/**
* Whether the extension should automatically generate the CRD based on {@link CustomResource}
* implementations.
*/
Optional<Boolean> generate();
/**
* Whether the extension should automatically apply updated CRDs when they change.
* <p>
* <strong>NOTE that this option is only considered when *not* in production mode as applying the CRD to a production
* cluster could be dangerous if done automatically.</strong>
* </p>
*/
Optional<Boolean> apply();
/**
* Comma-separated list of which CRD versions should be generated.
*/
@WithDefault(DEFAULT_VERSIONS)
List<String> versions();
/**
* The directory where the CRDs will be generated, defaults to the {@code kubernetes}
* directory of the project's output directory.
*/
Optional<String> outputDirectory();
/**
* Whether the extension should generate all CRDs for Custom Resource implementations known to the application even if some
* are not tied to a Reconciler.
*/
@WithDefault("false")
Boolean generateAll();
/**
* Whether the CRDs should be generated in parallel.
*/
@WithDefault("false")
Boolean generateInParallel();
/**
* A comma-separated list of fully-qualified class names implementing {@link CustomResource} to exclude from the CRD
* generation process.
*/
Optional<List<String>> excludeResources();
/**
* A comma-separated list of paths where external CRDs that need to be referenced for non-generated custom resources.
* Typical use cases where this might be needed include when custom resource implementations are located in a different
* module than the controller implementation or when the CRDs are not generated at all (e.g. in integration cases where your
* operator needs to deal with 3rd party custom resources).
*
* <p>
* Paths can be either absolute or relative, in which case they will be resolved from the current module root directory.
* </p>
*
* @since 6.8.4
*/
Optional<List<String>> externalCRDLocations();
/**
* Whether or not to use the v1 version of the CRD generator. Note that this should only be used if a compatibility issue is
* found with the v2 generator, which is the default one and the one that is actively maintained.
*
* @return {@code true} if the v1 version of the CRD generator should be used
* @since 6.8.5
* @deprecated using this method should be reserved for blocking situations, please open an issue reporting the problem
* you're facing with the v2 generator before reverting to use the v1 version
*/
@Deprecated(forRemoval = true)
@WithDefault(DEFAULT_USE_V1_CRD_GENERATOR)
@WithName("use-deprecated-v1-crd-generator")
Boolean useV1CRDGenerator();
/**
* The fully qualified name of a Fabric8 CRD generator v2 API {@code CRDPostProcessor} implementation, providing a public,
* no-arg constructor for instantiation
*
* @since 7.2.0
*/
@WithName("post-processor")
Optional<String> crdPostProcessorClass();
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/QuarkusConfigurationService.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/QuarkusConfigurationService.java | package io.quarkiverse.operatorsdk.runtime;
import java.time.Duration;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.javaoperatorsdk.operator.api.config.AbstractConfigurationService;
import io.javaoperatorsdk.operator.api.config.ControllerConfiguration;
import io.javaoperatorsdk.operator.api.config.InformerStoppedHandler;
import io.javaoperatorsdk.operator.api.config.LeaderElectionConfiguration;
import io.javaoperatorsdk.operator.api.config.Version;
import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceSpec;
import io.javaoperatorsdk.operator.api.monitoring.Metrics;
import io.javaoperatorsdk.operator.api.reconciler.Reconciler;
import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource;
import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResourceFactory;
import io.javaoperatorsdk.operator.processing.dependent.workflow.Condition;
import io.javaoperatorsdk.operator.processing.dependent.workflow.DependentResourceNode;
import io.javaoperatorsdk.operator.processing.dependent.workflow.ManagedWorkflow;
import io.javaoperatorsdk.operator.processing.dependent.workflow.ManagedWorkflowFactory;
import io.quarkus.arc.Arc;
import io.quarkus.arc.ArcContainer;
import io.quarkus.arc.ClientProxy;
import io.quarkus.arc.InstanceHandle;
public class QuarkusConfigurationService extends AbstractConfigurationService implements
DependentResourceFactory<QuarkusControllerConfiguration<?>, DependentResourceSpecMetadata<?, ?, ?>>,
ManagedWorkflowFactory<QuarkusControllerConfiguration<?>> {
public static final int UNSET_TERMINATION_TIMEOUT_SECONDS = -1;
private static final Logger log = LoggerFactory.getLogger(QuarkusConfigurationService.class);
private final CRDGenerationInfo crdInfo;
private final int concurrentReconciliationThreads;
private final int terminationTimeout;
private final Map<String, String> reconcilerClassToName;
private final Metrics metrics;
private final boolean startOperator;
private final LeaderElectionConfiguration leaderElectionConfiguration;
private final InformerStoppedHandler informerStoppedHandler;
private final boolean closeClientOnStop;
private final boolean stopOnInformerErrorDuringStartup;
private final int concurrentWorkflowExecutorThreads;
private final Duration cacheSyncTimeout;
private final boolean asyncStart;
@SuppressWarnings("rawtypes")
private final Map<String, DependentResource> knownDependents = new ConcurrentHashMap<>();
private final boolean useSSA;
private final boolean defensiveCloning;
@SuppressWarnings({ "rawtypes", "unchecked" })
public QuarkusConfigurationService(
Version version,
Collection<QuarkusControllerConfiguration> configurations,
KubernetesClient kubernetesClient,
CRDGenerationInfo crdInfo, int maxThreads, int maxWorflowThreads,
int timeout, Duration cacheSyncTimeout, boolean asyncStart, Metrics metrics, boolean startOperator,
LeaderElectionConfiguration leaderElectionConfiguration, InformerStoppedHandler informerStoppedHandler,
boolean closeClientOnStop, boolean stopOnInformerErrorDuringStartup,
boolean useSSA, boolean defensiveCloning) {
super(version);
this.closeClientOnStop = closeClientOnStop;
this.stopOnInformerErrorDuringStartup = stopOnInformerErrorDuringStartup;
init(null, null, kubernetesClient);
this.startOperator = startOperator;
this.metrics = metrics;
if (configurations != null && !configurations.isEmpty()) {
final var size = configurations.size();
reconcilerClassToName = new HashMap<>(size);
configurations.forEach(c -> {
final var name = c.getName();
reconcilerClassToName.put(c.getAssociatedReconcilerClassName(), name);
register(c);
c.setParent(this);
});
} else {
reconcilerClassToName = Collections.emptyMap();
}
this.crdInfo = crdInfo;
this.concurrentReconciliationThreads = maxThreads;
this.concurrentWorkflowExecutorThreads = maxWorflowThreads;
this.terminationTimeout = timeout;
this.cacheSyncTimeout = cacheSyncTimeout;
this.asyncStart = asyncStart;
this.informerStoppedHandler = informerStoppedHandler;
this.leaderElectionConfiguration = leaderElectionConfiguration;
this.useSSA = useSSA;
this.defensiveCloning = defensiveCloning;
}
private static <R extends HasMetadata> Reconciler<R> unwrap(Reconciler<R> reconciler) {
return ClientProxy.unwrap(reconciler);
}
@SuppressWarnings("rawtypes")
private static String getDependentKey(QuarkusControllerConfiguration configuration,
DependentResourceSpec spec) {
return getDependentKeyFromNames(configuration.getName(), spec.getName());
}
private static String getDependentKeyFromNames(String controllerName, String dependentName) {
return controllerName + "#" + dependentName;
}
@Override
public <R extends HasMetadata> QuarkusControllerConfiguration<R> getConfigurationFor(Reconciler<R> reconciler) {
final var unwrapped = unwrap(reconciler);
return (QuarkusControllerConfiguration<R>) super.getConfigurationFor(unwrapped);
}
@Override
public boolean checkCRDAndValidateLocalModel() {
return crdInfo.isValidateCRDs();
}
@Override
protected String keyFor(Reconciler controller) {
// retrieve the controller name from its associated class name
// but we first need to check if the class is wrapped
// heuristics: we're assuming that any class name with an '_' in it is a
// proxy / wrapped / generated class and that the "real" class name is located before the
// '_'. This probably won't work in all instances but should work most of the time.
var controllerClass = controller.getClass().getName();
final int i = controllerClass.indexOf('_');
if (i > 0) {
controllerClass = controllerClass.substring(0, i);
}
String controllerName = reconcilerClassToName.get(controllerClass);
if (controllerName == null) {
throw new IllegalArgumentException("Unknown controller " + controllerClass);
}
return controllerName;
}
@Override
public int concurrentReconciliationThreads() {
return this.concurrentReconciliationThreads;
}
public int getTerminationTimeoutSeconds() {
return terminationTimeout;
}
public CRDGenerationInfo getCRDGenerationInfo() {
return crdInfo;
}
@Override
protected void logMissingReconcilerWarning(String reconcilerKey, String reconcilersNameMessage) {
log.warn("Cannot find configuration for '{}' reconciler. {}", reconcilerKey, reconcilersNameMessage);
}
@Override
public Metrics getMetrics() {
return metrics;
}
boolean shouldStartOperator() {
return startOperator;
}
@SuppressWarnings("rawtypes")
@Override
public Stream<ControllerConfiguration> controllerConfigurations() {
return super.controllerConfigurations();
}
@Override
public Optional<LeaderElectionConfiguration> getLeaderElectionConfiguration() {
return Optional.ofNullable(leaderElectionConfiguration);
}
@Override
public Optional<InformerStoppedHandler> getInformerStoppedHandler() {
return Optional.ofNullable(informerStoppedHandler);
}
@Override
public int concurrentWorkflowExecutorThreads() {
return concurrentWorkflowExecutorThreads;
}
@Override
public boolean closeClientOnStop() {
return closeClientOnStop;
}
@Override
public boolean stopOnInformerErrorDuringStartup() {
return stopOnInformerErrorDuringStartup;
}
@Override
public Duration cacheSyncTimeout() {
return cacheSyncTimeout;
}
public boolean isAsyncStart() {
return asyncStart;
}
@Override
public DependentResourceFactory<QuarkusControllerConfiguration<?>, DependentResourceSpecMetadata<?, ?, ?>> dependentResourceFactory() {
return this;
}
@Override
public ManagedWorkflowFactory<QuarkusControllerConfiguration<?>> getWorkflowFactory() {
return this;
}
@Override
public ManagedWorkflow<?> workflowFor(QuarkusControllerConfiguration<?> controllerConfiguration) {
return controllerConfiguration.getWorkflow();
}
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public DependentResource createFrom(DependentResourceSpecMetadata spec,
QuarkusControllerConfiguration configuration) {
final var dependentKey = getDependentKey(configuration, spec);
var dependentResource = knownDependents.get(dependentKey);
if (dependentResource == null) {
final Class<? extends DependentResource<?, ?>> dependentResourceClass = spec.getDependentResourceClass();
try (final var dependentInstance = Arc.container().instance(dependentResourceClass)) {
final var dependent = dependentInstance.get();
if (dependent == null) {
throw new IllegalStateException(
"Couldn't find bean associated with DependentResource "
+ dependentResourceClass.getName());
}
dependentResource = ClientProxy.unwrap(dependent);
// configure the bean
configure(dependentResource, spec, configuration);
// record the configured dependent for later retrieval if needed
knownDependents.put(dependentKey, dependentResource);
}
}
return dependentResource;
}
@Override
public DependentResourceNode createNodeFrom(DependentResourceSpecMetadata spec,
DependentResource dependentResource) {
final var container = Arc.container();
if (container != null) {
return new DependentResourceNode(
getBeanInstanceOrDefault(container, spec.getReconcileCondition()),
getBeanInstanceOrDefault(container, spec.getDeletePostCondition()),
getBeanInstanceOrDefault(container, spec.getReadyCondition()),
getBeanInstanceOrDefault(container, spec.getActivationCondition()),
dependentResource);
} else {
return DependentResourceFactory.super.createNodeFrom(spec, dependentResource);
}
}
private Condition getBeanInstanceOrDefault(ArcContainer container, Condition reconcileCondition) {
if (reconcileCondition == null) {
return null;
}
try (InstanceHandle<? extends Condition> instance = container.instance(reconcileCondition.getClass())) {
if (instance.isAvailable()) {
return instance.get();
} else {
return reconcileCondition;
}
}
}
@Override
public Class<?> associatedResourceType(DependentResourceSpecMetadata spec) {
return spec.getResourceClass();
}
@SuppressWarnings({ "rawtypes" })
public DependentResourceSpecMetadata getDependentByName(String controllerName, String dependentName) {
final ControllerConfiguration<?> cc = getFor(controllerName);
if (cc == null) {
return null;
} else {
return cc.getWorkflowSpec().flatMap(spec -> spec.getDependentResourceSpecs().stream()
.filter(r -> r.getName().equals(dependentName) && r instanceof DependentResourceSpecMetadata<?, ?, ?>)
.map(DependentResourceSpecMetadata.class::cast)
.findFirst())
.orElse(null);
}
}
@SuppressWarnings("rawtypes")
public ManagedWorkflow workflowByName(String name) {
return ((QuarkusControllerConfiguration) getFor(name)).getWorkflow();
}
@Override
public boolean ssaBasedCreateUpdateMatchForDependentResources() {
return useSSA;
}
@Override
public boolean useSSAToPatchPrimaryResource() {
return useSSA;
}
@Override
public boolean cloneSecondaryResourcesWhenGettingFromCache() {
return defensiveCloning;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/QuarkusFieldSelector.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/QuarkusFieldSelector.java | package io.quarkiverse.operatorsdk.runtime;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import io.fabric8.kubernetes.api.model.Event;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.Namespace;
import io.fabric8.kubernetes.api.model.Node;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.ReplicationController;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinitionVersion;
import io.fabric8.kubernetes.api.model.apiextensions.v1.SelectableField;
import io.fabric8.kubernetes.api.model.apps.ReplicaSet;
import io.fabric8.kubernetes.api.model.batch.v1.Job;
import io.fabric8.kubernetes.api.model.certificates.v1.CertificateSigningRequest;
import io.fabric8.kubernetes.client.CustomResource;
import io.javaoperatorsdk.operator.api.config.informer.FieldSelector;
import io.quarkus.runtime.annotations.RecordableConstructor;
public class QuarkusFieldSelector extends FieldSelector {
private static final String METADATA_NAME = "metadata.name";
private static final String METADATA_NAMESPACE = "metadata.namespace";
private static final Set<String> DEFAULT_FIELD_SELECTOR_NAMES = Set.of(METADATA_NAME, METADATA_NAMESPACE);
static final Map<String, Set<String>> knownValidFields = Map.of(
Pod.class.getName(), Set.of(
"spec.nodeName", "spec.restartPolicy", "spec.schedulerName", "spec.serviceAccountName", "spec.hostNetwork",
"status.phase", "status.podIP", "status.podIPs", "status.nominatedNodeName"),
Event.class.getName(), Set.of("involvedObject.kind",
"involvedObject.namespace",
"involvedObject.name",
"involvedObject.uid",
"involvedObject.apiVersion",
"involvedObject.resourceVersion",
"involvedObject.fieldPath",
"reason",
"reportingComponent",
"source",
"type"),
Secret.class.getName(), Set.of("type"),
Namespace.class.getName(), Set.of("status.phase"),
ReplicaSet.class.getName(), Set.of("status.replicas"),
ReplicationController.class.getName(), Set.of("status.replicas"),
Job.class.getName(), Set.of("status.successful"),
Node.class.getName(), Set.of("spec.unschedulable"),
CertificateSigningRequest.class.getName(), Set.of("spec.signerName"));
@RecordableConstructor
public QuarkusFieldSelector(List<Field> fields) {
super(fields);
}
public QuarkusFieldSelector(FieldSelector fieldSelector) {
this(fieldSelector.getFields());
}
public static <R extends HasMetadata> QuarkusFieldSelector from(List<String> fieldSelectors, Class<R> resourceClass,
BuildTimeConfigurationService configurationService) {
if (fieldSelectors == null || fieldSelectors.isEmpty()) {
return new QuarkusFieldSelector(List.of());
}
final var validFieldNames = getValidFieldNamesOrNullIfDefault(resourceClass, configurationService);
final var fields = fieldSelectors.stream()
.map(s -> from(s, validFieldNames, resourceClass))
.filter(Objects::nonNull)
.toList();
return new QuarkusFieldSelector(fields);
}
static <R extends HasMetadata> Set<String> getValidFieldNamesOrNullIfDefault(Class<R> resourceClass,
BuildTimeConfigurationService configurationService) {
// first check if we have a known resource type as defined by:
// https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors/#list-of-supported-fields
final var validNames = knownValidFields.get(resourceClass.getName());
if (validNames == null) {
if (CustomResource.class.isAssignableFrom(resourceClass)) {
// check if the CRD defines selectable fields
final var infos = configurationService.getCrdInfo().getCRDInfosFor(CRDUtils.crdNameFor(resourceClass));
if (infos != null) {
final var info = infos.get(CRDUtils.DEFAULT_CRD_SPEC_VERSION);
if (info != null) {
try {
final var crd = CRDUtils.loadFrom(Path.of(info.getFilePath()));
return crd.getSpec().getVersions().stream()
.map(CustomResourceDefinitionVersion::getSelectableFields)
.filter(Objects::nonNull)
.flatMap(fields -> fields.stream().map(SelectableField::getJsonPath))
.collect(Collectors.toSet());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
// if not a CustomResource or one that doesn't define selectable fields, return null
return null;
} else {
return validNames;
}
}
public static FieldSelector.Field from(String fieldSelector, Set<String> validFieldNames, Class<?> resourceClass) {
if (fieldSelector == null || fieldSelector.isEmpty()) {
return null;
}
final var equalsIndex = fieldSelector.indexOf('=');
illegalArgIf(equalsIndex == -1, fieldSelector);
final var nameAndNegated = extractNameAndNegatedStatus(fieldSelector, equalsIndex);
final var name = nameAndNegated.name();
if (!DEFAULT_FIELD_SELECTOR_NAMES.contains(name)
&& (validFieldNames == null || !validFieldNames.contains(name))) {
throw new IllegalArgumentException("'" + name + "' is not a valid field name for resource "
+ resourceClass.getSimpleName());
}
final var value = extractValue(fieldSelector, equalsIndex);
return new Field(name, value, nameAndNegated.negated());
}
private static NameAndNegated extractNameAndNegatedStatus(String fieldSelector, int equalsIndex) {
var fieldNameWithPossibleBang = fieldSelector.substring(0, equalsIndex).trim();
illegalArgIf(fieldNameWithPossibleBang.isEmpty(), fieldSelector);
// check for possible ! as last character if the field is negated
boolean negated = false;
final var lastIndex = fieldNameWithPossibleBang.length() - 1;
if (fieldNameWithPossibleBang.charAt(lastIndex) == '!') {
negated = true;
fieldNameWithPossibleBang = fieldNameWithPossibleBang.substring(0, lastIndex).trim();
}
return new NameAndNegated(fieldNameWithPossibleBang, negated);
}
private record NameAndNegated(String name, boolean negated) {
}
private static String extractValue(String fieldSelector, int equalsIndex) {
var valueWithPossibleEquals = fieldSelector.substring(equalsIndex + 1).trim();
illegalArgIf(valueWithPossibleEquals.isEmpty(), fieldSelector);
// check for possible = as first character if the operator is == instead of simply =
if (valueWithPossibleEquals.charAt(0) == '=') {
valueWithPossibleEquals = valueWithPossibleEquals.substring(1);
}
return valueWithPossibleEquals;
}
private static void illegalArgIf(boolean predicate, String fieldSelector) {
if (predicate) {
throw new IllegalArgumentException(
"Field selector must be use the <field><op><value> format where 'op' is one of '=', '==' or '!='. Was: "
+ fieldSelector);
}
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/MicrometerMetricsProvider.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/MicrometerMetricsProvider.java | package io.quarkiverse.operatorsdk.runtime;
import jakarta.enterprise.inject.Produces;
import jakarta.inject.Singleton;
import io.javaoperatorsdk.operator.api.monitoring.Metrics;
import io.javaoperatorsdk.operator.monitoring.micrometer.MicrometerMetrics;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.MeterBinder;
import io.quarkus.arc.DefaultBean;
@Singleton
public class MicrometerMetricsProvider implements MeterBinder {
private Metrics metrics = Metrics.NOOP;
@Override
public void bindTo(MeterRegistry registry) {
metrics = MicrometerMetrics.newPerResourceCollectingMicrometerMetricsBuilder(registry).build();
}
@Produces
@DefaultBean
public Metrics getMetrics() {
return metrics;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/CRDInfo.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/CRDInfo.java | package io.quarkiverse.operatorsdk.runtime;
import java.util.Set;
import io.quarkus.runtime.annotations.RecordableConstructor;
public class CRDInfo {
private final String crdName;
private final String crdSpecVersion;
private final String filePath;
private final Set<String> dependentClassNames;
@RecordableConstructor // constructor needs to be recordable for the class to be passed around by Quarkus
public CRDInfo(String crdName, String crdSpecVersion, String filePath, Set<String> dependentClassNames) {
this.crdName = crdName;
this.crdSpecVersion = crdSpecVersion;
this.filePath = filePath;
this.dependentClassNames = dependentClassNames;
}
public String getCrdName() {
return this.crdName;
}
public String getCrdSpecVersion() {
return this.crdSpecVersion;
}
public String getFilePath() {
return this.filePath;
}
public Set<String> getDependentClassNames() {
return this.dependentClassNames;
}
@Override
public String toString() {
return crdName;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/DependentResourceSpecMetadata.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/DependentResourceSpecMetadata.java | package io.quarkiverse.operatorsdk.runtime;
import java.util.Set;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceSpec;
import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource;
import io.javaoperatorsdk.operator.processing.dependent.workflow.Condition;
import io.quarkus.runtime.annotations.RecordableConstructor;
public class DependentResourceSpecMetadata<R, P extends HasMetadata, C> extends
DependentResourceSpec<R, P, C> {
private final Class<R> resourceClass;
@RecordableConstructor
public DependentResourceSpecMetadata(Class<? extends DependentResource<R, P>> dependentResourceClass,
String name, Set<String> dependsOn,
Condition<?, ?> readyCondition,
Condition<?, ?> reconcileCondition,
Condition<?, ?> deletePostCondition,
Condition<?, ?> activationCondition,
String quarkusUseEventSourceWithName,
Class<R> resourceClass) {
super(dependentResourceClass, name, dependsOn, readyCondition, reconcileCondition, deletePostCondition,
activationCondition,
quarkusUseEventSourceWithName);
this.resourceClass = resourceClass;
}
// Getter required for Quarkus' RecordableConstructor, must match the associated constructor parameter name
@SuppressWarnings("unused")
public String getQuarkusUseEventSourceWithName() {
return getUseEventSourceWithName().orElse(null);
}
// Getter required for Quarkus' byte recording to work
@SuppressWarnings("unused")
public C getNullableConfiguration() {
return getConfiguration().orElse(null);
}
// Setter required for Quarkus' byte recording to work
@SuppressWarnings("unused")
@Override
public void setNullableConfiguration(C configuration) {
super.setNullableConfiguration(configuration);
}
public Class<R> getResourceClass() {
return resourceClass;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/BuildTimeControllerConfiguration.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/BuildTimeControllerConfiguration.java | package io.quarkiverse.operatorsdk.runtime;
import java.util.List;
import java.util.Optional;
import io.quarkus.runtime.annotations.ConfigGroup;
import io.smallrye.config.WithDefault;
@ConfigGroup
public interface BuildTimeControllerConfiguration {
/**
* Whether the controller should only process events if the associated resource generation has
* increased since last reconciliation, otherwise will process all events.
*/
Optional<Boolean> generationAware();
/**
* An optional list of comma-separated watched namespace names that will be used to generate manifests at build time.
*
* <p>
* Note that this is provided as a means to quickly deploy a specific controller to test it by applying the generated
* manifests to the target cluster. If empty, no manifests will be generated. The namespace in which the controller will be
* deployed will be the currently configured namespace as specified by your {@code .kube/config} file, unless you specify
* the target deployment namespace using the {@code quarkus.kubernetes.namespace} property.
* </p>
*
* <p>
* As this functionality cannot handle namespaces that are not know until runtime (because the generation happens during
* build time), we recommend that you use a different mechanism such as OLM or Helm charts to deploy your operator in
* production.
* </p>
*
* <p>
* This replaces the previous {@code namespaces} property which was confusing and against Quarkus best practices since it
* existed both at build time and runtime. That property wasn't also adequately capturing the fact that namespaces that
* wouldn't be known until runtime would render whatever got generated at build time invalid as far as generated manifests
* were concerned.
* </p>
*/
Optional<List<String>> generateWithWatchedNamespaces();
/**
* Indicates whether the primary resource for the associated controller is unowned, meaning that another controller is the
* principal controller handling resources of this type. By default, controllers are assumed to own their primary resource
* but there are cases where this might not be the case, for example, when extra processing of a given resource type is
* required even though another controller already handles reconciliations of resources of that type. Set this property to
* {@code true} if you want to indicate that the controller doesn't own its primary resource
*/
@WithDefault("false")
boolean unownedPrimary();
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/QuarkusInformerConfiguration.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/QuarkusInformerConfiguration.java | package io.quarkiverse.operatorsdk.runtime;
import java.util.Set;
import java.util.stream.Collectors;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.client.informers.cache.ItemStore;
import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration;
import io.javaoperatorsdk.operator.processing.event.source.filter.GenericFilter;
import io.javaoperatorsdk.operator.processing.event.source.filter.OnAddFilter;
import io.javaoperatorsdk.operator.processing.event.source.filter.OnDeleteFilter;
import io.javaoperatorsdk.operator.processing.event.source.filter.OnUpdateFilter;
import io.quarkus.runtime.annotations.RecordableConstructor;
public class QuarkusInformerConfiguration<R extends HasMetadata> extends InformerConfiguration<R> {
@RecordableConstructor
public QuarkusInformerConfiguration(Class<R> resourceClass, String name, Set<String> namespaces,
boolean followControllerNamespaceChanges, String labelSelector, OnAddFilter<? super R> onAddFilter,
OnUpdateFilter<? super R> onUpdateFilter, OnDeleteFilter<? super R> onDeleteFilter,
GenericFilter<? super R> genericFilter, ItemStore<R> itemStore, Long informerListLimit,
QuarkusFieldSelector fieldSelector) {
super(resourceClass, name, namespaces, followControllerNamespaceChanges, labelSelector, onAddFilter, onUpdateFilter,
onDeleteFilter, genericFilter, itemStore, informerListLimit, fieldSelector);
}
public QuarkusInformerConfiguration(InformerConfiguration<R> config) {
this(config.getResourceClass(),
config.getName(),
sanitizeNamespaces(config.getNamespaces()),
config.getFollowControllerNamespaceChanges(),
config.getLabelSelector(),
config.getOnAddFilter(),
config.getOnUpdateFilter(),
config.getOnDeleteFilter(),
config.getGenericFilter(),
config.getItemStore(),
config.getInformerListLimit(),
config.getFieldSelector() == null ? null : new QuarkusFieldSelector(config.getFieldSelector()));
}
private static Set<String> sanitizeNamespaces(Set<String> namespaces) {
return namespaces.stream().map(String::trim).collect(Collectors.toSet());
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/OperatorHealthCheck.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/OperatorHealthCheck.java | package io.quarkiverse.operatorsdk.runtime;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.eclipse.microprofile.health.HealthCheck;
import org.eclipse.microprofile.health.HealthCheckResponse;
import org.eclipse.microprofile.health.Readiness;
import io.javaoperatorsdk.operator.Operator;
@Readiness
@ApplicationScoped
public class OperatorHealthCheck implements HealthCheck {
public static final String HEALTH_CHECK_NAME = "Quarkus Operator SDK health check";
public static final String OK = "OK";
@Inject
Operator operator;
@Override
public HealthCheckResponse call() {
final var runtimeInfo = operator.getRuntimeInfo();
if (runtimeInfo.isStarted()) {
final var response = HealthCheckResponse.named(HEALTH_CHECK_NAME);
final boolean[] healthy = { true };
runtimeInfo.getRegisteredControllers().forEach(rc -> {
final var name = rc.getConfiguration().getName();
final var unhealthy = rc.getControllerHealthInfo().unhealthyEventSources();
if (unhealthy.isEmpty()) {
response.withData(name, OK);
} else {
healthy[0] = false;
response
.withData(name, "unhealthy: " + String.join(", ", unhealthy.keySet()));
}
});
if (healthy[0]) {
response.up();
} else {
response.down();
}
return response.build();
}
return HealthCheckResponse.down(HEALTH_CHECK_NAME);
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/AppEventListener.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/AppEventListener.java | package io.quarkiverse.operatorsdk.runtime;
import java.util.concurrent.ExecutorService;
import jakarta.annotation.Priority;
import jakarta.enterprise.event.Observes;
import jakarta.interceptor.Interceptor;
import org.jboss.logging.Logger;
import io.javaoperatorsdk.operator.Operator;
import io.quarkus.runtime.ShutdownEvent;
import io.quarkus.runtime.StartupEvent;
public class AppEventListener {
private static final Logger log = Logger.getLogger(AppEventListener.class);
private final Operator operator;
private final QuarkusConfigurationService configurationService;
private final ExecutorService executor;
// The ExecutorService is the default Quarkus managed ExecutorService that comes from the ArC extension
public AppEventListener(Operator operator, QuarkusConfigurationService quarkusConfigurationService,
ExecutorService executor) {
this.operator = operator;
this.configurationService = quarkusConfigurationService;
this.executor = executor;
}
public void onStartup(@Observes @Priority(Interceptor.Priority.LIBRARY_AFTER + 123) StartupEvent event) {
if (configurationService.isAsyncStart()) {
// delegate the startup to a separate thread in order not to block other processing, e.g. HTTP server
executor.execute(this::startOperator);
} else {
startOperator();
}
}
public void onShutdown(@Observes ShutdownEvent event) {
if (configurationService.shouldStartOperator()) {
log.infof("Quarkus Java Operator SDK extension is shutting down. Is standard shutdown: %s",
event.isStandardShutdown());
operator.stop();
} else {
log.warn("Operator was configured not to stop automatically, call the stop method to stop it.");
}
}
private void startOperator() {
if (configurationService.shouldStartOperator()) {
if (operator.getRegisteredControllersNumber() > 0) {
log.info("Starting operator.");
operator.start();
} else {
log.warn("No Reconciler implementation was found so the Operator was not started.");
}
} else {
log.warn("Operator was configured not to start automatically, call the start method to start it.");
}
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/ExternalGradualRetryIntervalConfiguration.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/ExternalGradualRetryIntervalConfiguration.java | package io.quarkiverse.operatorsdk.runtime;
import java.util.Optional;
import io.quarkus.runtime.annotations.ConfigGroup;
@ConfigGroup
public interface ExternalGradualRetryIntervalConfiguration {
long UNSET_INITIAL = -1;
double UNSET_MULTIPLIER = -1;
long UNSET_MAX = -1;
/**
* The initial interval that the controller waits for before attempting the first retry
*/
Optional<Long> initial();
/**
* The value by which the initial interval is multiplied by for each retry
*/
Optional<Double> multiplier();
/**
* The maximum interval that the controller will wait for before attempting a retry, regardless of
* all other configuration
*/
Optional<Long> max();
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/BuildTimeOperatorConfiguration.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/BuildTimeOperatorConfiguration.java | package io.quarkiverse.operatorsdk.runtime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import io.javaoperatorsdk.operator.api.config.ConfigurationService;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;
import io.smallrye.config.ConfigMapping;
import io.smallrye.config.WithDefault;
import io.smallrye.config.WithName;
@ConfigMapping(prefix = "quarkus.operator-sdk")
@ConfigRoot(phase = ConfigPhase.BUILD_AND_RUN_TIME_FIXED)
public interface BuildTimeOperatorConfiguration {
/**
* Maps a controller name to its configuration.
*/
Map<String, BuildTimeControllerConfiguration> controllers();
/**
* The optional CRD-related configuration options
*/
CRDConfiguration crd();
/**
* Whether controllers should only process events if the associated resource generation has
* increased since last reconciliation, otherwise will process all events. Sets the default value
* for all controllers.
*/
@WithDefault("true")
Optional<Boolean> generationAware();
/**
* Whether Role-Based Access Control (RBAC) resources generated by the Kubernetes extension should be augmented by this
* extension.
*/
@WithDefault("false")
Boolean disableRbacGeneration();
/**
* Whether the operator should be automatically started or not. Mostly useful for testing
* scenarios.
*/
@WithDefault("true")
Boolean startOperator();
/**
* Whether the injected Kubernetes client should be stopped when the operator is stopped.
*/
@WithDefault("true")
Boolean closeClientOnStop();
/**
* Whether the operator should stop if an informer error (such as one caused by missing / improper
* RBACs) occurs during startup.
*/
@WithDefault("true")
Boolean stopOnInformerErrorDuringStartup();
/**
* Whether to fail or emit a debug-level (when misalignment is at the minor or above version level) log when
* the extension detects that there are misaligned versions.
* <p/>
* The following versions are checked for alignment:
* <ul>
* <li>declared Quarkus version used to build the extension vs. actually used Quarkus version at runtime</li>
* <li>Fabric8 client version used by JOSDK vs. actually used Fabric8 client version</li>
* <li>Fabric8 client version used by Quarkus vs. actually used Fabric8 client version</li>
* </ul>
* <p>
* Checking the alignment of these versions used to be more important than it is now as it happened that attempting to use
* this extension with differing versions of the client between JOSDK and Quarkus caused issues. Usually, this manifested
* with otherwise unexplained issues when using native compilation (e.g. improper serialization of objects) so version
* alignment check was implemented to help diagnose such issues.
* </p>
* Prior to version 7.3.0, this version alignment check was outputting warning-level information whenever versions were
* mismatched at least at the minor level, sometimes causing confusion. Since issues caused by such misalignments have been
* rare now that the project is more mature, it was decided to move these logs to debug-level instead.
*/
@WithDefault("false")
Boolean failOnVersionCheck();
/**
* The list of profile names for which leader election should be activated. This is mostly useful for testing scenarios
* where leader election behavior might lead to issues.
*/
@WithDefault("prod")
List<String> activateLeaderElectionForProfiles();
/**
* The optional Server-Side Apply (SSA) related configuration.
*/
@WithName("enable-ssa")
@WithDefault("true")
boolean enableSSA();
/**
* Whether defensive cloning of resources retrieved from caches should be activated or not. With the prevalence of
* Server-Side Apply (SSA) use, defensively cloning resources, to prevent cached versions from being inadvertently modified,
* shouldn't be needed anymore. This should also allow for better performance. If you encounter cache corruption issues, you
* can always turn defensive cloning back on, however, you might first want to check that you're not unduly modifying
* resources retrieved from caches.
*
* @see ConfigurationService#cloneSecondaryResourcesWhenGettingFromCache()
* @since 7.0.0
*/
@WithDefault("false")
boolean defensiveCloning();
/**
* An optional list of comma-separated watched namespace names that will be used to generate manifests at build time if
* controllers do <strong>NOT</strong> specify a value individually. See
* {@link BuildTimeControllerConfiguration#generateWithWatchedNamespaces} for more information.
*/
Optional<List<String>> generateWithWatchedNamespaces();
default boolean isControllerOwningPrimary(String controllerName) {
final var controllerConfiguration = controllers().get(controllerName);
return controllerConfiguration == null || !controllerConfiguration.unownedPrimary();
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/QuarkusKubernetesDependentResourceConfig.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/QuarkusKubernetesDependentResourceConfig.java | package io.quarkiverse.operatorsdk.runtime;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration;
import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResourceConfig;
import io.quarkus.runtime.annotations.RecordableConstructor;
public class QuarkusKubernetesDependentResourceConfig<R extends HasMetadata> extends KubernetesDependentResourceConfig<R> {
@RecordableConstructor
public QuarkusKubernetesDependentResourceConfig(Boolean useSSA, boolean createResourceOnlyIfNotExistingWithSSA,
QuarkusInformerConfiguration<R> informerConfig) {
super(useSSA, createResourceOnlyIfNotExistingWithSSA, informerConfig);
}
// Getter required for Quarkus' RecordableConstructor, must match the associated constructor parameter name
@SuppressWarnings("unused")
public boolean isCreateResourceOnlyIfNotExistingWithSSA() {
return createResourceOnlyIfNotExistingWithSSA();
}
// Getter required for Quarkus' RecordableConstructor, must match the associated constructor parameter name
@SuppressWarnings("unused")
public Boolean isUseSSA() {
return useSSA();
}
// Getter required for Quarkus' RecordableConstructor, must match the associated constructor parameter name
@SuppressWarnings("unused")
public InformerConfiguration<R> getInformerConfig() {
return informerConfig();
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/RunTimeControllerConfiguration.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/RunTimeControllerConfiguration.java | package io.quarkiverse.operatorsdk.runtime;
import static io.quarkiverse.operatorsdk.runtime.Constants.QOSDK_USE_BUILDTIME_NAMESPACES;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration;
import io.javaoperatorsdk.operator.api.reconciler.MaxReconciliationInterval;
import io.quarkus.runtime.annotations.ConfigGroup;
import io.smallrye.config.WithDefault;
@ConfigGroup
public interface RunTimeControllerConfiguration {
/**
* An optional list of comma-separated namespace names the controller should watch. If this
* property is left empty then the controller will watch all namespaces.
* The value can be set to "JOSDK_WATCH_CURRENT" to watch the current (default) namespace from kube config.
* Constant(s) can be found in at {@link io.javaoperatorsdk.operator.api.reconciler.Constants}".
*/
@WithDefault(QOSDK_USE_BUILDTIME_NAMESPACES)
Optional<List<String>> namespaces();
/**
* The optional name of the finalizer for the controller. If none is provided, one will be
* automatically generated.
*/
Optional<String> finalizer();
/**
* Configures the controller's {@link io.javaoperatorsdk.operator.processing.retry.GradualRetry} policy. This will only take
* effect if {@link ControllerConfiguration#retry()} is set to use the
* {@link io.javaoperatorsdk.operator.processing.retry.GenericRetry} implementation (which is what is used by default if not
* otherwise configured)
*/
ExternalGradualRetryConfiguration retry();
/**
* An optional list of comma-separated label selectors that Custom Resources must match to trigger the controller.
* See <a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/">Kubernetes' labels
* documentation</a> for more details on
* label selectors.
*/
Optional<String> selector();
/**
* An optional list of comma-separated field selectors that Custom Resources must match to trigger the controller.
* See <a href="https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors/">Kubernetes' field
* selector documentation</a> for more details on
* field selectors.
*/
Optional<List<String>> fieldSelectors();
/**
* An optional {@link Duration} to specify the maximum time that is allowed to elapse before a reconciliation will happen
* regardless of the presence of events. See {@link MaxReconciliationInterval#interval()} for more details.
* Value is specified according to the rules defined at {@link Duration#parse(CharSequence)}.
*/
Optional<Duration> maxReconciliationInterval();
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/Version.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/Version.java | package io.quarkiverse.operatorsdk.runtime;
import java.io.IOException;
import java.io.InputStream;
import java.time.Instant;
import java.util.Date;
import java.util.Properties;
import org.jboss.logging.Logger;
import io.javaoperatorsdk.operator.api.config.Utils;
import io.quarkus.runtime.annotations.IgnoreProperty;
import io.quarkus.runtime.annotations.RecordableConstructor;
public class Version extends io.javaoperatorsdk.operator.api.config.Version {
private static final Logger log = Logger.getLogger(Version.class.getName());
public static final String UNKNOWN = "unknown";
private final String extensionVersion;
private final String extensionBranch;
private final String extensionCommit;
private final String runtimeFabric8Version;
private final Date extensionBuildTime;
@RecordableConstructor // constructor needs to be recordable for the class to be passed around by Quarkus
public Version(String commit, Date builtTime, String extensionVersion, String extensionCommit,
String extensionBranch, String runtimeFabric8Version, Date extensionBuildTime) {
super(commit, builtTime);
this.extensionVersion = extensionVersion;
this.extensionBranch = extensionBranch;
this.extensionCommit = extensionCommit;
this.runtimeFabric8Version = runtimeFabric8Version;
this.extensionBuildTime = extensionBuildTime;
}
public String getExtensionVersion() {
return extensionVersion;
}
@SuppressWarnings("unused")
public String getExtensionBranch() {
return extensionBranch;
}
public String getExtensionCommit() {
return extensionCommit;
}
@SuppressWarnings("unused")
public Date getExtensionBuildTime() {
return extensionBuildTime;
}
@IgnoreProperty
public String getExtensionCompleteVersion() {
final var branch = Version.UNKNOWN.equals(extensionBranch)
? " on branch: " + extensionBranch
: "";
return extensionVersion + " (commit: " + extensionCommit + branch + ") built on " + extensionBuildTime;
}
@IgnoreProperty
public String getSdkCompleteVersion() {
return getSdkVersion() + " (commit: " + getCommit() + ") built on " + getBuiltTime();
}
public String getQuarkusVersion() {
return Versions.QUARKUS;
}
public String getRuntimeFabric8Version() {
return runtimeFabric8Version;
}
public static Version loadFromProperties() {
final var sdkVersion = Utils.VERSION;
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("extension-version.properties");
Properties properties = new Properties();
if (is != null) {
try {
properties.load(is);
} catch (IOException e) {
log.warnf("Couldn't load extension version information: {0}", e.getMessage());
}
} else {
log.warn("Couldn't find extension-version.properties file. Default version information will be used.");
}
Date builtTime;
try {
String time = properties.getProperty("git.build.time");
if (time != null) {
builtTime = Date.from(Instant.parse(time));
} else {
builtTime = Date.from(Instant.EPOCH);
}
} catch (Exception e) {
log.debug("Couldn't parse git.build.time property", e);
builtTime = Date.from(Instant.EPOCH);
}
return new Version(sdkVersion.getCommit(), sdkVersion.getBuiltTime(),
properties.getProperty("git.build.version", UNKNOWN),
properties.getProperty("git.commit.id.abbrev", UNKNOWN),
properties.getProperty("git.branch", UNKNOWN),
io.fabric8.kubernetes.client.Version.clientVersion(),
builtTime);
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/KubernetesClientObjectMapperCustomizer.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/KubernetesClientObjectMapperCustomizer.java | package io.quarkiverse.operatorsdk.runtime;
import jakarta.inject.Singleton;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
@Singleton
public class KubernetesClientObjectMapperCustomizer implements
io.quarkus.kubernetes.client.KubernetesClientObjectMapperCustomizer {
@Override
public void customize(ObjectMapper mapper) {
// disable failure on empty beans
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/BuildTimeConfigurationService.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/BuildTimeConfigurationService.java | package io.quarkiverse.operatorsdk.runtime;
import java.util.List;
import java.util.Set;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.javaoperatorsdk.operator.api.config.ConfigurationService;
import io.javaoperatorsdk.operator.api.config.ControllerConfiguration;
import io.javaoperatorsdk.operator.api.reconciler.Reconciler;
import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResourceFactory;
import io.quarkus.runtime.annotations.IgnoreProperty;
public class BuildTimeConfigurationService implements ConfigurationService,
DependentResourceFactory<QuarkusBuildTimeControllerConfiguration<?>, DependentResourceSpecMetadata<?, ?, ?>> {
private final Version version;
private final CRDGenerationInfo crdInfo;
private final boolean startOperator;
private final boolean closeClientOnStop;
private final boolean stopOnInformerErrorDuringStartup;
private final boolean enableSSA;
private final List<String> leaderElectionActivationProfiles;
private final boolean defensiveCloning;
public BuildTimeConfigurationService(Version version, CRDGenerationInfo crdInfo, boolean startOperator,
boolean closeClientOnStop, boolean stopOnInformerErrorDuringStartup, boolean enableSSA,
List<String> leaderElectionActivationProfiles, boolean defensiveCloning) {
this.version = version;
this.crdInfo = crdInfo;
this.startOperator = startOperator;
this.closeClientOnStop = closeClientOnStop;
this.stopOnInformerErrorDuringStartup = stopOnInformerErrorDuringStartup;
this.enableSSA = enableSSA;
this.leaderElectionActivationProfiles = leaderElectionActivationProfiles;
this.defensiveCloning = defensiveCloning;
}
@Override
public <R extends HasMetadata> ControllerConfiguration<R> getConfigurationFor(Reconciler<R> reconciler) {
throw new UnsupportedOperationException();
}
@Override
@IgnoreProperty
public Set<String> getKnownReconcilerNames() {
throw new UnsupportedOperationException();
}
public Version getVersion() {
return version;
}
public CRDGenerationInfo getCrdInfo() {
return crdInfo;
}
public boolean isStartOperator() {
return startOperator;
}
public boolean isCloseClientOnStop() {
return closeClientOnStop;
}
public boolean isStopOnInformerErrorDuringStartup() {
return stopOnInformerErrorDuringStartup;
}
public boolean isEnableSSA() {
return enableSSA;
}
public boolean activateLeaderElection(List<String> activeProfiles) {
return activeProfiles.stream().anyMatch(leaderElectionActivationProfiles::contains);
}
public List<String> getLeaderElectionActivationProfiles() {
return leaderElectionActivationProfiles;
}
public boolean isDefensiveCloning() {
return defensiveCloning;
}
@Override
public DependentResourceFactory<QuarkusBuildTimeControllerConfiguration<?>, DependentResourceSpecMetadata<?, ?, ?>> dependentResourceFactory() {
return this;
}
@Override
public Class<?> associatedResourceType(DependentResourceSpecMetadata spec) {
return spec.getResourceClass();
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/QuarkusManagedWorkflow.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/QuarkusManagedWorkflow.java | package io.quarkiverse.operatorsdk.runtime;
import java.util.List;
import java.util.Optional;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.javaoperatorsdk.operator.api.config.ControllerConfiguration;
import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceSpec;
import io.javaoperatorsdk.operator.api.config.workflow.WorkflowSpec;
import io.javaoperatorsdk.operator.processing.dependent.workflow.DefaultManagedWorkflow;
import io.javaoperatorsdk.operator.processing.dependent.workflow.Workflow;
import io.quarkus.runtime.annotations.IgnoreProperty;
import io.quarkus.runtime.annotations.RecordableConstructor;
@SuppressWarnings("rawtypes")
public class QuarkusManagedWorkflow<P extends HasMetadata> extends DefaultManagedWorkflow<P> {
private final QuarkusWorkflowSpec spec;
public static final Workflow noOpWorkflow = new NoOpWorkflow();
public static final QuarkusManagedWorkflow noOpManagedWorkflow = new NoOpManagedWorkflow();
public static class NoOpWorkflow<P extends HasMetadata> implements Workflow<P> {
}
public static class NoOpManagedWorkflow<P extends HasMetadata> extends QuarkusManagedWorkflow<P> {
@Override
@SuppressWarnings("unchecked")
public Workflow<P> resolve(KubernetesClient kubernetesClient,
ControllerConfiguration<P> controllerConfiguration) {
return noOpWorkflow;
}
}
private QuarkusManagedWorkflow() {
this(null, List.of(), false);
}
@RecordableConstructor
public QuarkusManagedWorkflow(QuarkusWorkflowSpec nullableSpec, List<DependentResourceSpec> orderedSpecs,
boolean hasCleaner) {
super(orderedSpecs, hasCleaner);
this.spec = nullableSpec;
}
// Getter required for Quarkus' RecordableConstructor, must match the associated constructor parameter name
@SuppressWarnings("unused")
public boolean isHasCleaner() {
return hasCleaner();
}
// Getter required for Quarkus' RecordableConstructor, must match the associated constructor parameter name
@SuppressWarnings("unused")
public QuarkusWorkflowSpec getNullableSpec() {
return spec;
}
@IgnoreProperty
public Optional<QuarkusWorkflowSpec> getSpec() {
return Optional.ofNullable(spec);
}
@IgnoreProperty
public Optional<WorkflowSpec> getGenericSpec() {
return Optional.ofNullable(spec);
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/CRDGenerationInfo.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/CRDGenerationInfo.java | package io.quarkiverse.operatorsdk.runtime;
import java.util.Map;
import java.util.Set;
import io.quarkus.runtime.annotations.IgnoreProperty;
import io.quarkus.runtime.annotations.RecordableConstructor;
public class CRDGenerationInfo {
private final boolean applyCRDs;
private final boolean validateCRDs;
private final CRDInfos crds;
private final Set<String> generated;
@RecordableConstructor // constructor needs to be recordable for the class to be passed around by Quarkus
public CRDGenerationInfo(boolean applyCRDs, boolean validateCRDs, CRDInfos crds,
Set<String> generated) {
this.applyCRDs = applyCRDs;
this.validateCRDs = validateCRDs;
this.crds = crds;
this.generated = generated;
}
// Getter required for Quarkus' RecordableConstructor, must match the associated constructor parameter name
public CRDInfos getCrds() {
return crds;
}
// Getter required for Quarkus' RecordableConstructor, must match the associated constructor parameter name
public Set<String> getGenerated() {
return generated;
}
// Getter required for Quarkus' RecordableConstructor, must match the associated constructor parameter name
public boolean isApplyCRDs() {
return applyCRDs;
}
@IgnoreProperty
public Map<String, CRDInfo> getCRDInfosFor(String crdName) {
return crds.getOrCreateCRDSpecVersionToInfoMapping(crdName);
}
// Getter required for Quarkus' RecordableConstructor, must match the associated constructor parameter name
public boolean isValidateCRDs() {
return validateCRDs;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/ResourceInfo.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/ResourceInfo.java | package io.quarkiverse.operatorsdk.runtime;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.Namespaced;
import io.fabric8.kubernetes.model.Scope;
import io.quarkus.runtime.annotations.RecordableConstructor;
public class ResourceInfo {
private final String group;
private final String version;
private final String kind;
private final String singular;
private final String plural;
private final String[] shortNames;
private final boolean storage;
private final boolean served;
private final Scope scope;
private final String resourceClassName;
private final boolean statusPresentAndNotVoid;
private final String resourceFullName;
private final String controllerName;
@RecordableConstructor
public ResourceInfo(String group, String version, String kind, String singular, String plural, String[] shortNames,
boolean storage, boolean served, Scope scope, String resourceClassName, boolean statusPresentAndNotVoid,
String resourceFullName,
String controllerName) {
this.group = group;
this.version = version;
this.kind = kind;
this.singular = singular;
this.plural = plural;
this.shortNames = shortNames;
this.storage = storage;
this.served = served;
this.scope = scope;
this.resourceClassName = resourceClassName;
this.statusPresentAndNotVoid = statusPresentAndNotVoid;
this.resourceFullName = resourceFullName;
this.controllerName = controllerName;
}
public String getGroup() {
return group;
}
public String getVersion() {
return version;
}
public String getKind() {
return kind;
}
public String getSingular() {
return singular;
}
public String getPlural() {
return plural;
}
public String[] getShortNames() {
return shortNames;
}
public boolean isStorage() {
return storage;
}
public boolean isServed() {
return served;
}
public Scope getScope() {
return scope;
}
public String getResourceClassName() {
return resourceClassName;
}
public boolean isStatusPresentAndNotVoid() {
return statusPresentAndNotVoid;
}
public String getResourceFullName() {
return resourceFullName;
}
public String getControllerName() {
return controllerName;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ResourceInfo that = (ResourceInfo) o;
if (!group.equals(that.group))
return false;
if (!version.equals(that.version))
return false;
return kind.equals(that.kind);
}
@Override
public int hashCode() {
int result = group.hashCode();
result = 31 * result + version.hashCode();
result = 31 * result + kind.hashCode();
return result;
}
public static ResourceInfo createFrom(Class<? extends HasMetadata> resourceClass,
String resourceFullName, String associatedControllerName, boolean hasStatus) {
Scope scope = Namespaced.class.isAssignableFrom(resourceClass) ? Scope.NAMESPACED : Scope.CLUSTER;
return new ResourceInfo(HasMetadata.getGroup(resourceClass),
HasMetadata.getVersion(resourceClass),
HasMetadata.getKind(resourceClass), HasMetadata.getSingular(resourceClass),
HasMetadata.getPlural(resourceClass), new String[0],
false, false, scope, resourceClass.getCanonicalName(),
hasStatus,
resourceFullName, associatedControllerName);
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/QuarkusControllerConfiguration.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/QuarkusControllerConfiguration.java | package io.quarkiverse.operatorsdk.runtime;
import java.time.Duration;
import java.util.Optional;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.javaoperatorsdk.operator.api.config.ConfigurationService;
import io.javaoperatorsdk.operator.api.config.ControllerConfiguration;
import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceSpec;
import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration;
import io.javaoperatorsdk.operator.api.config.workflow.WorkflowSpec;
import io.javaoperatorsdk.operator.processing.event.rate.RateLimiter;
import io.javaoperatorsdk.operator.processing.retry.Retry;
public class QuarkusControllerConfiguration<P extends HasMetadata> implements ControllerConfiguration<P> {
private final InformerConfiguration<P> informerConfig;
private final String name;
private final boolean generationAware;
private final String associatedReconcilerClassName;
private final Retry retry;
private final RateLimiter<?> rateLimiter;
private final Duration maxReconciliationInterval;
private final String finalizer;
private final String fieldManager;
private final QuarkusManagedWorkflow<P> workflow;
private final String resourceTypeName;
private final Class<P> resourceClass;
private QuarkusConfigurationService configurationService;
@SuppressWarnings("rawtypes")
public QuarkusControllerConfiguration(InformerConfiguration<P> informerConfig, String name, boolean generationAware,
String associatedReconcilerClassName, Retry retry, RateLimiter rateLimiter, Duration maxReconciliationInterval,
String finalizer, String fieldManager,
QuarkusManagedWorkflow<P> workflow, String resourceTypeName, Class<P> resourceClass) {
this.informerConfig = informerConfig;
this.name = name;
this.generationAware = generationAware;
this.associatedReconcilerClassName = associatedReconcilerClassName;
this.retry = retry;
this.rateLimiter = rateLimiter;
this.maxReconciliationInterval = maxReconciliationInterval;
this.finalizer = finalizer;
this.fieldManager = fieldManager;
this.workflow = workflow;
this.resourceTypeName = resourceTypeName;
this.resourceClass = resourceClass;
}
protected void setParent(QuarkusConfigurationService configurationService) {
this.configurationService = configurationService;
}
@Override
public String getName() {
return name;
}
@Override
public String getFinalizerName() {
return finalizer;
}
@Override
public boolean isGenerationAware() {
return generationAware;
}
@Override
public String getAssociatedReconcilerClassName() {
return associatedReconcilerClassName;
}
@Override
public Retry getRetry() {
return retry;
}
@SuppressWarnings("rawtypes")
@Override
public RateLimiter getRateLimiter() {
return rateLimiter;
}
@Override
public Optional<WorkflowSpec> getWorkflowSpec() {
return workflow.getGenericSpec();
}
@Override
public Optional<Duration> maxReconciliationInterval() {
return Optional.of(maxReconciliationInterval);
}
@Override
public ConfigurationService getConfigurationService() {
return configurationService;
}
@Override
public String fieldManager() {
return fieldManager;
}
@Override
public <C> C getConfigurationFor(DependentResourceSpec<?, P, C> dependentResourceSpec) {
return dependentResourceSpec.getConfiguration().orElse(null);
}
@Override
public String getResourceTypeName() {
return resourceTypeName;
}
@Override
public InformerConfiguration<P> getInformerConfig() {
return informerConfig;
}
@Override
public Class<P> getResourceClass() {
return resourceClass;
}
public QuarkusManagedWorkflow<P> getWorkflow() {
return workflow;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/CRDUtils.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/CRDUtils.java | package io.quarkiverse.operatorsdk.runtime;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import org.jboss.logging.Logger;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinition;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.utils.KubernetesSerialization;
public final class CRDUtils {
private static final Logger LOGGER = Logger.getLogger(CRDUtils.class.getName());
private static final KubernetesSerialization SERIALIZATION = new KubernetesSerialization(new ObjectMapper(), false);
public final static String DEFAULT_CRD_SPEC_VERSION = "v1";
public static final String V1BETA1_CRD_SPEC_VERSION = "v1beta1";
private CRDUtils() {
}
public static String crdNameFor(Class<? extends HasMetadata> clazz) {
return HasMetadata.getFullResourceName(clazz);
}
public static void applyCRD(KubernetesClient client, CRDGenerationInfo crdInfo, String crdName) {
try {
crdInfo.getCRDInfosFor(crdName).forEach((unused, info) -> {
final var filePath = Path.of(info.getFilePath());
final var crdSpecVersion = info.getCrdSpecVersion();
try {
final var crd = loadFrom(filePath, client.getKubernetesSerialization(), getCRDClassFor(crdSpecVersion));
apply(client, crdSpecVersion, crd);
LOGGER.infof("Applied %s CRD named '%s' from %s", crdSpecVersion, crdName, filePath);
} catch (IOException ex) {
throw new IllegalArgumentException("Couldn't read CRD file at " + filePath
+ " as a " + crdSpecVersion + " CRD for " + crdName, ex);
}
});
} catch (Exception exception) {
LOGGER.warnf(exception, "Couldn't apply '%s' CRD", crdName);
}
}
private static <T> T loadFrom(Path crdPath, KubernetesSerialization serialization, Class<T> crdClass) throws IOException {
serialization = serialization == null ? SERIALIZATION : serialization;
return serialization.unmarshal(Files.newInputStream(crdPath), crdClass);
}
public static CustomResourceDefinition loadFrom(Path crdPath) throws IOException {
final var crd = loadFrom(crdPath, null, CustomResourceDefinition.class);
final var crdVersion = crd.getApiVersion().split("/")[1];
if (!DEFAULT_CRD_SPEC_VERSION.equals(crdVersion)) {
LOGGER.warnf(
"CRD at %s was loaded as a %s CRD but is defined as using %s CRD spec version. While things might still work as expected, we recommend that you only use CRDs using the %s CRD spec version.",
crdPath, DEFAULT_CRD_SPEC_VERSION, crdVersion, DEFAULT_CRD_SPEC_VERSION);
}
return crd;
}
public static CRDInfo loadFromAsCRDInfo(Path crdPath) {
try {
final var crd = loadFrom(crdPath);
final var crdName = crd.getMetadata().getName();
return new CRDInfo(crdName, DEFAULT_CRD_SPEC_VERSION, crdPath.toFile().getAbsolutePath(), Collections.emptySet());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void apply(KubernetesClient client, String v, Object crd) {
switch (v) {
case DEFAULT_CRD_SPEC_VERSION:
final var resource = client.apiextensions().v1().customResourceDefinitions()
.resource((CustomResourceDefinition) crd);
if (resource.get() != null) {
resource.update();
} else {
resource.create();
}
break;
case V1BETA1_CRD_SPEC_VERSION:
final var legacyResource = client.apiextensions().v1beta1().customResourceDefinitions()
.resource((io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceDefinition) crd);
if (legacyResource.get() != null) {
legacyResource.update();
} else {
legacyResource.create();
}
break;
default:
throw new IllegalArgumentException("Unknown CRD version: " + v);
}
}
private static Class<?> getCRDClassFor(String v) {
return switch (v) {
case DEFAULT_CRD_SPEC_VERSION -> CustomResourceDefinition.class;
case V1BETA1_CRD_SPEC_VERSION ->
io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceDefinition.class;
default -> throw new IllegalArgumentException("Unknown CRD version: " + v);
};
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/QuarkusBuildTimeControllerConfiguration.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/QuarkusBuildTimeControllerConfiguration.java | package io.quarkiverse.operatorsdk.runtime;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import org.jboss.logging.Logger;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.rbac.PolicyRule;
import io.fabric8.kubernetes.api.model.rbac.RoleRef;
import io.fabric8.kubernetes.client.informers.cache.ItemStore;
import io.javaoperatorsdk.operator.ReconcilerUtils;
import io.javaoperatorsdk.operator.api.config.ControllerConfiguration;
import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceSpec;
import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration;
import io.javaoperatorsdk.operator.api.config.workflow.WorkflowSpec;
import io.javaoperatorsdk.operator.processing.event.rate.LinearRateLimiter;
import io.javaoperatorsdk.operator.processing.event.rate.RateLimiter;
import io.javaoperatorsdk.operator.processing.event.source.filter.GenericFilter;
import io.javaoperatorsdk.operator.processing.event.source.filter.OnAddFilter;
import io.javaoperatorsdk.operator.processing.event.source.filter.OnUpdateFilter;
import io.javaoperatorsdk.operator.processing.retry.GenericRetry;
import io.javaoperatorsdk.operator.processing.retry.Retry;
import io.quarkus.runtime.annotations.IgnoreProperty;
import io.quarkus.runtime.annotations.RecordableConstructor;
@SuppressWarnings("rawtypes")
public class QuarkusBuildTimeControllerConfiguration<R extends HasMetadata> implements ControllerConfiguration<R> {
private static final Logger log = Logger.getLogger(QuarkusBuildTimeControllerConfiguration.class);
private final String associatedReconcilerClassName;
private final String name;
private final String resourceTypeName;
private final boolean generationAware;
private final boolean statusPresentAndNotVoid;
private final Class<R> resourceClass;
private final List<PolicyRule> additionalRBACRules;
private final List<RoleRef> additionalRBACRoleRefs;
private final String fieldManager;
private final boolean triggerReconcilerOnAllEvents;
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private Optional<Duration> maxReconciliationInterval;
private String finalizer;
private boolean wereNamespacesSet;
private final Retry retry;
private final RateLimiter rateLimiter;
private QuarkusManagedWorkflow<R> workflow;
private BuildTimeConfigurationService parent;
private QuarkusInformerConfiguration<R> informerConfig;
private Set<String> namespaces;
private String labelSelector;
private QuarkusFieldSelector fieldSelector;
@RecordableConstructor
@SuppressWarnings("unchecked")
public QuarkusBuildTimeControllerConfiguration(
String associatedReconcilerClassName,
String name,
String resourceTypeName,
boolean generationAware,
Class resourceClass,
boolean wereNamespacesSet,
String finalizerName,
boolean statusPresentAndNotVoid,
Duration maxReconciliationInterval,
Retry retry, RateLimiter rateLimiter,
List<PolicyRule> additionalRBACRules,
List<RoleRef> additionalRBACRoleRefs,
String fieldManager,
QuarkusInformerConfiguration<R> informerConfig,
boolean triggerReconcilerOnAllEvents) {
this.informerConfig = informerConfig;
this.associatedReconcilerClassName = associatedReconcilerClassName;
this.name = name;
this.resourceTypeName = resourceTypeName;
this.generationAware = generationAware;
this.resourceClass = resourceClass;
this.additionalRBACRules = additionalRBACRules;
this.additionalRBACRoleRefs = additionalRBACRoleRefs;
this.wereNamespacesSet = wereNamespacesSet;
setFinalizer(finalizerName);
this.statusPresentAndNotVoid = statusPresentAndNotVoid;
this.maxReconciliationInterval = maxReconciliationInterval != null ? Optional.of(maxReconciliationInterval)
: ControllerConfiguration.super.maxReconciliationInterval();
this.retry = retry == null ? new GenericRetry() : retry;
this.rateLimiter = rateLimiter == null ? new DefaultRateLimiter() : rateLimiter;
this.fieldManager = fieldManager != null ? fieldManager : ControllerConfiguration.super.fieldManager();
this.triggerReconcilerOnAllEvents = triggerReconcilerOnAllEvents;
}
@Override
@IgnoreProperty
public BuildTimeConfigurationService getConfigurationService() {
return parent;
}
public void setParent(BuildTimeConfigurationService parent) {
this.parent = parent;
}
@Override
public Class<R> getResourceClass() {
return resourceClass;
}
@Override
public String getName() {
return name;
}
@Override
public String getResourceTypeName() {
return resourceTypeName;
}
@Override
public String getFinalizerName() {
return finalizer;
}
public void setFinalizer(String finalizer) {
this.finalizer = finalizer != null && !finalizer.isBlank() ? finalizer
: ReconcilerUtils.getDefaultFinalizerName(resourceTypeName);
}
@Override
public boolean isGenerationAware() {
return generationAware;
}
@Override
public String getAssociatedReconcilerClassName() {
return associatedReconcilerClassName;
}
void setNamespaces(Set<String> namespaces) {
if (!namespaces.equals(informerConfig.getNamespaces())) {
this.namespaces = namespaces;
wereNamespacesSet = true;
}
}
public boolean isWereNamespacesSet() {
return wereNamespacesSet;
}
@IgnoreProperty
@Override
public Set<String> getEffectiveNamespaces() {
return ControllerConfiguration.super.getEffectiveNamespaces();
}
void setLabelSelector(String labelSelector) {
if (!Objects.equals(informerConfig.getLabelSelector(), labelSelector)) {
this.labelSelector = labelSelector;
}
}
void setFieldSelector(List<String> fieldSelectors) {
if (!Objects.equals(informerConfig.getFieldSelector(), fieldSelectors)) {
this.fieldSelector = QuarkusFieldSelector.from(fieldSelectors, resourceClass, parent);
}
}
public boolean isStatusPresentAndNotVoid() {
return statusPresentAndNotVoid;
}
public boolean areDependentsImpactedBy(Set<String> changedClasses) {
return dependentsMetadata().keySet().parallelStream().anyMatch(changedClasses::contains);
}
public boolean needsDependentBeansCreation() {
final var dependentsMetadata = dependentsMetadata();
return dependentsMetadata != null && !dependentsMetadata.isEmpty();
}
public QuarkusManagedWorkflow<R> getWorkflow() {
return workflow;
}
public void setWorkflow(QuarkusManagedWorkflow<R> workflow) {
this.workflow = workflow;
}
@Override
@SuppressWarnings("unchecked")
public Object getConfigurationFor(DependentResourceSpec dependentResourceSpec) {
return dependentResourceSpec.getConfiguration().orElse(null);
}
@Override
public Optional<WorkflowSpec> getWorkflowSpec() {
return workflow.getGenericSpec();
}
@Override
public Retry getRetry() {
return retry;
}
@Override
public RateLimiter getRateLimiter() {
return rateLimiter;
}
public Optional<Duration> maxReconciliationInterval() {
return maxReconciliationInterval;
}
// for Quarkus' RecordableConstructor
@SuppressWarnings("unused")
public Duration getMaxReconciliationInterval() {
return maxReconciliationInterval.orElseThrow();
}
void setMaxReconciliationInterval(Duration duration) {
maxReconciliationInterval = Optional.of(duration);
}
// for Quarkus' RecordableConstructor
@SuppressWarnings("unused")
public OnAddFilter<? super R> getOnAddFilter() {
return getInformerConfig().getOnAddFilter();
}
// for Quarkus' RecordableConstructor
@SuppressWarnings("unused")
public OnUpdateFilter<? super R> getOnUpdateFilter() {
return getInformerConfig().getOnUpdateFilter();
}
// for Quarkus' RecordableConstructor
@SuppressWarnings("unused")
public GenericFilter<? super R> getGenericFilter() {
return getInformerConfig().getGenericFilter();
}
public Map<String, DependentResourceSpecMetadata> dependentsMetadata() {
return workflow.getSpec().map(QuarkusWorkflowSpec::getDependentResourceSpecMetadata).orElse(Collections.emptyMap());
}
void updateRetryConfiguration(ExternalGradualRetryConfiguration externalGradualRetryConfiguration) {
// override with configuration from application.properties (if it exists) for GradualRetry
if (externalGradualRetryConfiguration != null) {
if (!(retry instanceof GenericRetry genericRetry)) {
log.warnf(
"Retry configuration in application.properties is only appropriate when using the GenericRetry implementation, yet your Reconciler is configured to use %s as Retry implementation. Configuration from application.properties will therefore be ignored.",
retry.getClass().getName());
return;
}
// configurable should be a GenericRetry as validated by RetryResolver
externalGradualRetryConfiguration.maxAttempts().ifPresent(genericRetry::setMaxAttempts);
final var intervalConfiguration = externalGradualRetryConfiguration.interval();
intervalConfiguration.initial().ifPresent(genericRetry::setInitialInterval);
intervalConfiguration.max().ifPresent(genericRetry::setMaxInterval);
intervalConfiguration.multiplier().ifPresent(genericRetry::setIntervalMultiplier);
}
}
public List<PolicyRule> getAdditionalRBACRules() {
return additionalRBACRules;
}
public List<RoleRef> getAdditionalRBACRoleRefs() {
return additionalRBACRoleRefs;
}
@SuppressWarnings("unused")
// this is needed by Quarkus for the RecordableConstructor
public String getFieldManager() {
return fieldManager;
}
@Override
public String fieldManager() {
return fieldManager;
}
@SuppressWarnings("unused")
// this is needed by Quarkus for the RecordableConstructor
public ItemStore<R> getNullableItemStore() {
return getInformerConfig().getItemStore();
}
@Override
public InformerConfiguration<R> getInformerConfig() {
if (labelSelector != null || fieldSelector != null || namespaces != null) {
final var builder = InformerConfiguration.builder(informerConfig);
if (namespaces != null) {
builder.withNamespaces(namespaces);
}
if (fieldSelector != null) {
builder.withFieldSelector(fieldSelector);
}
if (labelSelector != null) {
builder.withLabelSelector(labelSelector);
}
informerConfig = new QuarkusInformerConfiguration<>(builder.buildForController());
// reset so that we know that we don't need to regenerate the informer config next time if these values haven't changed since
labelSelector = null;
fieldSelector = null;
namespaces = null;
}
return informerConfig;
}
// Needed by Quarkus because LinearRateLimiter doesn't expose setters for byte recording
public final static class DefaultRateLimiter extends LinearRateLimiter {
public DefaultRateLimiter() {
super();
}
@RecordableConstructor
@SuppressWarnings("unused")
public DefaultRateLimiter(Duration refreshPeriod, int limitForPeriod) {
super(refreshPeriod, limitForPeriod);
}
}
@SuppressWarnings("unused")
// this is needed by Quarkus for the RecordableConstructor
public boolean isTriggerReconcilerOnAllEvents() {
return triggerReconcilerOnAllEvents;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/NoOpMetricsProvider.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/NoOpMetricsProvider.java | package io.quarkiverse.operatorsdk.runtime;
import jakarta.enterprise.inject.Produces;
import jakarta.inject.Singleton;
import io.javaoperatorsdk.operator.api.monitoring.Metrics;
import io.quarkus.arc.DefaultBean;
@Singleton
public class NoOpMetricsProvider {
@Produces
@DefaultBean
public Metrics getMetrics() {
return Metrics.NOOP;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/OperatorProducer.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/OperatorProducer.java | package io.quarkiverse.operatorsdk.runtime;
import java.time.Duration;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.enterprise.inject.Produces;
import jakarta.inject.Singleton;
import org.jboss.logging.Logger;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.javaoperatorsdk.operator.Operator;
import io.javaoperatorsdk.operator.api.config.ControllerConfigurationOverrider;
import io.javaoperatorsdk.operator.api.reconciler.MaxReconciliationInterval;
import io.javaoperatorsdk.operator.api.reconciler.Reconciler;
import io.quarkiverse.operatorsdk.runtime.api.ConfigurableReconciler;
import io.quarkus.arc.DefaultBean;
@Singleton
public class OperatorProducer {
private static final Logger log = Logger.getLogger(OperatorProducer.class);
@SuppressWarnings({ "rawtypes", "unchecked" })
private static <P extends HasMetadata> void register(QuarkusConfigurationService configurationService,
Reconciler<P> reconciler, Operator operator) {
if (reconciler instanceof ConfigurableReconciler configurable) {
final var conf = configurationService.getConfigurationFor(reconciler);
if (conf != null) {
final var override = ControllerConfigurationOverrider.override(conf);
configurable.updateConfigurationFrom(override);
final var updated = override.build();
final Duration maxReconciliationInterval = updated.maxReconciliationInterval()
.orElse(Duration.ofHours(MaxReconciliationInterval.DEFAULT_INTERVAL));
final var qConf = new QuarkusControllerConfiguration(updated.getInformerConfig(), updated.getName(),
updated.isGenerationAware(), conf.getAssociatedReconcilerClassName(), updated.getRetry(),
updated.getRateLimiter(), maxReconciliationInterval, updated.getFinalizerName(), updated.fieldManager(),
conf.getWorkflow(), conf.getResourceTypeName(), conf.getResourceClass());
qConf.setParent(configurationService);
operator.register(reconciler, qConf);
return;
}
}
operator.register(reconciler);
}
/**
* Produces an application-scoped Operator, given the provided configuration and detected reconcilers. We previously
* produced the operator instance as singleton-scoped but this prevents being able to inject the operator instance in
* reconcilers (which we don't necessarily recommend but might be needed for corner cases) due to an infinite loop.
* ApplicationScoped being proxy-based allows for breaking the cycle, thus allowing the operator-reconciler parent-child
* relation to be handled by CDI.
*
* @param configuration the {@link QuarkusConfigurationService} providing the configuration for the operator and controllers
* @param reconcilers the detected {@link Reconciler} implementations
* @return a properly configured {@link Operator} instance
*/
@Produces
@DefaultBean
@ApplicationScoped
Operator operator(QuarkusConfigurationService configuration, Instance<Reconciler<? extends HasMetadata>> reconcilers) {
if (configuration.getVersion() instanceof Version version) {
log.infof("Quarkus Java Operator SDK extension %s", version.getExtensionCompleteVersion());
}
// if some CRDs just got generated and need to be applied, apply them
final var crdInfo = configuration.getCRDGenerationInfo();
if (crdInfo.isApplyCRDs()) {
for (String generatedCrdName : crdInfo.getGenerated()) {
CRDUtils.applyCRD(configuration.getKubernetesClient(), crdInfo, generatedCrdName);
}
}
Operator operator = new Operator(configuration);
for (Reconciler<? extends HasMetadata> reconciler : reconcilers) {
register(configuration, reconciler, operator);
}
// if we set a termination timeout, install a shutdown hook
final var terminationTimeoutSeconds = configuration.getTerminationTimeoutSeconds();
if (QuarkusConfigurationService.UNSET_TERMINATION_TIMEOUT_SECONDS != terminationTimeoutSeconds) {
operator.installShutdownHook(Duration.ofSeconds(terminationTimeoutSeconds));
}
return operator;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/CRDInfos.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/CRDInfos.java | package io.quarkiverse.operatorsdk.runtime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import io.quarkus.runtime.annotations.IgnoreProperty;
import io.quarkus.runtime.annotations.RecordableConstructor;
public class CRDInfos {
private final Map<String, Map<String, CRDInfo>> nameToSpecVersionToInfos;
public CRDInfos() {
this(new ConcurrentHashMap<>());
}
public CRDInfos(CRDInfos other) {
this(new ConcurrentHashMap<>(other.nameToSpecVersionToInfos));
}
@RecordableConstructor // constructor needs to be recordable for the class to be passed around by Quarkus
private CRDInfos(Map<String, Map<String, CRDInfo>> infos) {
this.nameToSpecVersionToInfos = infos;
}
@IgnoreProperty
public Map<String, CRDInfo> getOrCreateCRDSpecVersionToInfoMapping(String crdName) {
return nameToSpecVersionToInfos.computeIfAbsent(crdName, k -> new HashMap<>());
}
@IgnoreProperty
public Map<String, CRDInfo> getCRDNameToInfoMappings() {
return nameToSpecVersionToInfos
.values().stream()
// only keep CRD v1 infos
.flatMap(entry -> entry.values().stream()
.filter(crdInfo -> CRDUtils.DEFAULT_CRD_SPEC_VERSION.equals(crdInfo.getCrdSpecVersion())))
.collect(Collectors.toMap(CRDInfo::getCrdName, Function.identity()));
}
public CRDInfo addCRDInfo(CRDInfo crdInfo) {
return getOrCreateCRDSpecVersionToInfoMapping(crdInfo.getCrdName()).put(crdInfo.getCrdSpecVersion(), crdInfo);
}
// Needed by Quarkus: if this method isn't present, state is not properly set
@SuppressWarnings("unused")
public Map<String, Map<String, CRDInfo>> getInfos() {
return nameToSpecVersionToInfos;
}
public boolean contains(String crdId) {
return nameToSpecVersionToInfos.containsKey(crdId);
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/Constants.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/Constants.java | package io.quarkiverse.operatorsdk.runtime;
import java.util.Collections;
import java.util.Set;
public final class Constants {
private Constants() {
}
public static final Set<String> QOSDK_USE_BUILDTIME_NAMESPACES_SET = Collections
.singleton(Constants.QOSDK_USE_BUILDTIME_NAMESPACES);
public static final String QOSDK_USE_BUILDTIME_NAMESPACES = "QOSDK_USE_BUILDTIME_NAMESPACES";
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/RunTimeOperatorConfiguration.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/RunTimeOperatorConfiguration.java | /**
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.quarkiverse.operatorsdk.runtime;
import static io.quarkiverse.operatorsdk.runtime.Constants.QOSDK_USE_BUILDTIME_NAMESPACES;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import io.javaoperatorsdk.operator.api.reconciler.Constants;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;
import io.smallrye.config.ConfigMapping;
import io.smallrye.config.WithDefault;
@ConfigMapping(prefix = "quarkus.operator-sdk")
@ConfigRoot(phase = ConfigPhase.RUN_TIME)
public interface RunTimeOperatorConfiguration {
/**
* Maps a controller name to its configuration.
*/
Map<String, RunTimeControllerConfiguration> controllers();
/**
* The max number of concurrent dispatches of reconciliation requests to controllers.
*/
Optional<Integer> concurrentReconciliationThreads();
/**
* Amount of seconds the SDK waits for reconciliation threads to terminate before shutting down. Setting this value will
* install a shutdown hook to wait for termination (causing
* {@link io.javaoperatorsdk.operator.Operator#installShutdownHook(Duration)} to be called with
* `Duration.ofSeconds(terminationTimeoutSeconds)`).
*/
Optional<Integer> terminationTimeoutSeconds();
/**
* An optional list of comma-separated namespace names all controllers will watch if they do not specify their own list. If
* a controller specifies its own list either via the
* {@link io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration} annotation or via the associated
* {@code application.properties} property, that value will be used instead of the operator-level default value that this
* configuration option provides.
*
* <p>
* If this property is left empty then controllers will watch all namespaces by default (which is equivalent to setting this
* property to {@link Constants#WATCH_ALL_NAMESPACES}, assuming they do not provide their own list of namespaces to watch. .
* The value can be set to {@link Constants#WATCH_CURRENT_NAMESPACE} to make all controllers watch the current namespace as
* specified by the kube config file the operator uses.
* </p>
*/
// We use a default here so that we are able to detect if the configuration value is set to "". Setting the value to "" will
// reset the configuration and result in an empty Optional, but not setting the value at all will result in the default being
// applied.
@WithDefault(QOSDK_USE_BUILDTIME_NAMESPACES)
Optional<List<String>> namespaces();
/**
* The max number of concurrent workflow processing requests.
*/
Optional<Integer> concurrentWorkflowThreads();
/**
* How long the operator will wait for informers to finish synchronizing their caches on startup
* before timing out.
*/
@WithDefault("2M")
Duration cacheSyncTimeout();
/**
* Whether or not starting the operator should occur asynchronously. This is useful when your operator starts slowly (which
* can happen if you have lots of resources that need to be put in the informers' caches), resulting in HTTP probes not
* being exposed quickly enough to prevent Kubernetes from considering your operator unhealthy and thus attempting to
* restart it.
*/
@WithDefault("false")
Boolean asyncStart();
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/ConfigurationServiceRecorder.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/ConfigurationServiceRecorder.java | package io.quarkiverse.operatorsdk.runtime;
import static io.javaoperatorsdk.operator.api.reconciler.Constants.DEFAULT_NAMESPACES_SET;
import static io.quarkiverse.operatorsdk.runtime.Constants.QOSDK_USE_BUILDTIME_NAMESPACES_SET;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
import org.jboss.logging.Logger;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.javaoperatorsdk.operator.api.config.ConfigurationService;
import io.javaoperatorsdk.operator.api.config.InformerStoppedHandler;
import io.javaoperatorsdk.operator.api.config.LeaderElectionConfiguration;
import io.javaoperatorsdk.operator.api.monitoring.Metrics;
import io.quarkus.arc.Arc;
import io.quarkus.runtime.RuntimeValue;
import io.quarkus.runtime.annotations.Recorder;
import io.quarkus.runtime.configuration.ConfigUtils;
@Recorder
public class ConfigurationServiceRecorder {
static final Logger log = Logger.getLogger(ConfigurationServiceRecorder.class.getName());
private final RuntimeValue<RunTimeOperatorConfiguration> runTimeConfigurationRuntimeValue;
public ConfigurationServiceRecorder(RuntimeValue<RunTimeOperatorConfiguration> runTimeConfigurationRuntimeValue) {
this.runTimeConfigurationRuntimeValue = runTimeConfigurationRuntimeValue;
}
@SuppressWarnings({ "rawtypes", "unchecked", "resource" })
public Supplier<QuarkusConfigurationService> configurationServiceSupplier(
BuildTimeConfigurationService buildTimeConfigurationService,
Map<String, QuarkusBuildTimeControllerConfiguration<?>> configurations) {
final var runTimeConfiguration = runTimeConfigurationRuntimeValue.getValue();
final var maxThreads = runTimeConfiguration.concurrentReconciliationThreads()
.orElse(ConfigurationService.DEFAULT_RECONCILIATION_THREADS_NUMBER);
final var timeout = runTimeConfiguration.terminationTimeoutSeconds()
.orElse(QuarkusConfigurationService.UNSET_TERMINATION_TIMEOUT_SECONDS);
final var workflowThreads = runTimeConfiguration.concurrentWorkflowThreads()
.orElse(ConfigurationService.DEFAULT_WORKFLOW_EXECUTOR_THREAD_NUMBER);
final var cacheSyncTimeout = runTimeConfiguration.cacheSyncTimeout();
final var asyncStart = runTimeConfiguration.asyncStart();
final var externalControllerConfigs = runTimeConfiguration.controllers();
final List<QuarkusControllerConfiguration> runtimeConfigurations = configurations.values().stream().map(c -> {
final var extConfig = externalControllerConfigs.get(c.getName());
// then override with controller-specific configuration if present
if (extConfig != null) {
extConfig.finalizer().ifPresent(c::setFinalizer);
extConfig.selector().ifPresent(c::setLabelSelector);
extConfig.fieldSelectors().ifPresent(c::setFieldSelector);
extConfig.maxReconciliationInterval().ifPresent(c::setMaxReconciliationInterval);
c.updateRetryConfiguration(extConfig.retry());
setNamespacesFromRuntime(c, extConfig.namespaces());
}
// if the namespaces weren't set on controller level or as an annotation, use the operator-level configuration if it exists
if (!c.isWereNamespacesSet()) {
setNamespacesFromRuntime(c, runTimeConfiguration.namespaces());
}
return new QuarkusControllerConfiguration(c.getInformerConfig(), c.getName(), c.isGenerationAware(),
c.getAssociatedReconcilerClassName(), c.getRetry(), c.getRateLimiter(),
c.getMaxReconciliationInterval(), c.getFinalizerName(), c.fieldManager(), c.getWorkflow(),
c.getResourceTypeName(), c.getResourceClass());
}).toList();
return () -> {
final var container = Arc.container();
// deactivate leader election in dev mode
LeaderElectionConfiguration leaderElectionConfiguration = null;
final var profiles = ConfigUtils.getProfiles();
if (buildTimeConfigurationService.activateLeaderElection(profiles)) {
leaderElectionConfiguration = container.instance(LeaderElectionConfiguration.class).get();
} else {
log.infof(
"Leader election deactivated because it is only activated for %s profiles. Currently active profiles: %s",
buildTimeConfigurationService.getLeaderElectionActivationProfiles(),
profiles);
}
return new QuarkusConfigurationService(
buildTimeConfigurationService.getVersion(),
runtimeConfigurations,
container.instance(KubernetesClient.class).get(),
buildTimeConfigurationService.getCrdInfo(),
maxThreads,
workflowThreads,
timeout,
cacheSyncTimeout,
asyncStart,
container.instance(Metrics.class).get(),
buildTimeConfigurationService.isStartOperator(),
leaderElectionConfiguration,
container.instance(InformerStoppedHandler.class).orElse(null),
buildTimeConfigurationService.isCloseClientOnStop(),
buildTimeConfigurationService.isStopOnInformerErrorDuringStartup(),
buildTimeConfigurationService.isEnableSSA(),
buildTimeConfigurationService.isDefensiveCloning());
};
}
@SuppressWarnings({ "rawtypes", "unchecked", "OptionalUsedAsFieldOrParameterType" })
private static void setNamespacesFromRuntime(QuarkusBuildTimeControllerConfiguration controllerConfig,
Optional<List<String>> runtimeNamespaces) {
// The namespaces field has a default value so that we are able to detect if the configuration value is set to "".
// Setting the value to "" will reset the configuration and result in an empty Optional.
// Not setting the value at all will result in the default being applied, which we can test for.
if (runtimeNamespaces.isPresent()) {
final var namespaces = new HashSet<>(runtimeNamespaces.get());
// If it's not the default value, use it because it was set.
// If it is the default value, ignore it and let any build time config be used.
if (!QOSDK_USE_BUILDTIME_NAMESPACES_SET.equals(namespaces)) {
controllerConfig.setNamespaces(namespaces);
}
} else {
// Value has been explicitly reset (value was empty string), use all namespaces mode
controllerConfig.setNamespaces(DEFAULT_NAMESPACES_SET);
}
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/ExternalGradualRetryConfiguration.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/ExternalGradualRetryConfiguration.java | package io.quarkiverse.operatorsdk.runtime;
import java.util.Optional;
import io.quarkus.runtime.annotations.ConfigGroup;
/**
* Configuration for {@link io.javaoperatorsdk.operator.processing.retry.GradualRetry}. Will only apply if the
* {@link io.javaoperatorsdk.operator.processing.retry.Retry} implementation class is
* {@link io.javaoperatorsdk.operator.processing.retry.GenericRetry}.
*/
@ConfigGroup
public interface ExternalGradualRetryConfiguration {
/**
* How many times an operation should be retried before giving up
*/
Optional<Integer> maxAttempts();
/**
* The configuration of the retry interval.
*/
ExternalGradualRetryIntervalConfiguration interval();
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/QuarkusWorkflowSpec.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/QuarkusWorkflowSpec.java | package io.quarkiverse.operatorsdk.runtime;
import java.util.List;
import java.util.Map;
import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceSpec;
import io.javaoperatorsdk.operator.api.config.workflow.WorkflowSpec;
import io.quarkus.runtime.annotations.IgnoreProperty;
import io.quarkus.runtime.annotations.RecordableConstructor;
@SuppressWarnings("rawtypes")
public class QuarkusWorkflowSpec implements WorkflowSpec {
private final boolean explicitInvocation;
private final boolean handleExceptionsInReconciler;
private final Map<String, DependentResourceSpecMetadata> dependentResourceSpecMetadata;
@RecordableConstructor
public QuarkusWorkflowSpec(Map<String, DependentResourceSpecMetadata> dependentResourceSpecMetadata,
boolean explicitInvocation, boolean handleExceptionsInReconciler) {
this.dependentResourceSpecMetadata = dependentResourceSpecMetadata;
this.explicitInvocation = explicitInvocation;
this.handleExceptionsInReconciler = handleExceptionsInReconciler;
}
@IgnoreProperty
@Override
public List<DependentResourceSpec> getDependentResourceSpecs() {
return dependentResourceSpecMetadata.values().stream().map(DependentResourceSpec.class::cast).toList();
}
public Map<String, DependentResourceSpecMetadata> getDependentResourceSpecMetadata() {
return dependentResourceSpecMetadata;
}
@Override
public boolean isExplicitInvocation() {
return explicitInvocation;
}
@Override
public boolean handleExceptionsInReconciler() {
return false;
}
// Getter required for Quarkus' RecordableConstructor, must match the associated constructor parameter name
@SuppressWarnings("unused")
public boolean isHandleExceptionsInReconciler() {
return handleExceptionsInReconciler;
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/api/ConfigurableReconciler.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/api/ConfigurableReconciler.java | package io.quarkiverse.operatorsdk.runtime.api;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.javaoperatorsdk.operator.api.config.ConfigurationService;
import io.javaoperatorsdk.operator.api.config.ControllerConfigurationOverrider;
import io.javaoperatorsdk.operator.api.reconciler.Reconciler;
/**
* Implement to change a {@link io.javaoperatorsdk.operator.api.reconciler.Reconciler}'s
* configuration at runtime
*
* @param <P> the primary resource type of the reconciler
* @since 7.2.0
*/
public interface ConfigurableReconciler<P extends HasMetadata> extends Reconciler<P> {
/**
* Updates the reconciler's configuration by applying the modifications specified by the provided
* {@link ControllerConfigurationOverrider}. Note that the resulting configuration update won't be recorded by the
* {@link ConfigurationService} as this currently is a JOSDK limitation. To access the up-to-date configuration, you need to
* retrieve it from the associated {@link io.javaoperatorsdk.operator.RegisteredController} from
* {@link io.javaoperatorsdk.operator.RuntimeInfo}.
*
* @param configOverrider provides the modifications to apply to the existing reconciler's
* configuration
*/
void updateConfigurationFrom(ControllerConfigurationOverrider<P> configOverrider);
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/devmode/OperatorSDKHotReplacementSetup.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/devmode/OperatorSDKHotReplacementSetup.java | package io.quarkiverse.operatorsdk.runtime.devmode;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import io.quarkus.dev.spi.HotReplacementContext;
import io.quarkus.dev.spi.HotReplacementSetup;
public class OperatorSDKHotReplacementSetup implements HotReplacementSetup {
private static final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
@Override
public void setupHotDeployment(HotReplacementContext context) {
executor.scheduleAtFixedRate(() -> {
try {
context.doScan(false);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}, 10, 10, TimeUnit.SECONDS);
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/devui/JSONRPCService.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/devui/JSONRPCService.java | package io.quarkiverse.operatorsdk.runtime.devui;
import java.util.Collection;
import java.util.stream.Collectors;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import io.javaoperatorsdk.operator.Operator;
import io.javaoperatorsdk.operator.processing.Controller;
import io.quarkiverse.operatorsdk.runtime.devconsole.ControllerInfo;
@ApplicationScoped
public class JSONRPCService {
@Inject
Operator operator;
@SuppressWarnings({ "rawtypes", "unchecked" })
public Collection<ControllerInfo> getControllers() {
return operator.getRegisteredControllers().stream()
.map(Controller.class::cast)
.map(registeredController -> new ControllerInfo(registeredController))
.collect(Collectors.toList());
}
@SuppressWarnings("unused")
public int controllersCount() {
return operator.getRegisteredControllersNumber();
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/devconsole/EventSourceInfo.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/devconsole/EventSourceInfo.java | package io.quarkiverse.operatorsdk.runtime.devconsole;
import java.util.Optional;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.javaoperatorsdk.operator.processing.event.source.Configurable;
import io.javaoperatorsdk.operator.processing.event.source.EventSource;
public class EventSourceInfo implements Comparable<EventSourceInfo> {
private final EventSource<?, ? extends HasMetadata> metadata;
public EventSourceInfo(EventSource<?, ? extends HasMetadata> metadata) {
this.metadata = metadata;
}
public String getName() {
return metadata.name();
}
@SuppressWarnings("unused")
public String getResourceClass() {
return metadata.resourceType().getName();
}
public String getType() {
return metadata.getClass().getName();
}
public Optional<?> getConfiguration() {
return metadata instanceof Configurable<?> ? Optional.of(((Configurable<?>) metadata).configuration())
: Optional.empty();
}
@Override
public int compareTo(EventSourceInfo other) {
return getName().compareTo(other.getName());
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/devconsole/DependentInfo.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/devconsole/DependentInfo.java | package io.quarkiverse.operatorsdk.runtime.devconsole;
import java.util.Set;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceSpec;
import io.javaoperatorsdk.operator.processing.dependent.workflow.Condition;
import io.quarkus.arc.Arc;
@SuppressWarnings({ "unused", "rawtypes" })
public class DependentInfo<R, P extends HasMetadata> implements Comparable<DependentInfo> {
private final DependentResourceSpec<R, P, ?> spec;
public DependentInfo(DependentResourceSpec<R, P, ?> spec) {
this.spec = spec;
}
public String getResourceClass() {
try (final var dependent = Arc.container().instance(spec.getDependentResourceClass())) {
return dependent.get().resourceType().getName();
}
}
public String getName() {
return spec.getName();
}
public Set<String> getDependsOn() {
return spec.getDependsOn();
}
public boolean getHasConditions() {
return getReadyCondition() != null || getReconcileCondition() != null || getDeletePostCondition() != null;
}
public String getReadyCondition() {
return getConditionClassName(spec.getReadyCondition());
}
public String getReconcileCondition() {
return getConditionClassName(spec.getReconcileCondition());
}
public String getDeletePostCondition() {
return getConditionClassName(spec.getDeletePostCondition());
}
private String getConditionClassName(Condition condition) {
return condition != null ? condition.getClass().getName() : null;
}
public String getUseEventSourceWithName() {
return spec.getUseEventSourceWithName().orElse(null);
}
public String getType() {
return spec.getDependentResourceClass().getName();
}
@Override
public int compareTo(DependentInfo other) {
return getName().compareTo(other.getName());
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/devconsole/ControllerInfo.java | core/runtime/src/main/java/io/quarkiverse/operatorsdk/runtime/devconsole/ControllerInfo.java | package io.quarkiverse.operatorsdk.runtime.devconsole;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.javaoperatorsdk.operator.api.config.workflow.WorkflowSpec;
import io.javaoperatorsdk.operator.processing.Controller;
public class ControllerInfo<P extends HasMetadata> {
private final Controller<P> controller;
private final Set<EventSourceInfo> eventSources;
@SuppressWarnings("rawtypes")
private final Set<DependentInfo> dependents;
@SuppressWarnings({ "rawtypes", "unchecked" })
public ControllerInfo(Controller<P> controller) {
this.controller = controller;
dependents = controller.getConfiguration().getWorkflowSpec().stream()
.map(WorkflowSpec::getDependentResourceSpecs)
.flatMap(List::stream)
.map(spec -> new DependentInfo(spec))
.sorted()
.collect(Collectors.toCollection(LinkedHashSet::new));
eventSources = controller.getEventSourceManager().getEventSourcesStream()
.map(EventSourceInfo::new)
.sorted()
.collect(Collectors.toCollection(LinkedHashSet::new));
}
public String getName() {
return controller.getConfiguration().getName();
}
@SuppressWarnings("unused")
public String getClassName() {
return controller.getConfiguration().getAssociatedReconcilerClassName();
}
@SuppressWarnings("unused")
public Class<P> getResourceClass() {
return controller.getConfiguration().getResourceClass();
}
@SuppressWarnings("unused")
public Set<String> getEffectiveNamespaces() {
return controller.getConfiguration().getEffectiveNamespaces();
}
@SuppressWarnings("unused")
public Set<String> getConfiguredNamespaces() {
return controller.getConfiguration().getInformerConfig().getNamespaces();
}
@SuppressWarnings("unused")
public Set<EventSourceInfo> getEventSources() {
return eventSources;
}
@SuppressWarnings("rawtypes")
public Set<DependentInfo> getDependents() {
return dependents;
}
@SuppressWarnings("unused")
public List<P> getKnownResources() {
return controller.getEventSourceManager().getControllerEventSource().list()
.collect(Collectors.toList());
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/runtime/src/main/java-templates/io/quarkiverse/operatorsdk/runtime/Versions.java | core/runtime/src/main/java-templates/io/quarkiverse/operatorsdk/runtime/Versions.java | package io.quarkiverse.operatorsdk.runtime;
public final class Versions {
public static final String QUARKUS = "${quarkus.version}";
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
quarkiverse/quarkus-operator-sdk | https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/core/deployment/src/test/java/io/quarkiverse/operatorsdk/test/WatchAllNamespacesTest.java | core/deployment/src/test/java/io/quarkiverse/operatorsdk/test/WatchAllNamespacesTest.java | package io.quarkiverse.operatorsdk.test;
import static io.quarkiverse.operatorsdk.annotations.RBACVerbs.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.fabric8.kubernetes.api.model.ConfigMap;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.rbac.ClusterRole;
import io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding;
import io.fabric8.kubernetes.client.utils.KubernetesSerialization;
import io.quarkiverse.operatorsdk.deployment.ClusterRoles;
import io.quarkiverse.operatorsdk.deployment.RoleBindings;
import io.quarkiverse.operatorsdk.test.sources.WatchAllReconciler;
import io.quarkus.test.ProdBuildResults;
import io.quarkus.test.ProdModeTestResults;
import io.quarkus.test.QuarkusProdModeTest;
public class WatchAllNamespacesTest {
private static final String APPLICATION_NAME = "watch-all-namespaces-test";
// Start unit test with your extension loaded
@RegisterExtension
static final QuarkusProdModeTest config = new QuarkusProdModeTest()
.setApplicationName(APPLICATION_NAME)
.withApplicationRoot((jar) -> jar.addClasses(WatchAllReconciler.class));
@ProdBuildResults
private ProdModeTestResults prodModeTestResults;
private static final KubernetesSerialization serialization = new KubernetesSerialization();
@Test
public void shouldCreateRolesAndRoleBindings() throws IOException {
final var kubernetesDir = prodModeTestResults.getBuildDir().resolve("kubernetes");
final var kubeManifest = kubernetesDir.resolve("kubernetes.yml");
Assertions.assertTrue(Files.exists(kubeManifest));
final var kubeIS = new FileInputStream(kubeManifest.toFile());
// use unmarshall version with parameters map to ensure code goes through the proper processing wrt multiple documents
@SuppressWarnings("unchecked")
final var kubeResources = (List<HasMetadata>) serialization.unmarshal(kubeIS);
// check cluster role
final var clusterRoleName = ClusterRoles.getClusterRoleName(WatchAllReconciler.NAME);
//make sure the target role exists because otherwise the test will succeed without actually checking anything
assertTrue(kubeResources.stream()
.anyMatch(i -> clusterRoleName.equals(i.getMetadata().getName())));
kubeResources.stream()
.filter(i -> clusterRoleName.equals(i.getMetadata().getName()))
.map(ClusterRole.class::cast)
.forEach(cr -> {
final var rules = cr.getRules();
assertEquals(1, rules.size());
var rule = rules.get(0);
assertEquals(List.of(HasMetadata.getGroup(ConfigMap.class)), rule.getApiGroups());
final var resources = rule.getResources();
final var plural = HasMetadata.getPlural(ConfigMap.class);
// status is void so shouldn't be present in resources
assertEquals(List.of(plural, plural + "/finalizers"), resources);
assertEquals(Arrays.asList(ALL_COMMON_VERBS), rule.getVerbs());
});
// check that we have a cluster role binding that is mapped to the proper ClusterRole
final var clusterRoleBindingName = RoleBindings.getClusterRoleBindingName(WatchAllReconciler.NAME);
assertTrue(kubeResources.stream().anyMatch(i -> clusterRoleBindingName.equals(i.getMetadata().getName())));
kubeResources.stream()
.filter(i -> clusterRoleBindingName.equals(i.getMetadata().getName()))
.map(ClusterRoleBinding.class::cast)
.forEach(rb -> assertEquals(clusterRoleName, rb.getRoleRef().getName()));
}
}
| java | Apache-2.0 | c5276c168ac00f94007e8b0c2c1b2c8162a1c424 | 2026-01-05T02:41:12.555806Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.