Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: make it possible to mark a primary resource as unowned #703

Merged
merged 2 commits into from
Sep 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import io.quarkiverse.operatorsdk.bundle.runtime.BundleGenerationConfiguration;
import io.quarkiverse.operatorsdk.bundle.runtime.CSVMetadataHolder;
import io.quarkiverse.operatorsdk.common.ReconcilerAugmentedClassInfo;
import io.quarkiverse.operatorsdk.runtime.BuildTimeOperatorConfiguration;
import io.quarkiverse.operatorsdk.runtime.CRDInfo;
import io.quarkiverse.operatorsdk.runtime.Version;
import io.quarkus.container.util.PathsUtil;
Expand Down Expand Up @@ -46,15 +47,16 @@ private BundleGenerator() {
}

public static List<ManifestsBuilder> prepareGeneration(BundleGenerationConfiguration bundleConfiguration,
Version version, Map<CSVMetadataHolder, List<ReconcilerAugmentedClassInfo>> csvGroups, Map<String, CRDInfo> crds,
BuildTimeOperatorConfiguration operatorConfiguration, Version version,
Map<CSVMetadataHolder, List<ReconcilerAugmentedClassInfo>> csvGroups, Map<String, CRDInfo> crds,
Path outputDirectory) {
List<ManifestsBuilder> builders = new ArrayList<>();
for (Map.Entry<CSVMetadataHolder, List<ReconcilerAugmentedClassInfo>> entry : csvGroups.entrySet()) {
final var csvMetadata = entry.getKey();
final var labels = generateBundleLabels(csvMetadata, bundleConfiguration, version);

final var mainSourcesRoot = PathsUtil.findMainSourcesRoot(outputDirectory);
final var csvBuilder = new CsvManifestsBuilder(csvMetadata, entry.getValue(),
final var csvBuilder = new CsvManifestsBuilder(csvMetadata, operatorConfiguration, entry.getValue(),
mainSourcesRoot != null ? mainSourcesRoot.getKey() : null);
builders.add(csvBuilder);
builders.add(new AnnotationsManifestsBuilder(csvMetadata, labels));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import io.quarkiverse.operatorsdk.common.*;
import io.quarkiverse.operatorsdk.deployment.GeneratedCRDInfoBuildItem;
import io.quarkiverse.operatorsdk.deployment.VersionBuildItem;
import io.quarkiverse.operatorsdk.runtime.BuildTimeOperatorConfiguration;
import io.quarkiverse.operatorsdk.runtime.CRDInfo;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
Expand Down Expand Up @@ -167,6 +168,7 @@ private String getMetadataOriginInformation(AnnotationInstance csvMetadataAnnota
@BuildStep(onlyIf = IsGenerationEnabled.class)
void generateBundle(ApplicationInfoBuildItem configuration,
BundleGenerationConfiguration bundleConfiguration,
BuildTimeOperatorConfiguration operatorConfiguration,
OutputTargetBuildItem outputTarget,
CSVMetadataBuildItem csvMetadata,
VersionBuildItem versionBuildItem,
Expand Down Expand Up @@ -218,7 +220,8 @@ void generateBundle(ApplicationInfoBuildItem configuration,
deployments.add((Deployment) r);
}
});
final var generated = BundleGenerator.prepareGeneration(bundleConfiguration, versionBuildItem.getVersion(),
final var generated = BundleGenerator.prepareGeneration(bundleConfiguration, operatorConfiguration,
versionBuildItem.getVersion(),
csvMetadata.getCsvGroups(), crds, outputTarget.getOutputDirectory());
generated.forEach(manifestBuilder -> {
final var fileName = manifestBuilder.getFileName();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import io.quarkiverse.operatorsdk.common.ReconciledResourceAugmentedClassInfo;
import io.quarkiverse.operatorsdk.common.ReconcilerAugmentedClassInfo;
import io.quarkiverse.operatorsdk.common.ResourceAssociatedAugmentedClassInfo;
import io.quarkiverse.operatorsdk.runtime.BuildTimeOperatorConfiguration;

public class CsvManifestsBuilder extends ManifestsBuilder {

Expand All @@ -42,7 +43,8 @@ public class CsvManifestsBuilder extends ManifestsBuilder {
private final Set<CRDDescription> requiredCRs = new HashSet<>();
private final Path kubernetesResources;

public CsvManifestsBuilder(CSVMetadataHolder metadata, List<ReconcilerAugmentedClassInfo> controllers,
public CsvManifestsBuilder(CSVMetadataHolder metadata, BuildTimeOperatorConfiguration operatorConfiguration,
List<ReconcilerAugmentedClassInfo> controllers,
Path mainSourcesRoot) {
super(metadata);
this.kubernetesResources = mainSourcesRoot != null ? mainSourcesRoot.resolve("kubernetes") : null;
Expand Down Expand Up @@ -142,11 +144,23 @@ public CsvManifestsBuilder(CSVMetadataHolder metadata, List<ReconcilerAugmentedC
// add owned and required CRD, also collect them
final var nativeApis = new ArrayList<GroupVersionKind>();
controllers.forEach(raci -> {
// add owned CRD
// deal with primary resource
final var resourceInfo = raci.associatedResourceInfo();
if (resourceInfo.isCR()) {
final var asResource = resourceInfo.asResourceTargeting();
ownedCRs.add(createCRDDescription(asResource));
// if the primary is not a CR, mark it as native API
if (asResource.isCR()) {
// check if the primary resource is unowned, in which case, make it required, otherwise, it's owned
final var crdDescription = createCRDDescription(asResource);
if (operatorConfiguration.isControllerOwningPrimary(raci.nameOrFailIfUnset())) {
ownedCRs.add(crdDescription);
} else {
requiredCRs.add(crdDescription);
}
} else {
nativeApis.add(new GroupVersionKind(asResource.group(), asResource.kind(),
asResource.version()));
}
}

// add required CRD for each dependent that targets a CR
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,9 +148,7 @@ boolean scheduleForGenerationIfNeeded(CustomResourceAugmentedClassInfo crInfo,
public void withCustomResource(Class<? extends CustomResource> crClass, String crdName, String associatedControllerName) {
// first check if the CR is not filtered out
if (crdConfiguration.excludeResources.map(excluded -> excluded.contains(crClass.getName())).orElse(false)) {
log.infov(
"CRD generation was skipped for ''{1}'' because it was excluded from generation",
crClass.getName());
log.infov("CRD generation was skipped for ''{0}'' because it was excluded from generation", crClass.getName());
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@

import org.jboss.logging.Logger;

import io.quarkiverse.operatorsdk.common.ClassUtils;
import io.quarkiverse.operatorsdk.common.ConfigurationUtils;
import io.quarkiverse.operatorsdk.common.Constants;
import io.quarkiverse.operatorsdk.common.CustomResourceAugmentedClassInfo;
import io.quarkiverse.operatorsdk.common.*;
import io.quarkiverse.operatorsdk.runtime.BuildTimeOperatorConfiguration;
import io.quarkiverse.operatorsdk.runtime.CRDGenerationInfo;
import io.quarkiverse.operatorsdk.runtime.CRDInfo;
Expand All @@ -22,7 +19,7 @@
class CRDGenerationBuildStep {
static final Logger log = Logger.getLogger(CRDGenerationBuildStep.class.getName());

private BuildTimeOperatorConfiguration buildTimeConfiguration;
private BuildTimeOperatorConfiguration operatorConfiguration;

@BuildStep
GeneratedCRDInfoBuildItem generateCRDs(
Expand All @@ -31,7 +28,7 @@ GeneratedCRDInfoBuildItem generateCRDs(
LiveReloadBuildItem liveReload,
OutputTargetBuildItem outputTarget,
CombinedIndexBuildItem combinedIndexBuildItem) {
final var crdConfig = buildTimeConfiguration.crd;
final var crdConfig = operatorConfiguration.crd;
final boolean validateCustomResources = ConfigurationUtils.shouldValidateCustomResources(crdConfig.validate);

//apply should imply generate: we cannot apply if we're not generating!
Expand All @@ -51,20 +48,27 @@ GeneratedCRDInfoBuildItem generateCRDs(

if (generate) {
reconcilers.getReconcilers().values().forEach(raci -> {
// add associated primary resource for CRD generation if needed
if (raci.associatedResourceInfo().isCR()) {
final var crInfo = raci.associatedResourceInfo().asResourceTargeting();
// When we have a live reload, check if we need to regenerate the associated CRD
Map<String, CRDInfo> crdInfos = Collections.emptyMap();

// add associated primary resource for CRD generation if it's a CR and it's owned by the reconciler
final ReconciledAugmentedClassInfo<?> associatedResource = raci.associatedResourceInfo();
if (associatedResource.isCR()) {
final var crInfo = associatedResource.asResourceTargeting();
final String targetCRName = crInfo.fullResourceName();
if (liveReload.isLiveReload()) {
crdInfos = storedCRDInfos.getCRDInfosFor(targetCRName);
}

if (crdGeneration.scheduleForGenerationIfNeeded((CustomResourceAugmentedClassInfo) crInfo, crdInfos,
changedClasses)) {
// if the primary resource is unowned, mark it as "scheduled" (i.e. already handled) so that it doesn't get considered if all CRDs generation is requested
if (!operatorConfiguration.isControllerOwningPrimary(raci.nameOrFailIfUnset())) {
scheduledForGeneration.add(targetCRName);
} else {
// When we have a live reload, check if we need to regenerate the associated CRD
Map<String, CRDInfo> crdInfos = Collections.emptyMap();
if (liveReload.isLiveReload()) {
crdInfos = storedCRDInfos.getCRDInfosFor(targetCRName);
}

// schedule the generation of associated primary resource CRD if required
if (crdGeneration.scheduleForGenerationIfNeeded((CustomResourceAugmentedClassInfo) crInfo, crdInfos,
changedClasses)) {
scheduledForGeneration.add(targetCRName);
}
}
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,7 @@ ReconcilerInfosBuildItem buildReconcilerInfos(CombinedIndexBuildItem combinedInd
.setUnremovable()
.setDefaultScope(APPLICATION_SCOPED)
.build()))
.collect(
Collectors.toMap(ResourceAssociatedAugmentedClassInfo::nameOrFailIfUnset, Function.identity()));
.collect(Collectors.toMap(ResourceAssociatedAugmentedClassInfo::nameOrFailIfUnset, Function.identity()));
return new ReconcilerInfosBuildItem(reconcilers);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package io.quarkiverse.operatorsdk.test;

import java.io.IOException;
import java.nio.file.Files;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.fabric8.kubernetes.client.CustomResource;
import io.quarkiverse.operatorsdk.test.sources.*;
import io.quarkus.test.ProdBuildResults;
import io.quarkus.test.ProdModeTestResults;
import io.quarkus.test.QuarkusProdModeTest;

public class UnownedTest {
// Start unit test with your extension loaded
@RegisterExtension
static final QuarkusProdModeTest config = new QuarkusProdModeTest()
.setApplicationName(UnownedReconciler.NAME)
.withApplicationRoot(
(jar) -> jar.addClasses(UnownedReconciler.class, TestCR.class))
.overrideConfigKey("quarkus.operator-sdk.crd.generate-all", "true")
.overrideConfigKey("quarkus.operator-sdk.controllers." + UnownedReconciler.NAME + ".unowned-primary", "true");
Copy link
Member Author

@metacosm metacosm Sep 6, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the salient part of this test: setting the unowned-primary property to true for the controller in application.properties, while this also checks that excluding an unowned primary from generation is not also forced by the generate-all property.


@ProdBuildResults
private ProdModeTestResults prodModeTestResults;

@Test
public void shouldNotGenerateUnownedPrimary() throws IOException {
final var kubernetesDir = prodModeTestResults.getBuildDir().resolve("kubernetes");
final var kubeManifest = kubernetesDir.resolve("kubernetes.yml");
Assertions.assertTrue(Files.exists(kubeManifest));

// checks that no CRD has been generated
Assertions.assertFalse(Files.exists(kubernetesDir.resolve(CustomResource.getCRDName(TestCR.class) + "-v1.yml")));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package io.quarkiverse.operatorsdk.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;

@ControllerConfiguration(name = UnownedReconciler.NAME)
public class UnownedReconciler implements Reconciler<TestCR> {

public static final String NAME = "unowned";

@Override
public UpdateControl<TestCR> reconcile(TestCR testCR, Context<TestCR> context) throws Exception {
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,14 @@ public class BuildTimeControllerConfiguration {
*/
@ConfigItem
public 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
*/
@ConfigItem(defaultValue = "false")
public boolean unownedPrimary;
}
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,9 @@ public class BuildTimeOperatorConfiguration {
*/
@ConfigItem
public HelmConfiguration helm;

public boolean isControllerOwningPrimary(String controllerName) {
final var controllerConfiguration = controllers.get(controllerName);
return controllerConfiguration == null || !controllerConfiguration.unownedPrimary;
}
}
17 changes: 17 additions & 0 deletions docs/modules/ROOT/pages/includes/quarkus-operator-sdk.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,23 @@ endif::add-copy-button-to-env-var[]
|


a|icon:lock[title=Fixed at build time] [[quarkus-operator-sdk_quarkus.operator-sdk.controllers.-controllers-.unowned-primary]]`link:#quarkus-operator-sdk_quarkus.operator-sdk.controllers.-controllers-.unowned-primary[quarkus.operator-sdk.controllers."controllers".unowned-primary]`


[.description]
--
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 `true` if you want to indicate that the controller doesn't own its primary resource

ifdef::add-copy-button-to-env-var[]
Environment variable: env_var_with_copy_button:+++QUARKUS_OPERATOR_SDK_CONTROLLERS__CONTROLLERS__UNOWNED_PRIMARY+++[]
endif::add-copy-button-to-env-var[]
ifndef::add-copy-button-to-env-var[]
Environment variable: `+++QUARKUS_OPERATOR_SDK_CONTROLLERS__CONTROLLERS__UNOWNED_PRIMARY+++`
endif::add-copy-button-to-env-var[]
--|boolean
|`false`


a| [[quarkus-operator-sdk_quarkus.operator-sdk.controllers.-controllers-.namespaces]]`link:#quarkus-operator-sdk_quarkus.operator-sdk.controllers.-controllers-.namespaces[quarkus.operator-sdk.controllers."controllers".namespaces]`


Expand Down