diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000000..67ab977ac3 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,49 @@ +name: Build + +env: + MAVEN_ARGS: -V -ntp -e + +on: + workflow_call: + +jobs: + integration_tests: + strategy: + matrix: + java: [ 17, 21 ] + kubernetes: [ 'v1.28.14', 'v1.29.9','1.30.5', '1.31.1' ] + it-category: [ 'baseapi', 'dependent', 'workflow' ] + uses: ./.github/workflows/integration-tests.yml + with: + java-version: ${{ matrix.java }} + kube-version: ${{ matrix.kubernetes }} + it-category: ${{ matrix.it-category }} + + http_client_tests: + strategy: + matrix: + java: [ 17, 21 ] + kubernetes: [ 'v1.28.14', 'v1.29.9','1.30.5', '1.31.1' ] + it-category: [ 'baseapi' ] + httpclient: [ 'vertx', 'jdk', 'jetty' ] + uses: ./.github/workflows/integration-tests.yml + with: + java-version: ${{ matrix.java }} + kube-version: ${{ matrix.kubernetes }} + it-category: ${{ matrix.it-category }} + http-client: ${{ matrix.httpclient }} + + special_integration_tests: + runs-on: ubuntu-latest + strategy: + matrix: + java: [ 17, 21 ] + steps: + - uses: actions/checkout@v4 + - name: Set up Java and Maven + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: ${{ matrix.java }} + - name: Run Special Integration Tests + run: ./mvnw ${MAVEN_ARGS} -B package -P minimal-watch-timeout-dependent-it --file pom.xml \ No newline at end of file diff --git a/.github/workflows/e2e-test.yml b/.github/workflows/e2e-test.yml index 5d6ec78c5f..df2d6ca584 100644 --- a/.github/workflows/e2e-test.yml +++ b/.github/workflows/e2e-test.yml @@ -19,7 +19,7 @@ jobs: sample_operators_tests: strategy: matrix: - sample_dir: + sample: - "sample-operators/mysql-schema" - "sample-operators/tomcat-operator" - "sample-operators/webpage" @@ -48,12 +48,10 @@ jobs: run: mvn install -DskipTests - name: Run integration tests in local mode - working-directory: ${{ matrix.sample_dir }} run: | - mvn test -P end-to-end-tests + mvn test -P end-to-end-tests -pl ${{ matrix.sample }} - name: Run E2E tests as a deployment - working-directory: ${{ matrix.sample_dir }} run: | eval $(minikube -p minikube docker-env) - mvn jib:dockerBuild test -P end-to-end-tests -Dtest.deployment=remote + mvn jib:dockerBuild test -P end-to-end-tests -Dtest.deployment=remote -pl ${{ matrix.sample }} diff --git a/.github/workflows/fabric8-next-version-schedule.yml b/.github/workflows/fabric8-next-version-schedule.yml index b0bc57ea75..64d2042135 100644 --- a/.github/workflows/fabric8-next-version-schedule.yml +++ b/.github/workflows/fabric8-next-version-schedule.yml @@ -23,46 +23,8 @@ jobs: with: distribution: temurin java-version: 17 - cache: 'maven' - name: Run unit tests run: ./mvnw ${MAVEN_ARGS} clean install --file pom.xml - integration_tests: - strategy: - matrix: - java: [ 11, 17 ] - kubernetes: ['v1.28.12', 'v1.29.7','1.30.3', '1.31.0'] - uses: ./.github/workflows/integration-tests.yml - with: - java-version: ${{ matrix.java }} - kube-version: ${{ matrix.kubernetes }} - - httpclient-tests: - strategy: - matrix: - httpclient: [ 'vertx', 'jdk', 'jetty' ] - uses: ./.github/workflows/integration-tests.yml - with: - java-version: 17 - kube-version: 'v1.29.1' - http-client: ${{ matrix.httpclient }} - experimental: true - checkout-ref: 'fabric8-next-version' - - special_integration_tests: - runs-on: ubuntu-latest - strategy: - matrix: - java: [ 11, 17 ] - steps: - - uses: actions/checkout@v4 - with: - ref: 'fabric8-next-version' - - name: Set up Java and Maven - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: ${{ matrix.java }} - cache: 'maven' - - name: Run Special Integration Tests - run: ./mvnw ${MAVEN_ARGS} -B package -P minimal-watch-timeout-dependent-it --file pom.xml \ No newline at end of file + build: + uses: ./.github/workflows/build.yml \ No newline at end of file diff --git a/.github/workflows/hugo.yaml b/.github/workflows/hugo.yaml index 2a5ee0d64e..1d91c85ef3 100644 --- a/.github/workflows/hugo.yaml +++ b/.github/workflows/hugo.yaml @@ -49,7 +49,7 @@ jobs: id: pages uses: actions/configure-pages@v5 - name: Install Node.js dependencies - working-directory: ./docsy + working-directory: ./docs run: | [[ -f package-lock.json || -f npm-shrinkwrap.json ]] && npm ci || true npm install -D autoprefixer @@ -61,7 +61,7 @@ jobs: HUGO_ENVIRONMENT: production HUGO_ENV: production TZ: America/Los_Angeles - working-directory: ./docsy + working-directory: ./docs run: | hugo \ --gc \ @@ -70,7 +70,7 @@ jobs: - name: Upload artifact uses: actions/upload-pages-artifact@v3 with: - path: ./docsy/public + path: ./docs/public # Deployment job deploy: diff --git a/.github/workflows/integration-tests.yml b/.github/workflows/integration-tests.yml index be811d309e..e36add39c2 100644 --- a/.github/workflows/integration-tests.yml +++ b/.github/workflows/integration-tests.yml @@ -12,7 +12,7 @@ on: http-client: type: string required: false - default: 'okhttp' + default: 'vertx' experimental: type: boolean required: false @@ -21,6 +21,10 @@ on: type: string required: false default: '' + it-category: + type: string + required: false + default: '' jobs: integration_tests: @@ -42,9 +46,17 @@ jobs: - name: Set up Minikube uses: manusa/actions-setup-minikube@v2.13.0 with: - minikube version: v1.33.0 - kubernetes version: ${{ inputs.kube-version }} + minikube version: 'v1.33.0' + kubernetes version: '${{ inputs.kube-version }}' driver: 'docker' github token: ${{ secrets.GITHUB_TOKEN }} - - name: Run integration tests - run: ./mvnw ${MAVEN_ARGS} -B package -P no-unit-tests -Dfabric8-httpclient-impl.name=${{inputs.http-client}} --file pom.xml \ No newline at end of file + - name: "${{inputs.it-category}} integration tests (kube: ${{ inputs.kube-version }} / java: ${{ inputs.java-version }} / client: ${{ inputs.http-client }})" + run: | + if [ -z "${{inputs.it-category}}" ]; then + it_profile="integration-tests" + else + it_profile="integration-tests-${{inputs.it-category}}" + fi + echo "Using profile: ${it_profile}" + ./mvnw ${MAVEN_ARGS} -T1C -B install -DskipTests -Pno-apt --file pom.xml + ./mvnw ${MAVEN_ARGS} -T1C -B package -P${it_profile} -Dfabric8-httpclient-impl.name=${{inputs.http-client}} --file pom.xml \ No newline at end of file diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 15342af1b1..facd6be13a 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -26,44 +26,9 @@ jobs: cache: 'maven' - name: Check code format run: | - ./mvnw ${MAVEN_ARGS} formatter:validate -Dconfigfile=$PWD/contributing/eclipse-google-style.xml -pl '!operator-framework-bom' --file pom.xml - ./mvnw ${MAVEN_ARGS} impsort:check -pl '!operator-framework-bom' --file pom.xml + ./mvnw ${MAVEN_ARGS} spotless:check --file pom.xml - name: Run unit tests - run: ./mvnw ${MAVEN_ARGS} clean install --file pom.xml + run: ./mvnw ${MAVEN_ARGS} clean install -Pno-apt --file pom.xml - integration_tests: - strategy: - matrix: - java: [ 11, 17 ] - kubernetes: [ 'v1.28.12', 'v1.29.7','1.30.3', '1.31.0' ] - uses: ./.github/workflows/integration-tests.yml - with: - java-version: ${{ matrix.java }} - kube-version: ${{ matrix.kubernetes }} - - httpclient-tests: - strategy: - matrix: - httpclient: [ 'vertx', 'jdk', 'jetty' ] - uses: ./.github/workflows/integration-tests.yml - with: - java-version: 17 - kube-version: 'v1.29.1' - http-client: ${{ matrix.httpclient }} - experimental: true - - special_integration_tests: - runs-on: ubuntu-latest - strategy: - matrix: - java: [ 11, 17 ] - steps: - - uses: actions/checkout@v4 - - name: Set up Java and Maven - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: ${{ matrix.java }} - cache: 'maven' - - name: Run Special Integration Tests - run: ./mvnw ${MAVEN_ARGS} -B package -P minimal-watch-timeout-dependent-it --file pom.xml \ No newline at end of file + build: + uses: ./.github/workflows/build.yml \ No newline at end of file diff --git a/.github/workflows/release-project-in-dir.yml b/.github/workflows/release-project-in-dir.yml index b271f05f02..dc79b6f6c2 100644 --- a/.github/workflows/release-project-in-dir.yml +++ b/.github/workflows/release-project-in-dir.yml @@ -26,7 +26,7 @@ jobs: - name: Set up Java and Maven uses: actions/setup-java@v4 with: - java-version: 11 + java-version: 17 distribution: temurin cache: 'maven' @@ -61,7 +61,7 @@ jobs: - name: Set up Java and Maven uses: actions/setup-java@v4 with: - java-version: 11 + java-version: 17 distribution: temurin cache: 'maven' diff --git a/.github/workflows/snapshot-releases.yml b/.github/workflows/snapshot-releases.yml index e5aff55e62..66fe9d25a3 100644 --- a/.github/workflows/snapshot-releases.yml +++ b/.github/workflows/snapshot-releases.yml @@ -21,7 +21,7 @@ jobs: uses: actions/setup-java@v4 with: distribution: temurin - java-version: 11 + java-version: 17 cache: 'maven' - name: Build and test project run: ./mvnw ${MAVEN_ARGS} clean install --file pom.xml @@ -34,7 +34,7 @@ jobs: uses: actions/setup-java@v4 with: distribution: temurin - java-version: 11 + java-version: 17 cache: 'maven' - name: Release Maven package uses: samuelmeuli/action-maven-publish@v1 diff --git a/README.md b/README.md index b932fe1e96..933dacb54b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# ![java-operator-sdk](docsy/static/images/full_logo.png) +# ![java-operator-sdk](docs/static/images/full_logo.png) ![Java CI with Maven](https://github.com/operator-framework/java-operator-sdk/actions/workflows/snapshot-releases.yml/badge.svg) [![Slack](https://img.shields.io/badge/Slack-4A154B?style=flat-square&logo=slack&logoColor=white)](https://kubernetes.slack.com/archives/CAW0GV7A5 "get invite here: https://communityinviter.com/apps/kubernetes/community" ) @@ -40,7 +40,6 @@ It makes it easy to implement best practices and patterns for an Operator. Featu * Handling dependent resources, related events, and caching. * Automatic Retries * Smart event scheduling -* Handling Observed Generations automatically * Easy to use Error Handling * ... and everything that a batteries included framework needs diff --git a/bootstrapper-maven-plugin/pom.xml b/bootstrapper-maven-plugin/pom.xml index efa9619e57..ce93472d79 100644 --- a/bootstrapper-maven-plugin/pom.xml +++ b/bootstrapper-maven-plugin/pom.xml @@ -1,11 +1,11 @@ - + + 4.0.0 - java-operator-sdk io.javaoperatorsdk - 4.9.7-SNAPSHOT + java-operator-sdk + 5.0.0-SNAPSHOT bootstrapper @@ -39,7 +39,7 @@ org.apache.logging.log4j - log4j-slf4j-impl + log4j-slf4j2-impl test @@ -72,29 +72,29 @@ - - - org.apache.maven.plugins - maven-plugin-plugin - ${maven-plugin-plugin.version} - - josdk-bootstrapper - - - - org.codehaus.mojo - templating-maven-plugin - ${templating-maven-plugin.version} - - - filtering-java-templates - - filter-sources - - - - + + + org.apache.maven.plugins + maven-plugin-plugin + ${maven-plugin-plugin.version} + + josdk-bootstrapper + + + + org.codehaus.mojo + templating-maven-plugin + ${templating-maven-plugin.version} + + + filtering-java-templates + + filter-sources + + + + - + diff --git a/bootstrapper-maven-plugin/src/main/java/io/javaoperatorsdk/boostrapper/Bootstrapper.java b/bootstrapper-maven-plugin/src/main/java/io/javaoperatorsdk/boostrapper/Bootstrapper.java index ad7bc3cc79..ed12e7619d 100644 --- a/bootstrapper-maven-plugin/src/main/java/io/javaoperatorsdk/boostrapper/Bootstrapper.java +++ b/bootstrapper-maven-plugin/src/main/java/io/javaoperatorsdk/boostrapper/Bootstrapper.java @@ -21,7 +21,7 @@ public class Bootstrapper { private static final Logger log = LoggerFactory.getLogger(Bootstrapper.class); - private MustacheFactory mustacheFactory = new DefaultMustacheFactory(); + private final MustacheFactory mustacheFactory = new DefaultMustacheFactory(); // .gitignore gets excluded from resource, using here a prefixed version private static final Map TOP_LEVEL_STATIC_FILES = diff --git a/bootstrapper-maven-plugin/src/main/resources/templates/Reconciler.java b/bootstrapper-maven-plugin/src/main/resources/templates/Reconciler.java index 03ac06f882..f7583be4ee 100644 --- a/bootstrapper-maven-plugin/src/main/resources/templates/Reconciler.java +++ b/bootstrapper-maven-plugin/src/main/resources/templates/Reconciler.java @@ -1,23 +1,15 @@ package {{groupId}}; -import io.fabric8.kubernetes.api.model.ConfigMap; -import io.fabric8.kubernetes.api.model.ConfigMapBuilder; -import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; -import io.javaoperatorsdk.operator.api.reconciler.EventSourceInitializer; import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; -import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; -import io.javaoperatorsdk.operator.processing.event.source.EventSource; -import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; +import io.javaoperatorsdk.operator.api.reconciler.Workflow; import java.util.Map; import java.util.Optional; -@ControllerConfiguration(dependents = {@Dependent(type = ConfigMapDependentResource.class)}) +@Workflow(dependents = {@Dependent(type = ConfigMapDependentResource.class)}) public class {{artifactClassId}}Reconciler implements Reconciler<{{artifactClassId}}CustomResource> { public UpdateControl<{{artifactClassId}}CustomResource> reconcile({{artifactClassId}}CustomResource primary, diff --git a/bootstrapper-maven-plugin/src/main/resources/templates/Status.java b/bootstrapper-maven-plugin/src/main/resources/templates/Status.java index 4c37b99947..52bd0fd4d2 100644 --- a/bootstrapper-maven-plugin/src/main/resources/templates/Status.java +++ b/bootstrapper-maven-plugin/src/main/resources/templates/Status.java @@ -1,7 +1,5 @@ package {{groupId}}; -import io.javaoperatorsdk.operator.api.ObservedGenerationAwareStatus; - -public class {{artifactClassId}}Status extends ObservedGenerationAwareStatus { +public class {{artifactClassId}}Status { } diff --git a/bootstrapper-maven-plugin/src/main/resources/templates/pom.xml b/bootstrapper-maven-plugin/src/main/resources/templates/pom.xml index fe9d29300e..6a835598a3 100644 --- a/bootstrapper-maven-plugin/src/main/resources/templates/pom.xml +++ b/bootstrapper-maven-plugin/src/main/resources/templates/pom.xml @@ -11,7 +11,7 @@ jar - 11 + 17 ${java.version} ${java.version} {{josdkVersion}} @@ -58,7 +58,7 @@ org.apache.logging.log4j - log4j-slf4j-impl + log4j-slf4j2-impl ${log4j.version} diff --git a/caffeine-bounded-cache-support/pom.xml b/caffeine-bounded-cache-support/pom.xml index ae4fa16c39..d0840f420a 100644 --- a/caffeine-bounded-cache-support/pom.xml +++ b/caffeine-bounded-cache-support/pom.xml @@ -1,22 +1,15 @@ - + + 4.0.0 - java-operator-sdk io.javaoperatorsdk - 4.9.7-SNAPSHOT + java-operator-sdk + 5.0.0-SNAPSHOT - 4.0.0 caffeine-bounded-cache-support Operator SDK - Caffeine Bounded Cache Support - - 11 - 11 - - io.javaoperatorsdk @@ -44,7 +37,7 @@ org.apache.logging.log4j - log4j-slf4j-impl + log4j-slf4j2-impl test @@ -70,10 +63,10 @@ However, this is needed to compile the tests so let's disable apt just for the compile phase --> default-compile - compile compile + compile -proc:none @@ -85,4 +78,4 @@ - \ No newline at end of file + diff --git a/caffeine-bounded-cache-support/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/sample/AbstractTestReconciler.java b/caffeine-bounded-cache-support/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/sample/AbstractTestReconciler.java index b6e3ba2c8f..9d912986e1 100644 --- a/caffeine-bounded-cache-support/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/sample/AbstractTestReconciler.java +++ b/caffeine-bounded-cache-support/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/sample/AbstractTestReconciler.java @@ -1,6 +1,7 @@ package io.javaoperatorsdk.operator.processing.event.source.cache.sample; import java.time.Duration; +import java.util.List; import java.util.Map; import org.slf4j.Logger; @@ -13,7 +14,7 @@ import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.KubernetesClientBuilder; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; import io.javaoperatorsdk.operator.api.reconciler.*; import io.javaoperatorsdk.operator.processing.event.source.EventSource; import io.javaoperatorsdk.operator.processing.event.source.cache.BoundedItemStore; @@ -28,7 +29,7 @@ import com.github.benmanes.caffeine.cache.Caffeine; public abstract class AbstractTestReconciler

> - implements Reconciler

, EventSourceInitializer

{ + implements Reconciler

{ private static final Logger log = LoggerFactory.getLogger(BoundedCacheClusterScopeTestReconciler.class); @@ -69,20 +70,23 @@ protected void createConfigMap(P resource, Context

context) { } @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext

context) { var boundedItemStore = boundedItemStore(new KubernetesClientBuilder().build(), ConfigMap.class, Duration.ofMinutes(1), 1); // setting max size for testing purposes - var es = new InformerEventSource<>(InformerConfiguration.from(ConfigMap.class, context) - .withItemStore(boundedItemStore) - .withSecondaryToPrimaryMapper( - Mappers.fromOwnerReference(this instanceof BoundedCacheClusterScopeTestReconciler)) - .build(), context); + var es = new InformerEventSource<>( + InformerEventSourceConfiguration.from(ConfigMap.class, primaryClass()) + .withInformerConfiguration(c -> c.withItemStore(boundedItemStore)) + .withSecondaryToPrimaryMapper( + Mappers.fromOwnerReferences(context.getPrimaryResourceClass(), + this instanceof BoundedCacheClusterScopeTestReconciler)) + .build(), + context); - return EventSourceInitializer.nameEventSources(es); + return List.of(es); } private void ensureStatus(P resource) { @@ -102,4 +106,7 @@ public static BoundedItemStore boundedItemStore( .build(); return CaffeineBoundedItemStores.boundedItemStore(client, rClass, cache); } + + protected abstract Class

primaryClass(); + } diff --git a/caffeine-bounded-cache-support/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/sample/clusterscope/BoundedCacheClusterScopeTestReconciler.java b/caffeine-bounded-cache-support/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/sample/clusterscope/BoundedCacheClusterScopeTestReconciler.java index a154659164..84448fc9d8 100644 --- a/caffeine-bounded-cache-support/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/sample/clusterscope/BoundedCacheClusterScopeTestReconciler.java +++ b/caffeine-bounded-cache-support/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/sample/clusterscope/BoundedCacheClusterScopeTestReconciler.java @@ -7,4 +7,8 @@ public class BoundedCacheClusterScopeTestReconciler extends AbstractTestReconciler { + @Override + protected Class primaryClass() { + return BoundedCacheClusterScopeTestCustomResource.class; + } } diff --git a/caffeine-bounded-cache-support/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/sample/namespacescope/BoundedCacheTestReconciler.java b/caffeine-bounded-cache-support/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/sample/namespacescope/BoundedCacheTestReconciler.java index 211877b361..6b95665585 100644 --- a/caffeine-bounded-cache-support/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/sample/namespacescope/BoundedCacheTestReconciler.java +++ b/caffeine-bounded-cache-support/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/sample/namespacescope/BoundedCacheTestReconciler.java @@ -7,4 +7,8 @@ public class BoundedCacheTestReconciler extends AbstractTestReconciler { + @Override + protected Class primaryClass() { + return BoundedCacheTestCustomResource.class; + } } diff --git a/caffeine-bounded-cache-support/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/sample/namespacescope/BoundedCacheTestStatus.java b/caffeine-bounded-cache-support/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/sample/namespacescope/BoundedCacheTestStatus.java index 03a311529e..2bdd434d23 100644 --- a/caffeine-bounded-cache-support/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/sample/namespacescope/BoundedCacheTestStatus.java +++ b/caffeine-bounded-cache-support/src/test/java/io/javaoperatorsdk/operator/processing/event/source/cache/sample/namespacescope/BoundedCacheTestStatus.java @@ -1,6 +1,4 @@ package io.javaoperatorsdk.operator.processing.event.source.cache.sample.namespacescope; -import io.javaoperatorsdk.operator.api.ObservedGenerationAwareStatus; - -public class BoundedCacheTestStatus extends ObservedGenerationAwareStatus { +public class BoundedCacheTestStatus { } diff --git a/docsy/.gitignore b/docs/.gitignore similarity index 100% rename from docsy/.gitignore rename to docs/.gitignore diff --git a/docsy/.nvmrc b/docs/.nvmrc similarity index 100% rename from docsy/.nvmrc rename to docs/.nvmrc diff --git a/docsy/CONTRIBUTING.md b/docs/CONTRIBUTING.md similarity index 100% rename from docsy/CONTRIBUTING.md rename to docs/CONTRIBUTING.md diff --git a/docsy/Dockerfile b/docs/Dockerfile similarity index 100% rename from docsy/Dockerfile rename to docs/Dockerfile diff --git a/docsy/LICENSE b/docs/LICENSE similarity index 100% rename from docsy/LICENSE rename to docs/LICENSE diff --git a/docsy/README.md b/docs/README.md similarity index 100% rename from docsy/README.md rename to docs/README.md diff --git a/docsy/assets/icons/logo.svg b/docs/assets/icons/logo.svg similarity index 100% rename from docsy/assets/icons/logo.svg rename to docs/assets/icons/logo.svg diff --git a/docsy/assets/scss/_variables_project.scss b/docs/assets/scss/_variables_project.scss similarity index 100% rename from docsy/assets/scss/_variables_project.scss rename to docs/assets/scss/_variables_project.scss diff --git a/docsy/config.yaml b/docs/config.yaml similarity index 100% rename from docsy/config.yaml rename to docs/config.yaml diff --git a/docsy/content/en/_index.md b/docs/content/en/_index.md similarity index 100% rename from docsy/content/en/_index.md rename to docs/content/en/_index.md diff --git a/docsy/content/en/blog/_index.md b/docs/content/en/blog/_index.md similarity index 100% rename from docsy/content/en/blog/_index.md rename to docs/content/en/blog/_index.md diff --git a/docsy/content/en/blog/news/_index.md b/docs/content/en/blog/news/_index.md similarity index 100% rename from docsy/content/en/blog/news/_index.md rename to docs/content/en/blog/news/_index.md diff --git a/docsy/content/en/blog/releases/_index.md b/docs/content/en/blog/releases/_index.md similarity index 100% rename from docsy/content/en/blog/releases/_index.md rename to docs/content/en/blog/releases/_index.md diff --git a/docsy/content/en/community/_index.md b/docs/content/en/community/_index.md similarity index 100% rename from docsy/content/en/community/_index.md rename to docs/content/en/community/_index.md diff --git a/docsy/content/en/docs/_index.md b/docs/content/en/docs/_index.md similarity index 100% rename from docsy/content/en/docs/_index.md rename to docs/content/en/docs/_index.md diff --git a/docsy/content/en/docs/architecture/_index.md b/docs/content/en/docs/architecture/_index.md similarity index 100% rename from docsy/content/en/docs/architecture/_index.md rename to docs/content/en/docs/architecture/_index.md diff --git a/docsy/content/en/docs/configuration/_index.md b/docs/content/en/docs/configuration/_index.md similarity index 100% rename from docsy/content/en/docs/configuration/_index.md rename to docs/content/en/docs/configuration/_index.md diff --git a/docsy/content/en/docs/contributing/_index.md b/docs/content/en/docs/contributing/_index.md similarity index 100% rename from docsy/content/en/docs/contributing/_index.md rename to docs/content/en/docs/contributing/_index.md diff --git a/docsy/content/en/docs/dependent-resources/_index.md b/docs/content/en/docs/dependent-resources/_index.md similarity index 71% rename from docsy/content/en/docs/dependent-resources/_index.md rename to docs/content/en/docs/dependent-resources/_index.md index be67ec6ab6..ab0ccd06c9 100644 --- a/docsy/content/en/docs/dependent-resources/_index.md +++ b/docs/content/en/docs/dependent-resources/_index.md @@ -3,6 +3,8 @@ title: Dependent Resources weight: 60 --- +# Dependent Resources + ## Motivations and Goals Most operators need to deal with secondary resources when trying to realize the desired state @@ -96,13 +98,13 @@ and labels, which are ignored by default: ```java public class MyDependentResource extends KubernetesDependentResource - implements Matcher { - // your implementation + implements Matcher { + // your implementation - public Result match(MyDependent actualResource, MyPrimary primary, - Context context) { - return GenericKubernetesResourceMatcher.match(this, actualResource, primary, context, true); - } + public Result match(MyDependent actualResource, MyPrimary primary, + Context context) { + return GenericKubernetesResourceMatcher.match(this, actualResource, primary, context, true); + } } ``` @@ -136,24 +138,24 @@ Deleted (or set to be garbage collected). The following example shows how to cre @KubernetesDependent(labelSelector = WebPageManagedDependentsReconciler.SELECTOR) class DeploymentDependentResource extends CRUDKubernetesDependentResource { - public DeploymentDependentResource() { - super(Deployment.class); - } - - @Override - protected Deployment desired(WebPage webPage, Context context) { - var deploymentName = deploymentName(webPage); - Deployment deployment = loadYaml(Deployment.class, getClass(), "deployment.yaml"); - deployment.getMetadata().setName(deploymentName); - deployment.getMetadata().setNamespace(webPage.getMetadata().getNamespace()); - deployment.getSpec().getSelector().getMatchLabels().put("app", deploymentName); - - deployment.getSpec().getTemplate().getMetadata().getLabels() - .put("app", deploymentName); - deployment.getSpec().getTemplate().getSpec().getVolumes().get(0) - .setConfigMap(new ConfigMapVolumeSourceBuilder().withName(configMapName(webPage)).build()); - return deployment; - } + public DeploymentDependentResource() { + super(Deployment.class); + } + + @Override + protected Deployment desired(WebPage webPage, Context context) { + var deploymentName = deploymentName(webPage); + Deployment deployment = loadYaml(Deployment.class, getClass(), "deployment.yaml"); + deployment.getMetadata().setName(deploymentName); + deployment.getMetadata().setNamespace(webPage.getMetadata().getNamespace()); + deployment.getSpec().getSelector().getMatchLabels().put("app", deploymentName); + + deployment.getSpec().getTemplate().getMetadata().getLabels() + .put("app", deploymentName); + deployment.getSpec().getTemplate().getSpec().getVolumes().get(0) + .setConfigMap(new ConfigMapVolumeSourceBuilder().withName(configMapName(webPage)).build()); + return deployment; + } } ``` @@ -189,25 +191,25 @@ instances are managed by JOSDK, an example of which can be seen below: ```java @ControllerConfiguration( - labelSelector = SELECTOR, - dependents = { - @Dependent(type = ConfigMapDependentResource.class), - @Dependent(type = DeploymentDependentResource.class), - @Dependent(type = ServiceDependentResource.class) - }) + labelSelector = SELECTOR, + dependents = { + @Dependent(type = ConfigMapDependentResource.class), + @Dependent(type = DeploymentDependentResource.class), + @Dependent(type = ServiceDependentResource.class) + }) public class WebPageManagedDependentsReconciler - implements Reconciler, ErrorStatusHandler { + implements Reconciler, ErrorStatusHandler { - // omitted code + // omitted code - @Override - public UpdateControl reconcile(WebPage webPage, Context context) { + @Override + public UpdateControl reconcile(WebPage webPage, Context context) { - final var name = context.getSecondaryResource(ConfigMap.class).orElseThrow() - .getMetadata().getName(); - webPage.setStatus(createStatus(name)); - return UpdateControl.patchStatus(webPage); - } + final var name = context.getSecondaryResource(ConfigMap.class).orElseThrow() + .getMetadata().getName(); + webPage.setStatus(createStatus(name)); + return UpdateControl.patchStatus(webPage); + } } ``` @@ -222,104 +224,11 @@ It is also possible to wire dependent resources programmatically. In practice th developer is responsible for initializing and managing the dependent resources as well as calling their `reconcile` method. However, this makes it possible for developers to fully customize the reconciliation process. Standalone dependent resources should be used in cases when the managed use -case does not fit. - -Note that [Workflows](https://javaoperatorsdk.io/docs/workflows) also can be invoked from standalone -resources. - -The following sample is similar to the one above, simply performing additional checks, and -conditionally creating an `Ingress`: - -```java - -@ControllerConfiguration -public class WebPageStandaloneDependentsReconciler - implements Reconciler, ErrorStatusHandler, - EventSourceInitializer { - - private KubernetesDependentResource configMapDR; - private KubernetesDependentResource deploymentDR; - private KubernetesDependentResource serviceDR; - private KubernetesDependentResource ingressDR; - - public WebPageStandaloneDependentsReconciler(KubernetesClient kubernetesClient) { - // 1. - createDependentResources(kubernetesClient); - } - - @Override - public List prepareEventSources(EventSourceContext context) { - // 2. - return List.of( - configMapDR.initEventSource(context), - deploymentDR.initEventSource(context), - serviceDR.initEventSource(context)); - } - - @Override - public UpdateControl reconcile(WebPage webPage, Context context) { - - // 3. - if (!isValidHtml(webPage.getHtml())) { - return UpdateControl.patchStatus(setInvalidHtmlErrorMessage(webPage)); - } - - // 4. - configMapDR.reconcile(webPage, context); - deploymentDR.reconcile(webPage, context); - serviceDR.reconcile(webPage, context); - - // 5. - if (Boolean.TRUE.equals(webPage.getSpec().getExposed())) { - ingressDR.reconcile(webPage, context); - } else { - ingressDR.delete(webPage, context); - } +case does not fit. You can, of course, also use [Workflows](https://javaoperatorsdk.io/docs/workflows) when managing +resources programmatically. - // 6. - webPage.setStatus( - createStatus(configMapDR.getResource(webPage).orElseThrow().getMetadata().getName())); - return UpdateControl.patchStatus(webPage); - } - - private void createDependentResources(KubernetesClient client) { - this.configMapDR = new ConfigMapDependentResource(); - this.deploymentDR = new DeploymentDependentResource(); - this.serviceDR = new ServiceDependentResource(); - this.ingressDR = new IngressDependentResource(); - - Arrays.asList(configMapDR, deploymentDR, serviceDR, ingressDR).forEach(dr -> { - dr.setKubernetesClient(client); - dr.configureWith(new KubernetesDependentResourceConfig() - .setLabelSelector(DEPENDENT_RESOURCE_LABEL_SELECTOR)); - }); - } - - // omitted code -} -``` - -There are multiple things happening here: - -1. Dependent resources are explicitly created and can be access later by reference. -2. Event sources are produced by the dependent resources, but needs to be explicitly registered in - this case by implementing - the [`EventSourceInitializer`](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/EventSourceInitializer.java) - interface. -3. The input html is validated, and error message is set in case it is invalid. -4. Reconciliation of dependent resources is called explicitly, but here the workflow - customization is fully in the hand of the developer. -5. An `Ingress` is created but only in case `exposed` flag set to true on custom resource. Tries to - delete it if not. -6. Status is set in a different way, this is just an alternative way to show, that the actual state - can be read using the reference. This could be written in a same way as in the managed example. - -See the full source code of -sample [here](https://github.com/operator-framework/java-operator-sdk/blob/main/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageStandaloneDependentsReconciler.java) -. - -Note also the Workflows feature makes it possible to also support this conditional creation use -case in managed dependent resources. +You can see a commented example of how to do +so [here](https://github.com/operator-framework/java-operator-sdk/blob/main/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageStandaloneDependentsReconciler.java). ## Creating/Updating Kubernetes Resources @@ -352,17 +261,17 @@ Since SSA is a complex feature, JOSDK implements a feature flag allowing users t these implementations. See in [ConfigurationService](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java#L332-L358). -It is, however, important to note that these implementations are default, generic -implementations that the framework can provide expected behavior out of the box. In many -situations, these will work just fine but it is also possible to provide matching algorithms +It is, however, important to note that these implementations are default, generic +implementations that the framework can provide expected behavior out of the box. In many +situations, these will work just fine but it is also possible to provide matching algorithms optimized for specific use cases. This is easily done by simply overriding -the `match(...)` [method](https://github.com/java-operator-sdk/java-operator-sdk/blob/e16559fd41bbb8bef6ce9d1f47bffa212a941b09/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependentResource.java#L156-L156). +the `match(...)` [method](https://github.com/java-operator-sdk/java-operator-sdk/blob/e16559fd41bbb8bef6ce9d1f47bffa212a941b09/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependentResource.java#L156-L156). -It is also possible to bypass the matching logic altogether to simply rely on the server-side +It is also possible to bypass the matching logic altogether to simply rely on the server-side apply mechanism if always sending potentially unchanged resources to the cluster is not an issue. JOSDK's matching mechanism allows to spare some potentially useless calls to the Kubernetes API -server. To bypass the matching feature completely, simply override the `match` method to always -return `false`, thus telling JOSDK that the actual state never matches the desired one, making +server. To bypass the matching feature completely, simply override the `match` method to always +return `false`, thus telling JOSDK that the actual state never matches the desired one, making it always update the resources using SSA. WARNING: Older versions of Kubernetes before 1.25 would create an additional resource version for every SSA update @@ -382,27 +291,32 @@ customized by implementing by the dependent resource. See sample in one of the integration -tests [here](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primaryindexer/DependentPrimaryIndexerTestReconciler.java#L25-L25) +tests [here](https://github.com/operator-framework/java-operator-sdk/tree/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primaryindexer) . ## Multiple Dependent Resources of Same Type When dealing with multiple dependent resources of same type, the dependent resource implementation needs to know which specific resource should be targeted when reconciling a given dependent -resource, since there will be multiple instances of that type which could possibly be used, each -associated with the same primary resource. In order to do this, JOSDK relies on the -[resource discriminator](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ResourceDiscriminator.java) -concept. Resource discriminators uniquely identify the target resource of a dependent resource. -In the managed Kubernetes dependent resources case, the discriminator can be declaratively set -using the `@KubernetesDependent` annotation: - -```java - -@KubernetesDependent(resourceDiscriminator = ConfigMap1Discriminator.class) -public class MultipleManagedDependentResourceConfigMap1 { -//... -} -``` +resource, since there could be multiple instances of that type which could possibly be used, each +associated with the same primary resource. In this situation, JOSDK automatically selects the appropriate secondary +resource matching the desired state associated with the primary resource. This makes sense because the desired +state computation already needs to be able to discriminate among multiple related secondary resources to tell JOSDK how +they should be reconciled. + +There might be casees, though, where it might be problematic to call the `desired` method several times (for example, because it is costly to do so), it is always possible to override this automated discrimination using several means: + +- Implement your own `getSecondaryResource` method on your `DependentResource` implementation from scratch. +- Override the `selectManagedSecondaryResource` method, if your `DependentResource` extends `AbstractDependentResource`. + This should be relatively simple to override this method to optimize the matching to your needs. You can see an + example of such an implementation in + the [`ExternalWithStateDependentResource`](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalWithStateDependentResource.java) + class. +- Override the `managedSecondaryResourceID` method, if your `DependentResource` extends `KubernetesDependentResource`, + where it's very often possible to easily determine the `ResourceID` of the secondary resource. This would probably be + the easiest solution if you're working with Kubernetes resources. + +### Sharing an Event Source Between Dependent Resources Dependent resources usually also provide event sources. When dealing with multiple dependents of the same type, one needs to decide whether these dependent resources should track the same @@ -418,10 +332,10 @@ would look as follows: useEventSourceWithName = "configMapSource") ``` -A sample is provided as an integration test both -for [managed](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleManagedDependentSameTypeIT.java) -and -for [standalone](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleDependentResourceIT.java) +A sample is provided as an integration test both: +for [managed](https://github.com/operator-framework/java-operator-sdk/tree/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledrsametypenodiscriminator) + +For [standalone](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresource) cases. ## Bulk Dependent Resources @@ -438,11 +352,11 @@ implement the interface. Various examples are provided -as [integration tests](https://github.com/java-operator-sdk/java-operator-sdk/tree/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent) +as [integration tests](https://github.com/operator-framework/java-operator-sdk/tree/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent) . To see how bulk dependent resources interact with workflow conditions, please refer to this -[integration test](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent/BulkDependentWithConditionIT.java). +[integration test](https://github.com/operator-framework/java-operator-sdk/tree/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/conidition). ## External State Tracking Dependent Resources @@ -463,11 +377,11 @@ interface. Note that most of the JOSDK-provided dependent resource implementatio `PollingDependentResource` or `PerResourcePollingDependentResource` already extends `AbstractExternalDependentResource`, thus supporting external state tracking out of the box. -See [integration test](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/ExternalStateDependentIT.java) +See [integration test](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateDependentIT.java) as a sample. For a better understanding it might be worth to study -a [sample implementation](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/ExternalStateReconciler.java) +a [sample implementation](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateReconciler.java) without dependent resources. Please also refer to the [docs](/docs/patterns-and-best-practices#managing-state) for managing state in @@ -481,18 +395,21 @@ created. For example, if three bulk dependent resources associated with external three associated `ConfigMaps` (assuming `ConfigMaps` are used as a state-tracking resource) will also be created, one per dependent resource. -See [integration test](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/ExternalStateBulkIT.java) +See [integration test](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/externalstatebulkdependent) as a sample. - ## GenericKubernetesResource based Dependent Resources -In rare circumstances resource handling where there is no class representation or just typeless handling might be needed. -Fabric8 Client provides [GenericKubernetesResource](https://github.com/fabric8io/kubernetes-client/blob/main/doc/CHEATSHEET.md#resource-typeless-api) -to support that. +In rare circumstances resource handling where there is no class representation or just typeless handling might be +needed. +Fabric8 Client +provides [GenericKubernetesResource](https://github.com/fabric8io/kubernetes-client/blob/main/doc/CHEATSHEET.md#resource-typeless-api) +to support that. -For dependent resource this is supported by [GenericKubernetesDependentResource](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesDependentResource.java#L8-L8) -. See samples [here](https://github.com/java-operator-sdk/java-operator-sdk/tree/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource). +For dependent resource this is supported +by [GenericKubernetesDependentResource](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesDependentResource.java#L8-L8) +. See +samples [here](https://github.com/java-operator-sdk/java-operator-sdk/tree/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource). ## Other Dependent Resource Features @@ -518,13 +435,13 @@ For dependent resource this is supported by [GenericKubernetesDependentResource] practice in general) - so for example if there are two config map dependents, either there should be a shared event source between them, or a label selector on the event sources to select only the relevant events, see - in [related integration test](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/orderedmanageddependent/ConfigMapDependentResource1.java) + in [related integration test](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/orderedmanageddependent/ConfigMapDependentResource2.java) . ## "Read-only" Dependent Resources vs. Event Source See Integration test for a read-only -dependent [here](https://github.com/java-operator-sdk/java-operator-sdk/blob/249b41f3c68c4d0e9c77c41eca647a69a24347b0/operator-framework/src/test/java/io/javaoperatorsdk/operator/PrimaryToSecondaryDependentIT.java). +dependent [here](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/ConfigMapDependent.java). Some secondary resources only exist as input for the reconciliation process and are never updated *by a controller* (they might, and actually usually do, get updated by users interacting diff --git a/docsy/content/en/docs/faq/_index.md b/docs/content/en/docs/faq/_index.md similarity index 100% rename from docsy/content/en/docs/faq/_index.md rename to docs/content/en/docs/faq/_index.md diff --git a/docsy/content/en/docs/features/_index.md b/docs/content/en/docs/features/_index.md similarity index 90% rename from docsy/content/en/docs/features/_index.md rename to docs/content/en/docs/features/_index.md index 8c775ed4fa..17c385e119 100644 --- a/docsy/content/en/docs/features/_index.md +++ b/docs/content/en/docs/features/_index.md @@ -3,6 +3,8 @@ title: Features weight: 50 --- +# Features + The Java Operator SDK (JOSDK) is a high level framework and related tooling aimed at facilitating the implementation of Kubernetes operators. The features are by default following the best practices in an opinionated way. However, feature flags and other configuration options @@ -62,7 +64,8 @@ and/or re-schedule a reconciliation with a desired time delay: @Override public UpdateControl reconcile( EventSourceTestCustomResource resource, Context context) { - ... + // omitted code + return UpdateControl.patchStatus(resource).rescheduleAfter(10, TimeUnit.SECONDS); } ``` @@ -73,7 +76,8 @@ without an update: @Override public UpdateControl reconcile( EventSourceTestCustomResource resource, Context context) { - ... + // omitted code + return UpdateControl.noUpdate().rescheduleAfter(10, TimeUnit.SECONDS); } ``` @@ -85,17 +89,31 @@ Those are the typical use cases of resource updates, however in some cases there the controller wants to update the resource itself (for example to add annotations) or not perform any updates, which is also supported. -It is also possible to update both the status and the resource with the -`updateResourceAndStatus` method. In this case, the resource is updated first followed by the -status, using two separate requests to the Kubernetes API. - -You should always state your intent using `UpdateControl` and let the SDK deal with the actual -updates instead of performing these updates yourself using the actual Kubernetes client so that -the SDK can update its internal state accordingly. - -Resource updates are protected using optimistic version control, to make sure that other updates -that might have occurred in the mean time on the server are not overwritten. This is ensured by -setting the `resourceVersion` field on the processed resources. +It is also possible to update both the status and the resource with the `patchResourceAndStatus` method. In this case, +the resource is updated first followed by the status, using two separate requests to the Kubernetes API. + +From v5 `UpdateControl` only supports patching the resources, by default +using [Server Side Apply (SSA)](https://kubernetes.io/docs/reference/using-api/server-side-apply/). +It is important to understand how SSA works in Kubernetes. Mainly, resources applied using SSA +should contain only the fields identifying the resource and those the user is interested in (a 'fully specified intent' +in Kubernetes parlance), thus usually using a resource created from scratch, see +[sample](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa). +To contrast, see the same sample, this time [without SSA](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourceandstatusnossa/PatchResourceAndStatusNoSSAReconciler.java). + +Non-SSA based patch is still supported. +You can control whether or not to use SSA +using [`ConfigurationServcice.useSSAToPatchPrimaryResource()`](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java#L385-L385) +and the related `ConfigurationServiceOverrider.withUseSSAToPatchPrimaryResource` method. +Related integration test can be +found [here](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourceandstatusnossa). + +Handling resources directly using the client, instead of delegating these updates operations to JOSDK by returning +an `UpdateControl` at the end of your reconciliation, should work appropriately. However, we do recommend to +use `UpdateControl` instead since JOSDK makes sure that the operations are handled properly, since there are subtleties +to be aware of. For example, if you are using a finalizer, JOSDK makes sure to include it in your fully specified intent +so that it is not unintentionally removed from the resource (which would happen if you omit it, since your controller is +the designated manager for that field and Kubernetes interprets the finalizer being gone from the specified intent as a +request for removal). [`DeleteControl`](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/DeleteControl.java) typically instructs the framework to remove the finalizer after the dependent @@ -104,7 +122,8 @@ resource are cleaned up in `cleanup` implementation. ```java public DeleteControl cleanup(MyCustomResource customResource,Context context){ - ... + // omitted code + return DeleteControl.defaultDelete(); } @@ -163,56 +182,7 @@ You can specify the name of the finalizer to use for your `Reconciler` using the [`@ControllerConfiguration`](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ControllerConfiguration.java) annotation. If you do not specify a finalizer name, one will be automatically generated for you. -## Automatic Observed Generation Handling - -Having an `.observedGeneration` value on your resources' status is a best practice to -indicate the last generation of the resource which was successfully reconciled by the controller. -This helps users / administrators diagnose potential issues. - -In order to have this feature working: - -- the **status class** (not the resource itself) must implement the - [`ObservedGenerationAware`](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/ObservedGenerationAware.java) - interface. See also - the [`ObservedGenerationAwareStatus`](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/ObservedGenerationAwareStatus.java) - convenience implementation that you can extend in your own status class implementations. -- The other condition is that the `CustomResource.getStatus()` method should not return `null`. - So the status should be instantiated when the object is returned using the `UpdateControl`. - -If these conditions are fulfilled and generation awareness is activated, the observed generation -is automatically set by the framework after the `reconcile` method is called. Note that the -observed generation is also updated even when `UpdateControl.noUpdate()` is returned from the -reconciler. See this feature at work in -the [WebPage example](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageStatus.java#L5) -. - -```java -public class WebPageStatus extends ObservedGenerationAwareStatus { - - private String htmlConfigMap; - - ... -} -``` - -Initializing status automatically on custom resource could be done by overriding the `initStatus` method -of `CustomResource`. However, this is NOT advised, since breaks the status patching if you use: -`UpdateControl.patchStatus`. See -also [javadocs](https://github.com/java-operator-sdk/java-operator-sdk/blob/3994f5ffc1fb000af81aa198abf72a5f75fd3e97/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/UpdateControl.java#L41-L42) -. - -```java -@Group("sample.javaoperatorsdk") -@Version("v1") -public class WebPage extends CustomResource - implements Namespaced { - - @Override - protected WebPageStatus initStatus() { - return new WebPageStatus(); - } -} -``` +From v5 by default finalizer is added using Served Side Apply. See also UpdateControl in docs. ## Generation Awareness and Event Filtering @@ -231,23 +201,22 @@ To turn off this feature, set `generationAwareEventProcessing` to `false` for th ## Support for Well Known (non-custom) Kubernetes Resources A Controller can be registered for a non-custom resource, so well known Kubernetes resources like ( -`Ingress`, `Deployment`,...). Note that automatic observed generation handling is not supported -for these resources, though, in this case, the handling of the observed generation is probably -handled by the primary controller. +`Ingress`, `Deployment`,...). See -the [integration test](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/deployment/DeploymentReconciler.java) +the [integration test](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/deployment) for reconciling deployments. ```java public class DeploymentReconciler implements Reconciler, TestExecutionInfoProvider { - @Override - public UpdateControl reconcile( - Deployment resource, Context context) { - ... - } + @Override + public UpdateControl reconcile( + Deployment resource, Context context) { + // omitted code + } +} ``` ## Max Interval Between Reconciliations @@ -265,6 +234,7 @@ standard annotation: @ControllerConfiguration(maxReconciliationInterval = @MaxReconciliationInterval( interval = 50, timeUnit = TimeUnit.MILLISECONDS)) +public class MyReconciler implements Reconciler {} ``` The event is not propagated at a fixed rate, rather it's scheduled after each reconciliation. So the @@ -487,9 +457,8 @@ related [method](https://github.com/java-operator-sdk/java-operator-sdk/blob/mai ### Registering Event Sources -To register event sources, your `Reconciler` has to implement the -[`EventSourceInitializer`](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/EventSourceInitializer.java) -interface and initialize a list of event sources to register. One way to see this in action is +To register event sources, your `Reconciler` has to override the `prepareEventSources` and return +list of event sources to register. One way to see this in action is to look at the [tomcat example](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/sample-operators/tomcat-operator/src/main/java/io/javaoperatorsdk/operator/sample/WebappReconciler.java) (irrelevant details omitted): @@ -499,8 +468,9 @@ to look at the @ControllerConfiguration public class WebappReconciler implements Reconciler, Cleaner, EventSourceInitializer { - - @Override + // ommitted code + + @Override public Map prepareEventSources(EventSourceContext context) { InformerConfiguration configuration = InformerConfiguration.from(Tomcat.class, context) @@ -512,7 +482,7 @@ public class WebappReconciler return EventSourceInitializer .nameEventSources(new InformerEventSource<>(configuration, context)); } - ... + } ``` @@ -561,7 +531,7 @@ between a primary resource and its associated secondary resources using an imple `PrimaryToSecondaryMapper` interface. This is typically needed when there are many-to-one or many-to-many relationships between primary and secondary resources, e.g. when the primary resource is referencing secondary resources. -See [PrimaryToSecondaryIT](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/PrimaryToSecondaryIT.java) +See [PrimaryToSecondaryIT](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primarytosecondary/PrimaryToSecondaryIT.java) integration test for a sample. ### Built-in EventSources @@ -638,6 +608,25 @@ parts of reconciliation logic and during the execution of the controller: For more information about MDC see this [link](https://www.baeldung.com/mdc-in-log4j-2-logback). +## InformerEventSource Multi-Cluster Support + +It is possible to handle resources for remote cluster with `InformerEventSource`. To do so, +simply set a client that connects to a remote cluster: + +```java + +InformerEventSourceConfiguration configuration = + InformerEventSourceConfiguration.from(SecondaryResource.class, PrimaryResource.class) + .withKubernetesClient(remoteClusterClient) + .withSecondaryToPrimaryMapper(Mappers.fromDefaultAnnotations()); + +``` + +You will also need to specify a `SecondaryToPrimaryMapper`, since the default one +is based on owner references and won't work across cluster instances. You could, for example, use the provided implementation that relies on annotations added to the secondary resources to identify the associated primary resource. + +See related [integration test](https://github.com/operator-framework/java-operator-sdk/tree/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informerremotecluster). + ## Dynamically Changing Target Namespaces A controller can be configured to watch a specific set of namespaces in addition of the @@ -656,15 +645,15 @@ registering an associated `Informer` and then calling the `changeNamespaces` met ```java -public static void main(String[]args)throws IOException{ - KubernetesClient client=new DefaultKubernetesClient(); - Operator operator=new Operator(client); - RegisteredController registeredController=operator.register(new WebPageReconciler(client)); - operator.installShutdownHook(); - operator.start(); +public static void main(String[] args) { + KubernetesClient client = new DefaultKubernetesClient(); + Operator operator = new Operator(client); + RegisteredController registeredController = operator.register(new WebPageReconciler(client)); + operator.installShutdownHook(); + operator.start(); - // call registeredController further while operator is running - } + // call registeredController further while operator is running +} ``` @@ -676,8 +665,7 @@ configured appropriately so that the `followControllerNamespaceChanges` method r ```java @ControllerConfiguration -public class MyReconciler - implements Reconciler, EventSourceInitializer { +public class MyReconciler implements Reconciler { @Override public Map prepareEventSources( @@ -688,7 +676,7 @@ public class MyReconciler .withNamespacesInheritedFromController(context) .build(), context); - return EventSourceInitializer.nameEventSources(configMapES); + return EventSourceUtils.nameEventSources(configMapES); } } @@ -698,7 +686,7 @@ As seen in the above code snippet, the informer will have the initial namespaces controller, but also will adjust the target namespaces if it changes for the controller. See also -the [integration test](https://github.com/java-operator-sdk/java-operator-sdk/blob/ec37025a15046d8f409c77616110024bf32c3416/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/changenamespace/ChangeNamespaceTestReconciler.java) +the [integration test](https://github.com/operator-framework/java-operator-sdk/tree/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/changenamespace) for this feature. ## Leader Election @@ -767,8 +755,8 @@ You can use a different implementation by overriding the default one provided by follows: ```java -Metrics metrics= …; -Operator operator = new Operator(client, o -> o.withMetrics()); +Metrics metrics; // initialize your metrics implementation +Operator operator = new Operator(client, o -> o.withMetrics(metrics)); ``` ### Micrometer implementation @@ -784,8 +772,8 @@ To create a `MicrometerMetrics` implementation that behaves how it has historica instance via: ```java -MeterRegistry registry= …; -Metrics metrics=new MicrometerMetrics(registry) +MeterRegistry registry; // initialize your registry implementation +Metrics metrics = new MicrometerMetrics(registry); ``` Note, however, that this constructor is deprecated and we encourage you to use the factory methods instead, which either @@ -801,7 +789,7 @@ basis, deleting the associated meters after 5 seconds when a resource is deleted MicrometerMetrics.newPerResourceCollectingMicrometerMetricsBuilder(registry) .withCleanUpDelayInSeconds(5) .withCleaningThreadNumber(2) - .build() + .build(); ``` The micrometer implementation records the following metrics: diff --git a/docsy/content/en/docs/getting-started/_index.md b/docs/content/en/docs/getting-started/_index.md similarity index 100% rename from docsy/content/en/docs/getting-started/_index.md rename to docs/content/en/docs/getting-started/_index.md diff --git a/docsy/content/en/docs/glossary/_index.md b/docs/content/en/docs/glossary/_index.md similarity index 100% rename from docsy/content/en/docs/glossary/_index.md rename to docs/content/en/docs/glossary/_index.md diff --git a/docsy/content/en/docs/intro-to-operators/_index.md b/docs/content/en/docs/intro-to-operators/_index.md similarity index 100% rename from docsy/content/en/docs/intro-to-operators/_index.md rename to docs/content/en/docs/intro-to-operators/_index.md diff --git a/docsy/content/en/docs/migration/_index.md b/docs/content/en/docs/migration/_index.md similarity index 100% rename from docsy/content/en/docs/migration/_index.md rename to docs/content/en/docs/migration/_index.md diff --git a/docsy/content/en/docs/migration/v2-migration.md b/docs/content/en/docs/migration/v2-migration.md similarity index 98% rename from docsy/content/en/docs/migration/v2-migration.md rename to docs/content/en/docs/migration/v2-migration.md index 4500672308..5b0ef31c45 100644 --- a/docsy/content/en/docs/migration/v2-migration.md +++ b/docs/content/en/docs/migration/v2-migration.md @@ -1,12 +1,9 @@ --- title: Migrating from v1 to v2 -description: Migrating from v1 to v2 layout: docs permalink: /docs/v2-migration --- -# Migrating from v1 to v2 - Version 2 of the framework introduces improvements, features and breaking changes for the APIs both internal and user facing ones. The migration should be however trivial in most of the cases. For detailed overview of all major issues until the release of diff --git a/docsy/content/en/docs/migration/v3-1-migration.md b/docs/content/en/docs/migration/v3-1-migration.md similarity index 97% rename from docsy/content/en/docs/migration/v3-1-migration.md rename to docs/content/en/docs/migration/v3-1-migration.md index 9a7d9f7a9f..e42c4a206a 100644 --- a/docsy/content/en/docs/migration/v3-1-migration.md +++ b/docs/content/en/docs/migration/v3-1-migration.md @@ -1,12 +1,9 @@ --- title: Migrating from v3 to v3.1 -description: Migrating from v3 to v3.1 layout: docs permalink: /docs/v3-1-migration --- -# Migrating from v3 to v3.1 - ## ReconciliationMaxInterval Annotation has been renamed to MaxReconciliationInterval Associated methods on both the `ControllerConfiguration` class and annotation have also been diff --git a/docsy/content/en/docs/migration/v3-migration.md b/docs/content/en/docs/migration/v3-migration.md similarity index 98% rename from docsy/content/en/docs/migration/v3-migration.md rename to docs/content/en/docs/migration/v3-migration.md index 97e844904e..462ab26f9f 100644 --- a/docsy/content/en/docs/migration/v3-migration.md +++ b/docs/content/en/docs/migration/v3-migration.md @@ -1,12 +1,9 @@ --- title: Migrating from v2 to v3 -description: Migrating from v2 to v3 layout: docs permalink: /docs/v3-migration --- -# Migrating from v2 to v3 - Version 3 introduces some breaking changes to APIs, however the migration to these changes should be trivial. ## Reconciler diff --git a/docsy/content/en/docs/migration/v4-3-migration.md b/docs/content/en/docs/migration/v4-3-migration.md similarity index 96% rename from docsy/content/en/docs/migration/v4-3-migration.md rename to docs/content/en/docs/migration/v4-3-migration.md index 17d3be70b4..e9fd58c5f8 100644 --- a/docsy/content/en/docs/migration/v4-3-migration.md +++ b/docs/content/en/docs/migration/v4-3-migration.md @@ -1,12 +1,9 @@ --- title: Migrating from v4.2 to v4.3 -description: Migrating from v4.2 to v4.3 layout: docs permalink: /docs/v4-3-migration --- -# Migrating from v4.2 to v4.3 - ## Condition API Change In Workflows the target of the condition was the managed resource itself, not the target dependent resource. diff --git a/docsy/content/en/docs/migration/v4-4-migration.md b/docs/content/en/docs/migration/v4-4-migration.md similarity index 98% rename from docsy/content/en/docs/migration/v4-4-migration.md rename to docs/content/en/docs/migration/v4-4-migration.md index c198871f3f..998e6ddf9a 100644 --- a/docsy/content/en/docs/migration/v4-4-migration.md +++ b/docs/content/en/docs/migration/v4-4-migration.md @@ -1,12 +1,9 @@ --- title: Migrating from v4.3 to v4.4 -description: Migrating from v4.3 to v4.4 layout: docs permalink: /docs/v4-4-migration --- -# Migrating from v4.3 to v4.4 - ## API changes ### ConfigurationService diff --git a/docsy/content/en/docs/migration/v4-5-migration.md b/docs/content/en/docs/migration/v4-5-migration.md similarity index 96% rename from docsy/content/en/docs/migration/v4-5-migration.md rename to docs/content/en/docs/migration/v4-5-migration.md index 0ff08eef13..eff1581d87 100644 --- a/docsy/content/en/docs/migration/v4-5-migration.md +++ b/docs/content/en/docs/migration/v4-5-migration.md @@ -1,12 +1,9 @@ --- title: Migrating from v4.4 to v4.5 -description: Migrating from v4.4 to v4.5 layout: docs permalink: /docs/v4-5-migration --- -# Migrating from v4.4 to v4.5 - Version 4.5 introduces improvements related to event handling for Dependent Resources, more precisely the [caching and event handling](https://javaoperatorsdk.io/docs/dependent-resources#caching-and-event-handling-in-kubernetesdependentresource) features. As a result the Kubernetes resources managed using diff --git a/docs/content/en/docs/migration/v5-0-migration.md b/docs/content/en/docs/migration/v5-0-migration.md new file mode 100644 index 0000000000..fdf624e29c --- /dev/null +++ b/docs/content/en/docs/migration/v5-0-migration.md @@ -0,0 +1,64 @@ +--- +title: Migrating from v4.7 to v5.0 +description: Migrating from v4.7 to v5.0 +--- + +# Migrating from v4.7 to v5.0 + +## API Tweaks + +1. [Result of managed dependent resources](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/ManagedDependentResourceContext.java#L55-L57) + is not `Optional` anymore. In case you use this result, simply use the result + objects directly. +2. `EventSourceInitializer` is not a separate interface anymore. It is part of the `Reconciler` interface with a + default implementation. You can simply remove this interface from your reconciler. The + [`EventSourceUtils`](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/EventSourceUtils.java#L11-L11) + now contains all the utility methods used for event sources naming that were previously defined in + the `EventSourceInitializer` interface. +3. Similarly, the `EventSourceProvider` interface has been remove, replaced by explicit initialization of the associated + event source on `DependentResource` via the ` + Optional> eventSource(EventSourceContext

eventSourceContext)` method. +4. Event sources are now explicitly named (via the `name` method of the `EventSource` interface). Built-in event sources + implementation have been updated to allow you to specify a name when instantiating them. If you don't provide a name + for your `EventSource` implementation (for example, by using its default, no-arg constructor), one will be + automatically generated. This simplifies the API to define event source to + `List prepareEventSources(EventSourceContext

context)`. + !!! IMPORTANT !!! + If you use dynamic registration of event sources, be sure to name your event sources explicitly as letting JOSDK name + them automatically might result in duplicated event sources being registered as JOSDK relies on the name to identify + event sources and concurrent, dynamic registration might lead to identical event sources having different generated + names, thus leading JOSDK to consider them as different and hence, register them multiple times. +5. Updates through `UpdateControl` now + use [Server Side Apply (SSA)](https://kubernetes.io/docs/reference/using-api/server-side-apply/) by default to add + the finalizer and for all + the patch operations in `UpdateControl`. The update operations were removed. If you do not wish to use SSA, you can + deactivate the feature using `ConfigurationService.useSSAToPatchPrimaryResource` and + related `ConfigurationServiceOverrider.withUseSSAToPatchPrimaryResource`. + + !!! IMPORTANT !!! + + See known issues with migration from non-SSA to SSA based status updates here: + [integration test](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/StatusPatchSSAMigrationIT.java#L71-L82) + where it is demonstrated. Also, the related part of + a [workaround](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/StatusPatchSSAMigrationIT.java#L110-L116). + +6. `ManagedDependentResourceContext` has been renamed to `ManagedWorkflowAndDependentResourceContext` and is accessed + via the accordingly renamed `managedWorkflowAndDependentResourceContext` method. +7. `ResourceDiscriminator` was removed. In most of the cases you can just delete the discriminator, everything should + work without it by default. To optimize and handle special cases see the relevant section + in [Dependent Resource documentation](/docs/dependent-resources#multiple-dependent-resources-of-same-type). +8. `ConfigurationService.getTerminationTimeoutSeconds` and associated overriding mechanism have been removed, + use `Operator.stop(Duration)` instead. +9. `Operator.installShutdownHook()` has been removed, use `Operator.installShutdownHook(Duration)` instead +10. Automated observed generation handling feature was removed (`ObservedGenerationAware` interface + and `ObservedGenerationAwareStatus` class were deleted). Manually handling observed generation is fairly easy to do + in your reconciler, however, it cannot be done automatically when using SSA. We therefore removed the feature since + it would have been confusing to have a different behavior for SSA and non-SSA cases. For an example of how to do + observed generation handling manually in your reconciler, see + [this sample](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/manualobservedgeneration/ManualObservedGenerationReconciler.java). +11. `BulkDependentResource` now supports [read-only mode](https://github.com/operator-framework/java-operator-sdk/issues/2233). + This also means, that `BulkDependentResource` now does not automatically implement `Creator` and `Deleter` as before. + Make sure to implement those interfaces in your bulk dependent resources. You can use also the new helper interface, the + [`CRUDBulkDependentResource`](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/CRUDBulkDependentResource.java) + what also implement `BulkUpdater` interface. +12. `ErrorStatusHandler` is deleted. Just delete the interface from your impl. \ No newline at end of file diff --git a/docsy/content/en/docs/patterns-and-best-practices/_index.md b/docs/content/en/docs/patterns-and-best-practices/_index.md similarity index 94% rename from docsy/content/en/docs/patterns-and-best-practices/_index.md rename to docs/content/en/docs/patterns-and-best-practices/_index.md index 422f3f7bfe..a2b3b716b6 100644 --- a/docsy/content/en/docs/patterns-and-best-practices/_index.md +++ b/docs/content/en/docs/patterns-and-best-practices/_index.md @@ -120,3 +120,15 @@ might be a permission issue for some resources in another namespace. The `stopOnInformerErrorDuringStartup` has implication on [cache sync timeout](https://github.com/java-operator-sdk/java-operator-sdk/blob/114c4312c32b34688811df8dd7cea275878c9e73/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java#L177-L179) behavior. If true operator will stop on cache sync timeout. if `false`, after the timeout the controller will start reconcile resources even if one or more event source caches did not sync yet. + +## Graceful Shutdown + +You can provide sufficient time for the reconciler to process and complete the currently ongoing events before shutting down. +The configuration is simple. You just need to set an appropriate duration value for `reconciliationTerminationTimeout` using `ConfigurationServiceOverrider`. + +```java +final var overridden = new ConfigurationServiceOverrider(config) + .withReconciliationTerminationTimeout(Duration.ofSeconds(5)); + +final var operator = new Operator(overridden); +``` diff --git a/docsy/content/en/docs/using-samples/_index.md b/docs/content/en/docs/using-samples/_index.md similarity index 100% rename from docsy/content/en/docs/using-samples/_index.md rename to docs/content/en/docs/using-samples/_index.md diff --git a/docsy/content/en/docs/workflows/_index.md b/docs/content/en/docs/workflows/_index.md similarity index 75% rename from docsy/content/en/docs/workflows/_index.md rename to docs/content/en/docs/workflows/_index.md index 5f275c2b9a..19b5fab104 100644 --- a/docsy/content/en/docs/workflows/_index.md +++ b/docs/content/en/docs/workflows/_index.md @@ -41,10 +41,33 @@ reconciliation process. condition holds or not. This is a very useful feature when your operator needs to handle different flavors of the platform (e.g. OpenShift vs plain Kubernetes) and/or change its behavior based on the availability of optional resources / features (e.g. CertManager, a specific Ingress controller, etc.). - - Activation condition is semi-experimental at the moment, and it has its limitations. - For example event sources cannot be shared between multiple managed dependent resources which use activation condition. - The intention is to further improve and explore the possibilities with this approach. + + A generic activation condition is provided out of the box, called + [CRDPresentActivationCondition](https://github.com/operator-framework/java-operator-sdk/blob/ba5e33527bf9e3ea0bd33025ccb35e677f9d44b4/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/CRDPresentActivationCondition.java) + that will prevent the associated dependent resource from being activated if the Custom Resource Definition associated + with the dependent's resource type is not present on the cluster. + See related [integration test](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/crdpresentactivation). + + To have multiple resources of same type with an activation condition is a bit tricky, since you + don't want to have multiple `InformerEventSource` for the same type, you have to explicitly + name the informer for the Dependent Resource (`@KubernetesDependent(informerConfig = @InformerConfig(name = "configMapInformer"))`) + for all resource of same type with activation condition. This will make sure that only one is registered. + See details at [low level api](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSourceRetriever.java#L20-L52). + +### Result conditions + +While simple conditions are usually enough, it might happen you want to convey extra information as a result of the +evaluation of the conditions (e.g., to report error messages or because the result of the condition evaluation might be +interesting for other purposes). In this situation, you should implement `DetailedCondition` instead of `Condition` and +provide an implementation of the `detailedIsMet` method, which allows you to return a more detailed `Result` object via +which you can provide extra information. The `DetailedCondition.Result` interface provides factory method for your +convenience but you can also provide your own implementation if required. + +You can access the results for conditions from the `WorkflowResult` instance that is returned whenever a workflow is +evaluated. You can access that result from the `ManagedWorkflowAndDependentResourceContext` accessible from the +reconciliation `Context`. You can then access individual condition results using the ` +getDependentConditionResult` methods. You can see an example of this +in [this integration test](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/WorkflowAllFeatureReconciler.java). ## Defining Workflows @@ -70,15 +93,16 @@ will only consider the `ConfigMap` deleted until that post-condition becomes `tr ```java -@ControllerConfiguration(dependents = { - @Dependent(name = DEPLOYMENT_NAME, type = DeploymentDependentResource.class, - readyPostcondition = DeploymentReadyCondition.class), - @Dependent(type = ConfigMapDependentResource.class, - reconcilePrecondition = ConfigMapReconcileCondition.class, - deletePostcondition = ConfigMapDeletePostCondition.class, - activationCondition = ConfigMapActivationCondition.class, - dependsOn = DEPLOYMENT_NAME) +@Workflow(dependents = { + @Dependent(name = DEPLOYMENT_NAME, type = DeploymentDependentResource.class, + readyPostcondition = DeploymentReadyCondition.class), + @Dependent(type = ConfigMapDependentResource.class, + reconcilePrecondition = ConfigMapReconcileCondition.class, + deletePostcondition = ConfigMapDeletePostCondition.class, + activationCondition = ConfigMapActivationCondition.class, + dependsOn = DEPLOYMENT_NAME) }) +@ControllerConfiguration public class SampleWorkflowReconciler implements Reconciler, Cleaner { @@ -120,7 +144,7 @@ page sample): @ControllerConfiguration( labelSelector = WebPageDependentsWorkflowReconciler.DEPENDENT_RESOURCE_LABEL_SELECTOR) public class WebPageDependentsWorkflowReconciler - implements Reconciler, ErrorStatusHandler, EventSourceInitializer { + implements Reconciler, ErrorStatusHandler { public static final String DEPENDENT_RESOURCE_LABEL_SELECTOR = "!low-level"; private static final Logger log = @@ -131,7 +155,7 @@ public class WebPageDependentsWorkflowReconciler private KubernetesDependentResource serviceDR; private KubernetesDependentResource ingressDR; - private Workflow workflow; + private final Workflow workflow; public WebPageDependentsWorkflowReconciler(KubernetesClient kubernetesClient) { initDependentResources(kubernetesClient); @@ -145,7 +169,7 @@ public class WebPageDependentsWorkflowReconciler @Override public Map prepareEventSources(EventSourceContext context) { - return EventSourceInitializer.nameEventSources( + return EventSourceUtils.nameEventSources( configMapDR.initEventSource(context), deploymentDR.initEventSource(context), serviceDR.initEventSource(context), @@ -198,7 +222,7 @@ demonstrated using examples: 2. Root nodes, i.e. nodes in the graph that do not depend on other nodes are reconciled first, in a parallel manner. 3. A DR is reconciled if it does not depend on any other DRs, or *ALL* the DRs it depends on are - reconciled and ready. If a DR defines a reconcile pre-condition and/or an activation condition, + reconciled and ready. If a DR defines a reconcile pre-condition and/or an activation condition, then these condition must become `true` before the DR is reconciled. 4. A DR is considered *ready* if it got successfully reconciled and any ready post-condition it might define is `true`. @@ -326,12 +350,40 @@ checks that the resource is actually removed or that it, at least, doesn't have provides such a delete post-condition implementation in the form of [`KubernetesResourceDeletedCondition`](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/KubernetesResourceDeletedCondition.java) -Also, check usage in an [integration test](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/manageddependentdeletecondition/ManagedDependentDefaultDeleteConditionReconciler.java). +Also, check usage in an [integration test](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/manageddependentdeletecondition/ManagedDependentDefaultDeleteConditionReconciler.java). -In such cases the Kubernetes Dependent Resource should extend `CRUDNoGCKubernetesDependentResource` +In such cases the Kubernetes Dependent Resource should extend `CRUDNoGCKubernetesDependentResource` and NOT `CRUDKubernetesDependentResource` since otherwise the Kubernetes Garbage Collector would delete the resources. In other words if a Kubernetes Dependent Resource depends on another dependent resource, it should not implement -`GargageCollected` interface, otherwise the deletion order won't be guaranteed. +`GargageCollected` interface, otherwise the deletion order won't be guaranteed. + + +## Explicit Managed Workflow Invocation + +Managed workflows, i.e. ones that are declared via annotations and therefore completely managed by JOSDK, are reconciled +before the primary resource. Each dependent resource that can be reconciled (according to the workflow configuration) +will therefore be reconciled before the primary reconciler is called to reconcile the primary resource. There are, +however, situations where it would be be useful to perform additional steps before the workflow is reconciled, for +example to validate the current state, execute arbitrary logic or even skip reconciliation altogether. Explicit +invocation of managed workflow was therefore introduced to solve these issues. + +To use this feature, you need to set the `explicitInvocation` field to `true` on the `@Workflow` annotation and then +call the `reconcileManagedWorkflow` method from the ` +ManagedWorkflowAndDependentResourceContext` retrieved from the reconciliation `Context` provided as part of your primary +resource reconciler `reconcile` method arguments. + +See +related [integration test](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitinvocation) +for more details. + +For `cleanup`, if the `Cleaner` interface is implemented, the `cleanupManageWorkflow()` needs to be called explicitly. +However, if `Cleaner` interface is not implemented, it will be called implicitly. +See +related [integration test](https://github.com/operator-framework/java-operator-sdk/tree/main/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitcleanup). + +While nothing prevents calling the workflow multiple times in a reconciler, it isn't typical or even recommended to do +so. Conversely, if explicit invocation is requested but `reconcileManagedWorkflow` is not called in the primary resource +reconciler, the workflow won't be reconciled at all. ## Notes and Caveats diff --git a/docsy/content/en/featured-background.jpg b/docs/content/en/featured-background.jpg similarity index 100% rename from docsy/content/en/featured-background.jpg rename to docs/content/en/featured-background.jpg diff --git a/docsy/content/en/search.md b/docs/content/en/search.md similarity index 100% rename from docsy/content/en/search.md rename to docs/content/en/search.md diff --git a/docsy/content/fileList.txt b/docs/content/fileList.txt similarity index 100% rename from docsy/content/fileList.txt rename to docs/content/fileList.txt diff --git a/docsy/docker-compose.yaml b/docs/docker-compose.yaml similarity index 100% rename from docsy/docker-compose.yaml rename to docs/docker-compose.yaml diff --git a/docsy/docsy.work b/docs/docsy.work similarity index 100% rename from docsy/docsy.work rename to docs/docsy.work diff --git a/docsy/docsy.work.sum b/docs/docsy.work.sum similarity index 100% rename from docsy/docsy.work.sum rename to docs/docsy.work.sum diff --git a/docsy/go.mod b/docs/go.mod similarity index 100% rename from docsy/go.mod rename to docs/go.mod diff --git a/docsy/go.sum b/docs/go.sum similarity index 100% rename from docsy/go.sum rename to docs/go.sum diff --git a/docsy/hugo.toml b/docs/hugo.toml similarity index 99% rename from docsy/hugo.toml rename to docs/hugo.toml index 520a1cb358..b4535c08af 100644 --- a/docsy/hugo.toml +++ b/docs/hugo.toml @@ -110,7 +110,7 @@ github_repo = "https://github.com/operator-framework/java-operator-sdk/" # github_project_repo = "https://github.com/operator-framework/java-operator-sdk" # Specify a value here if your content directory is not in your repo's root directory -github_subdir = "docsy" +github_subdir = "docs" # Uncomment this if your GitHub repo does not have "main" as the default branch, # or specify a new value if you want to reference another branch in your GitHub links diff --git a/docsy/layouts/404.html b/docs/layouts/404.html similarity index 100% rename from docsy/layouts/404.html rename to docs/layouts/404.html diff --git a/docsy/layouts/_default/_markup/render-heading.html b/docs/layouts/_default/_markup/render-heading.html similarity index 100% rename from docsy/layouts/_default/_markup/render-heading.html rename to docs/layouts/_default/_markup/render-heading.html diff --git a/docsy/netlify.toml b/docs/netlify.toml similarity index 100% rename from docsy/netlify.toml rename to docs/netlify.toml diff --git a/docsy/package.json b/docs/package.json similarity index 100% rename from docsy/package.json rename to docs/package.json diff --git a/docsy/static/favicons/favicon.ico b/docs/static/favicons/favicon.ico similarity index 100% rename from docsy/static/favicons/favicon.ico rename to docs/static/favicons/favicon.ico diff --git a/docsy/static/images/architecture.svg b/docs/static/images/architecture.svg similarity index 100% rename from docsy/static/images/architecture.svg rename to docs/static/images/architecture.svg diff --git a/docsy/static/images/cncf_logo.png b/docs/static/images/cncf_logo.png similarity index 100% rename from docsy/static/images/cncf_logo.png rename to docs/static/images/cncf_logo.png diff --git a/docsy/static/images/cs-logo.svg b/docs/static/images/cs-logo.svg similarity index 100% rename from docsy/static/images/cs-logo.svg rename to docs/static/images/cs-logo.svg diff --git a/docsy/static/images/full-logo-white.svg b/docs/static/images/full-logo-white.svg similarity index 100% rename from docsy/static/images/full-logo-white.svg rename to docs/static/images/full-logo-white.svg diff --git a/docsy/static/images/full_logo.png b/docs/static/images/full_logo.png similarity index 100% rename from docsy/static/images/full_logo.png rename to docs/static/images/full_logo.png diff --git a/docsy/static/images/red-hat.webp b/docs/static/images/red-hat.webp similarity index 100% rename from docsy/static/images/red-hat.webp rename to docs/static/images/red-hat.webp diff --git a/micrometer-support/pom.xml b/micrometer-support/pom.xml index 01205ab47a..a24acef29e 100644 --- a/micrometer-support/pom.xml +++ b/micrometer-support/pom.xml @@ -1,22 +1,15 @@ - + + 4.0.0 - java-operator-sdk io.javaoperatorsdk - 4.9.7-SNAPSHOT + java-operator-sdk + 5.0.0-SNAPSHOT - 4.0.0 micrometer-support Operator SDK - Micrometer Support - - 11 - 11 - - io.micrometer @@ -42,9 +35,9 @@ test - org.awaitility - awaitility - test + org.awaitility + awaitility + test io.javaoperatorsdk @@ -59,4 +52,4 @@ - \ No newline at end of file + diff --git a/micrometer-support/src/main/java/io/javaoperatorsdk/operator/monitoring/micrometer/MicrometerMetrics.java b/micrometer-support/src/main/java/io/javaoperatorsdk/operator/monitoring/micrometer/MicrometerMetrics.java index b819bd0ca3..07106d9b3c 100644 --- a/micrometer-support/src/main/java/io/javaoperatorsdk/operator/monitoring/micrometer/MicrometerMetrics.java +++ b/micrometer-support/src/main/java/io/javaoperatorsdk/operator/monitoring/micrometer/MicrometerMetrics.java @@ -59,20 +59,6 @@ public class MicrometerMetrics implements Metrics { private final Map gauges = new ConcurrentHashMap<>(); private final Cleaner cleaner; - /** - * Creates a default micrometer-based Metrics implementation, collecting metrics on a per resource - * basis and not dealing with cleaning these after these resources are deleted. Note that this - * probably will change in a future release. If you want more control over what the implementation - * actually does, please use the static factory methods instead. - * - * @param registry the {@link MeterRegistry} instance to use for metrics recording - * @deprecated Use the factory methods / builders instead - */ - @Deprecated - public MicrometerMetrics(MeterRegistry registry) { - this(registry, Cleaner.NOOP, true); - } - /** * Creates a MicrometerMetrics instance configured to not collect per-resource metrics, just * aggregates per resource **type** diff --git a/operator-framework-bom/pom.xml b/operator-framework-bom/pom.xml index a52b6d70eb..96a5e01495 100644 --- a/operator-framework-bom/pom.xml +++ b/operator-framework-bom/pom.xml @@ -1,142 +1,170 @@ - - 4.0.0 + + 4.0.0 - io.javaoperatorsdk - operator-framework-bom - 4.9.7-SNAPSHOT - Operator SDK - Bill of Materials - pom - Java SDK for implementing Kubernetes operators - https://github.com/operator-framework/java-operator-sdk + io.javaoperatorsdk + operator-framework-bom + 5.0.0-SNAPSHOT + pom + Operator SDK - Bill of Materials + Java SDK for implementing Kubernetes operators + https://github.com/operator-framework/java-operator-sdk - - - Apache 2 License - https://www.apache.org/licenses/LICENSE-2.0.html - - - - - Attila Meszaros - csviri@gmail.com - - - Christophe Laprun - claprun@redhat.com - - + + + Apache 2 License + https://www.apache.org/licenses/LICENSE-2.0.html + + + + + Attila Meszaros + csviri@gmail.com + + + Christophe Laprun + claprun@redhat.com + + - - scm:git:git://github.com/java-operator-sdk/java-operator-sdk.git - scm:git:git@github.com/java-operator-sdk/java-operator-sdk.git - https://github.com/operator-framework/java-operator-sdk/tree/master - + + scm:git:git://github.com/java-operator-sdk/java-operator-sdk.git + scm:git:git@github.com/java-operator-sdk/java-operator-sdk.git + https://github.com/operator-framework/java-operator-sdk/tree/master + - - - - io.javaoperatorsdk - operator-framework-core - ${project.version} - - - io.javaoperatorsdk - operator-framework - ${project.version} - - - io.javaoperatorsdk - micrometer-support - ${project.version} - - - io.javaoperatorsdk - operator-framework-junit-5 - ${project.version} - - - + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + - - 1.7.0 - 3.2.5 - 3.3.1 - 3.10.0 - + + 1.6.13 + 3.2.4 + 3.3.1 + 3.10.0 + 2.43.0 + - - - release - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${maven-javadoc-plugin.version} - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-source-plugin - ${maven-source-plugin.version} - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-gpg-plugin - ${maven-gpg-plugin.version} - - - sign-artifacts - verify - - sign - - - - --pinentry-mode - loopback - - - - - - - org.sonatype.plugins - nexus-staging-maven-plugin - ${nexus-staging-maven-plugin.version} - true - - ossrh - https://oss.sonatype.org/ - true - - - - - - + + + + io.javaoperatorsdk + operator-framework-core + ${project.version} + + + io.javaoperatorsdk + operator-framework + ${project.version} + + + io.javaoperatorsdk + micrometer-support + ${project.version} + + + io.javaoperatorsdk + operator-framework-junit-5 + ${project.version} + + + - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - + + + + com.diffplug.spotless + spotless-maven-plugin + ${spotless.version} + + + + pom.xml + ./**/pom.xml + + + + + + contributing/eclipse-google-style.xml + + + contributing/eclipse.importorder + + + + + + + + + + + release + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven-javadoc-plugin.version} + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + ${maven-source-plugin.version} + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-gpg-plugin + ${maven-gpg-plugin.version} + + + sign-artifacts + + sign + + verify + + + --pinentry-mode + loopback + + + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + ${nexus-staging-maven-plugin.version} + true + + ossrh + https://oss.sonatype.org/ + true + + + + + + diff --git a/operator-framework-core/pom.xml b/operator-framework-core/pom.xml index f8e3f2ce75..76a6169a3f 100644 --- a/operator-framework-core/pom.xml +++ b/operator-framework-core/pom.xml @@ -1,70 +1,23 @@ - + 4.0.0 io.javaoperatorsdk java-operator-sdk - 4.9.7-SNAPSHOT + 5.0.0-SNAPSHOT ../pom.xml operator-framework-core + jar Operator SDK - Framework - Core Core framework for implementing Kubernetes operators - jar - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - - io.github.git-commit-id - git-commit-id-maven-plugin - ${git-commit-id-maven-plugin.version} - - - get-the-git-infos - - revision - - initialize - - - - true - ${project.build.outputDirectory}/version.properties - - - ^git.build.time$ - ^git.commit.id.(abbrev|full)$ - git.branch - - full - - - - org.codehaus.mojo - templating-maven-plugin - 3.0.0 - - - filtering-java-templates - - filter-sources - - - - - - - + + io.github.java-diff-utils + java-diff-utils + io.fabric8 kubernetes-client @@ -81,7 +34,7 @@ org.apache.logging.log4j - log4j-slf4j-impl + log4j-slf4j2-impl test @@ -127,4 +80,51 @@ test + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + + io.github.git-commit-id + git-commit-id-maven-plugin + ${git-commit-id-maven-plugin.version} + + true + ${project.build.outputDirectory}/version.properties + + ^git.build.time$ + ^git.commit.id.(abbrev|full)$ + git.branch + + full + + + + get-the-git-infos + + revision + + initialize + + + + + org.codehaus.mojo + templating-maven-plugin + 3.0.0 + + + filtering-java-templates + + filter-sources + + + + + + diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/BuilderUtils.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/BuilderUtils.java index 1cb46bafab..8f33036b74 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/BuilderUtils.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/BuilderUtils.java @@ -10,7 +10,7 @@ public final class BuilderUtils { // prevent instantiation of util class private BuilderUtils() {} - public static final B newBuilder(Class builderType, T item) { + public static B newBuilder(Class builderType, T item) { Class builderTargetType = builderTargetType(builderType); try { Constructor constructor = builderType.getDeclaredConstructor(builderTargetType); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ControllerManager.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ControllerManager.java index e90070d3c2..a755e4db7e 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ControllerManager.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ControllerManager.java @@ -89,4 +89,3 @@ synchronized int size() { return controllers.size(); } } - diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/LeaderElectionManager.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/LeaderElectionManager.java index d0af5ee441..d6ee17a383 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/LeaderElectionManager.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/LeaderElectionManager.java @@ -102,11 +102,15 @@ private void startLeading() { } private void stopLeading() { - log.info("Stopped leading for identity: {}. Exiting.", identity); - // When leader stops leading the process ends immediately to prevent multiple reconciliations - // running parallel. - // Note that some reconciliations might run for a very long time. - System.exit(1); + if (configurationService.getLeaderElectionConfiguration().orElseThrow().isExitOnStopLeading()) { + log.info("Stopped leading for identity: {}. Exiting.", identity); + // When leader stops leading the process ends immediately to prevent multiple reconciliations + // running parallel. + // Note that some reconciliations might run for a very long time. + System.exit(1); + } else { + log.info("Stopped leading, configured not to exit"); + } } private String identity(LeaderElectionConfiguration config) { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/Operator.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/Operator.java index 3fc01e1f64..9680bc7e8d 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/Operator.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/Operator.java @@ -35,7 +35,7 @@ public Operator() { } Operator(KubernetesClient kubernetesClient) { - this(kubernetesClient, null); + this(initConfigurationService(kubernetesClient, null)); } /** @@ -63,19 +63,7 @@ public Operator(ConfigurationService configurationService) { * {@link ConfigurationService} values */ public Operator(Consumer overrider) { - this(null, overrider); - } - - /** - * @param client client to use to all Kubernetes related operations - * @param overrider a {@link ConfigurationServiceOverrider} consumer used to override the default - * {@link ConfigurationService} values - * @deprecated Use {@link Operator#Operator(Consumer)} instead, passing your custom client with - * {@link ConfigurationServiceOverrider#withKubernetesClient(KubernetesClient)} - */ - @Deprecated(since = "4.4.0") - public Operator(KubernetesClient client, Consumer overrider) { - this(initConfigurationService(client, overrider)); + this(initConfigurationService(null, overrider)); } private static ConfigurationService initConfigurationService(KubernetesClient client, @@ -98,17 +86,6 @@ private static ConfigurationService initConfigurationService(KubernetesClient cl return ConfigurationService.newOverriddenConfigurationService(overrider); } - /** - * Uses {@link ConfigurationService#getTerminationTimeoutSeconds()} for graceful shutdown timeout - * - * @deprecated use the overloaded version with graceful shutdown timeout parameter. - * - */ - @Deprecated(forRemoval = true) - public void installShutdownHook() { - installShutdownHook(Duration.ofSeconds(configurationService.getTerminationTimeoutSeconds())); - } - /** * Adds a shutdown hook that automatically calls {@link #stop()} when the app shuts down. Note * that graceful shutdown is usually not needed, but some {@link Reconciler} implementations might @@ -120,9 +97,10 @@ public void installShutdownHook() { * @param gracefulShutdownTimeout timeout to wait for executor threads to complete actual * reconciliations */ + @SuppressWarnings("unused") public void installShutdownHook(Duration gracefulShutdownTimeout) { if (!leaderElectionManager.isLeaderElectionEnabled()) { - Runtime.getRuntime().addShutdownHook(new Thread(() -> stop(gracefulShutdownTimeout))); + Runtime.getRuntime().addShutdownHook(new Thread(this::stop)); } else { log.warn("Leader election is on, shutdown hook will not be installed."); } @@ -167,15 +145,18 @@ public synchronized void start() { } } - public void stop(Duration gracefulShutdownTimeout) throws OperatorException { + @Override + public void stop() throws OperatorException { + Duration reconciliationTerminationTimeout = + configurationService.reconciliationTerminationTimeout(); if (!started) { return; } - log.info( - "Operator SDK {} is shutting down...", configurationService.getVersion().getSdkVersion()); + log.info("Operator SDK {} is shutting down...", + configurationService.getVersion().getSdkVersion()); controllerManager.stop(); - configurationService.getExecutorServiceManager().stop(gracefulShutdownTimeout); + configurationService.getExecutorServiceManager().stop(reconciliationTerminationTimeout); leaderElectionManager.stop(); if (configurationService.closeClientOnStop()) { getKubernetesClient().close(); @@ -184,11 +165,6 @@ public void stop(Duration gracefulShutdownTimeout) throws OperatorException { started = false; } - @Override - public void stop() throws OperatorException { - stop(Duration.ZERO); - } - /** * Add a registration requests for the specified reconciler with this operator. The effective * registration of the reconciler is delayed till the operator is started. @@ -237,8 +213,9 @@ public

RegisteredController

register(Reconciler

re controllerManager.add(controller); - final var watchedNS = configuration.watchAllNamespaces() ? "[all namespaces]" - : configuration.getEffectiveNamespaces(); + final var informerConfig = configuration.getInformerConfig(); + final var watchedNS = informerConfig.watchAllNamespaces() ? "[all namespaces]" + : informerConfig.getEffectiveNamespaces(configuration); log.info( "Registered reconciler: '{}' for resource: '{}' for namespace(s): {}", diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ReconcilerUtils.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ReconcilerUtils.java index fec5c4e61e..c2241e4bbb 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ReconcilerUtils.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ReconcilerUtils.java @@ -9,7 +9,6 @@ import java.util.Objects; import java.util.function.Predicate; import java.util.regex.Pattern; -import java.util.stream.Collectors; import io.fabric8.kubernetes.api.builder.Builder; import io.fabric8.kubernetes.api.model.GenericKubernetesResource; @@ -126,8 +125,7 @@ public static boolean specsEqual(HasMetadata r1, HasMetadata r2) { // will be replaced with: https://github.com/fabric8io/kubernetes-client/issues/3816 public static Object getSpec(HasMetadata resource) { // optimize CustomResource case - if (resource instanceof CustomResource) { - CustomResource cr = (CustomResource) resource; + if (resource instanceof CustomResource cr) { return cr.getSpec(); } @@ -142,8 +140,7 @@ public static Object getSpec(HasMetadata resource) { @SuppressWarnings("unchecked") public static Object setSpec(HasMetadata resource, Object spec) { // optimize CustomResource case - if (resource instanceof CustomResource) { - CustomResource cr = (CustomResource) resource; + if (resource instanceof CustomResource cr) { cr.setSpec(spec); return null; } @@ -191,8 +188,7 @@ public static void handleKubernetesClientException(Exception e, String resourceT throw ((MissingCRDException) e); } - if (e instanceof KubernetesClientException) { - KubernetesClientException ke = (KubernetesClientException) e; + if (e instanceof KubernetesClientException ke) { // only throw MissingCRDException if the 404 error occurs on the target CRD if (404 == ke.getCode() && (resourceTypeName.equals(ke.getFullResourceName()) @@ -217,7 +213,7 @@ private static boolean matchesResourceType(String resourceTypeName, group = group.substring(0, group.length() - 1); } final var segments = Arrays.stream(group.split("/")).filter(Predicate.not(String::isEmpty)) - .collect(Collectors.toUnmodifiableList()); + .toList(); if (segments.size() != 3) { return false; } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/RuntimeInfo.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/RuntimeInfo.java index 961e519d62..ee2f4d447e 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/RuntimeInfo.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/RuntimeInfo.java @@ -7,6 +7,7 @@ import io.javaoperatorsdk.operator.health.EventSourceHealthIndicator; import io.javaoperatorsdk.operator.health.InformerWrappingEventSourceHealthIndicator; +import io.javaoperatorsdk.operator.processing.event.source.controller.ControllerEventSource; /** * RuntimeInfo in general is available when operator is fully started. You can use "isStarted" to @@ -64,9 +65,7 @@ public Map> unhealthyEventSource /** * @return Aggregated Map with controller related event sources that wraps an informer. Thus, - * either a - * {@link io.javaoperatorsdk.operator.processing.event.source.controller.ControllerResourceEventSource} - * or an + * either a {@link ControllerEventSource} or an * {@link io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource}. */ public Map> unhealthyInformerWrappingEventSourceHealthIndicator() { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/ObservedGenerationAware.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/ObservedGenerationAware.java deleted file mode 100644 index 069953a32d..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/ObservedGenerationAware.java +++ /dev/null @@ -1,27 +0,0 @@ -package io.javaoperatorsdk.operator.api; - -import io.fabric8.kubernetes.api.model.HasMetadata; -import io.fabric8.kubernetes.client.CustomResource; -import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; - -/** - * If the custom resource's status implements this interface, the observed generation will be - * automatically handled. The last observed generation will be updated on status. - *

- * In order for this automatic handling to work the status object returned by - * {@link CustomResource#getStatus()} should not be null. - *

- * The observed generation is updated even when {@link UpdateControl#noUpdate()} or - * {@link UpdateControl#updateResource(HasMetadata)} is called. Although those results call normally - * does not result in a status update, there will be a subsequent status update Kubernetes API call - * in this case. - * - * @see ObservedGenerationAwareStatus - */ -public interface ObservedGenerationAware { - - void setObservedGeneration(Long generation); - - Long getObservedGeneration(); - -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/ObservedGenerationAwareStatus.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/ObservedGenerationAwareStatus.java deleted file mode 100644 index d2048c9513..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/ObservedGenerationAwareStatus.java +++ /dev/null @@ -1,19 +0,0 @@ -package io.javaoperatorsdk.operator.api; - -/** - * A helper base class for status sub-resources classes to extend to support generate awareness. - */ -public class ObservedGenerationAwareStatus implements ObservedGenerationAware { - - private Long observedGeneration; - - @Override - public void setObservedGeneration(Long generation) { - this.observedGeneration = generation; - } - - @Override - public Long getObservedGeneration() { - return observedGeneration; - } -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/AbstractConfigurationService.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/AbstractConfigurationService.java index 1a54dbafc7..f7ed42c577 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/AbstractConfigurationService.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/AbstractConfigurationService.java @@ -10,6 +10,9 @@ import io.javaoperatorsdk.operator.ReconcilerUtils; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +/** + * An abstract implementation of {@link ConfigurationService} meant to ease custom implementations + */ @SuppressWarnings("rawtypes") public class AbstractConfigurationService implements ConfigurationService { private final Map configurations = new ConcurrentHashMap<>(); @@ -18,11 +21,11 @@ public class AbstractConfigurationService implements ConfigurationService { private Cloner cloner; private ExecutorServiceManager executorServiceManager; - public AbstractConfigurationService(Version version) { + protected AbstractConfigurationService(Version version) { this(version, null); } - public AbstractConfigurationService(Version version, Cloner cloner) { + protected AbstractConfigurationService(Version version, Cloner cloner) { this(version, cloner, null, null); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/BaseConfigurationService.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/BaseConfigurationService.java index d908f52ebe..4204cb6faf 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/BaseConfigurationService.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/BaseConfigurationService.java @@ -7,38 +7,34 @@ import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.function.Function; -import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.client.KubernetesClient; -import io.fabric8.kubernetes.client.informers.cache.ItemStore; -import io.javaoperatorsdk.operator.OperatorException; import io.javaoperatorsdk.operator.ReconcilerUtils; import io.javaoperatorsdk.operator.api.config.Utils.Configurator; +import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceConfigurationResolver; 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.api.reconciler.Constants; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +import io.javaoperatorsdk.operator.api.reconciler.Workflow; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; import io.javaoperatorsdk.operator.processing.dependent.workflow.Condition; import io.javaoperatorsdk.operator.processing.event.rate.RateLimiter; -import io.javaoperatorsdk.operator.processing.event.source.controller.ResourceEventFilter; -import io.javaoperatorsdk.operator.processing.event.source.controller.ResourceEventFilters; -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.Retry; import static io.javaoperatorsdk.operator.api.config.ControllerConfiguration.CONTROLLER_NAME_AS_FIELD_MANAGER; -import static io.javaoperatorsdk.operator.api.reconciler.Constants.DEFAULT_NAMESPACES_SET; public class BaseConfigurationService extends AbstractConfigurationService { private static final String LOGGER_NAME = "Default ConfigurationService implementation"; private static final Logger logger = LoggerFactory.getLogger(LOGGER_NAME); + private static final ResourceClassResolver DEFAULT_RESOLVER = new DefaultResourceClassResolver(); public BaseConfigurationService(Version version) { this(version, null); @@ -56,6 +52,98 @@ public BaseConfigurationService() { this(Utils.VERSION); } + @SuppressWarnings({"unchecked", "rawtypes"}) + private static List dependentResources( + Workflow annotation, + ControllerConfiguration controllerConfiguration) { + final var dependents = annotation.dependents(); + + + if (dependents == null || dependents.length == 0) { + return Collections.emptyList(); + } + + final var specsMap = new LinkedHashMap(dependents.length); + for (Dependent dependent : dependents) { + final Class dependentType = dependent.type(); + + final var dependentName = getName(dependent.name(), dependentType); + var spec = specsMap.get(dependentName); + if (spec != null) { + throw new IllegalArgumentException( + "A DependentResource named '" + dependentName + "' already exists: " + spec); + } + + final var name = controllerConfiguration.getName(); + + var eventSourceName = dependent.useEventSourceWithName(); + eventSourceName = Constants.NO_VALUE_SET.equals(eventSourceName) ? null : eventSourceName; + final var context = Utils.contextFor(name, dependentType, null); + spec = new DependentResourceSpec(dependentType, dependentName, + Set.of(dependent.dependsOn()), + Utils.instantiate(dependent.readyPostcondition(), Condition.class, context), + Utils.instantiate(dependent.reconcilePrecondition(), Condition.class, context), + Utils.instantiate(dependent.deletePostcondition(), Condition.class, context), + Utils.instantiate(dependent.activationCondition(), Condition.class, context), + eventSourceName); + specsMap.put(dependentName, spec); + + // extract potential configuration + DependentResourceConfigurationResolver.configureSpecFromConfigured(spec, + controllerConfiguration, + dependentType); + + specsMap.put(dependentName, spec); + } + + return specsMap.values().stream().toList(); + } + + @SuppressWarnings("unchecked") + private static T valueOrDefaultFromAnnotation( + io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration controllerConfiguration, + Function mapper, + String defaultMethodName) { + try { + if (controllerConfiguration == null) { + return (T) io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration.class + .getDeclaredMethod(defaultMethodName).getDefaultValue(); + } else { + return mapper.apply(controllerConfiguration); + } + } catch (NoSuchMethodException e) { + throw new RuntimeException(e); + } + } + + @SuppressWarnings("rawtypes") + private static String getName(String name, Class dependentType) { + if (name.isBlank()) { + name = DependentResource.defaultNameFor(dependentType); + } + return name; + } + + @SuppressWarnings("unused") + private static Configurator configuratorFor(Class instanceType, + Class> reconcilerClass) { + return instance -> configureFromAnnotatedReconciler(instance, reconcilerClass); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static void configureFromAnnotatedReconciler(Object instance, + Class> reconcilerClass) { + if (instance instanceof AnnotationConfigurable configurable) { + final Class configurationClass = + (Class) Utils.getFirstTypeArgumentFromSuperClassOrInterface( + instance.getClass(), AnnotationConfigurable.class); + final var configAnnotation = reconcilerClass.getAnnotation(configurationClass); + if (configAnnotation != null) { + configurable.initFrom(configAnnotation); + } + } + } + @Override protected void logMissingReconcilerWarning(String reconcilerKey, String reconcilersNameMessage) { logger.warn("Configuration for reconciler '{}' was not found. {}", reconcilerKey, @@ -95,39 +183,84 @@ public ControllerConfiguration getConfigurationFor( return config; } + /** + * Override if a different class resolution is needed + * + * @return the custom {@link ResourceClassResolver} implementation to use + */ + protected ResourceClassResolver getResourceClassResolver() { + return DEFAULT_RESOLVER; + } + @SuppressWarnings({"unchecked", "rawtypes"}) protected

ControllerConfiguration

configFor(Reconciler

reconciler) { - final var annotation = reconciler.getClass().getAnnotation( + final Class> reconcilerClass = + (Class>) reconciler.getClass(); + final var controllerAnnotation = reconcilerClass.getAnnotation( io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration.class); - if (annotation == null) { - throw new OperatorException( - "Missing mandatory @" - + io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration.class - .getSimpleName() - + - " annotation for reconciler: " + reconciler); + + ResolvedControllerConfiguration

config = + controllerConfiguration(reconcilerClass, controllerAnnotation); + + final var workflowAnnotation = reconcilerClass.getAnnotation( + io.javaoperatorsdk.operator.api.reconciler.Workflow.class); + if (workflowAnnotation != null) { + final var specs = dependentResources(workflowAnnotation, config); + WorkflowSpec workflowSpec = new WorkflowSpec() { + @Override + public List getDependentResourceSpecs() { + return specs; + } + + @Override + public boolean isExplicitInvocation() { + return workflowAnnotation.explicitInvocation(); + } + + @Override + public boolean handleExceptionsInReconciler() { + return workflowAnnotation.handleExceptionsInReconciler(); + } + + }; + config.setWorkflowSpec(workflowSpec); } - Class> reconcilerClass = (Class>) reconciler.getClass(); - final var resourceClass = getResourceClassResolver().getResourceClass(reconcilerClass); - final var name = ReconcilerUtils.getNameFor(reconciler); - final var generationAware = valueOrDefault( + return config; + } + + @SuppressWarnings({"unchecked"}) + private

ResolvedControllerConfiguration

controllerConfiguration( + Class> reconcilerClass, + io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration annotation) { + final var resourceClass = getResourceClassResolver().getPrimaryResourceClass(reconcilerClass); + + final var name = ReconcilerUtils.getNameFor(reconcilerClass); + final var generationAware = valueOrDefaultFromAnnotation( annotation, io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration::generationAwareEventProcessing, - true); + "generationAwareEventProcessing"); final var associatedReconcilerClass = - ResolvedControllerConfiguration.getAssociatedReconcilerClassName(reconciler.getClass()); + ResolvedControllerConfiguration.getAssociatedReconcilerClassName(reconcilerClass); final var context = Utils.contextFor(name); - final Class retryClass = annotation.retry(); + final Class retryClass = + valueOrDefaultFromAnnotation(annotation, + io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration::retry, + "retry"); final var retry = Utils.instantiateAndConfigureIfNeeded(retryClass, Retry.class, - context, configuratorFor(Retry.class, reconciler)); + context, configuratorFor(Retry.class, reconcilerClass)); - final Class rateLimiterClass = annotation.rateLimiter(); + @SuppressWarnings("rawtypes") + final Class rateLimiterClass = valueOrDefaultFromAnnotation(annotation, + io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration::rateLimiter, + "rateLimiter"); final var rateLimiter = Utils.instantiateAndConfigureIfNeeded(rateLimiterClass, - RateLimiter.class, context, configuratorFor(RateLimiter.class, reconciler)); + RateLimiter.class, context, configuratorFor(RateLimiter.class, reconcilerClass)); - final var reconciliationInterval = annotation.maxReconciliationInterval(); + final var reconciliationInterval = valueOrDefaultFromAnnotation(annotation, + io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration::maxReconciliationInterval, + "maxReconciliationInterval"); long interval = -1; TimeUnit timeUnit = null; if (reconciliationInterval != null && reconciliationInterval.interval() > 0) { @@ -135,107 +268,29 @@ protected

ControllerConfiguration

configFor(Reconcile timeUnit = reconciliationInterval.timeUnit(); } + var fieldManager = valueOrDefaultFromAnnotation(annotation, + io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration::fieldManager, + "fieldManager"); final var dependentFieldManager = - annotation.fieldManager().equals(CONTROLLER_NAME_AS_FIELD_MANAGER) ? name - : annotation.fieldManager(); + fieldManager.equals(CONTROLLER_NAME_AS_FIELD_MANAGER) ? name + : fieldManager; - final var informerListLimit = - annotation.informerListLimit() == Constants.NO_LONG_VALUE_SET ? null - : annotation.informerListLimit(); + InformerConfiguration

informerConfig = InformerConfiguration.builder(resourceClass) + .initFromAnnotation(annotation != null ? annotation.informer() : null, context) + .buildForController(); - final var config = new ResolvedControllerConfiguration

( - resourceClass, name, generationAware, + return new ResolvedControllerConfiguration

( + name, generationAware, associatedReconcilerClass, retry, rateLimiter, ResolvedControllerConfiguration.getMaxReconciliationInterval(interval, timeUnit), - Utils.instantiate(annotation.onAddFilter(), OnAddFilter.class, context), - Utils.instantiate(annotation.onUpdateFilter(), OnUpdateFilter.class, context), - Utils.instantiate(annotation.genericFilter(), GenericFilter.class, context), - Set.of(valueOrDefault(annotation, - io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration::namespaces, - DEFAULT_NAMESPACES_SET.toArray(String[]::new))), - valueOrDefault(annotation, + valueOrDefaultFromAnnotation(annotation, io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration::finalizerName, - Constants.NO_VALUE_SET), - valueOrDefault(annotation, - io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration::labelSelector, - Constants.NO_VALUE_SET), + "finalizerName"), null, - Utils.instantiate(annotation.itemStore(), ItemStore.class, context), dependentFieldManager, - this, informerListLimit); - - ResourceEventFilter

answer = deprecatedEventFilter(annotation); - config.setEventFilter(answer != null ? answer : ResourceEventFilters.passthrough()); - - List specs = dependentResources(annotation, config); - config.setDependentResources(specs); - - return config; + dependentFieldManager, + this, informerConfig); } - @SuppressWarnings("unchecked") - private static

ResourceEventFilter

deprecatedEventFilter( - io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration annotation) { - ResourceEventFilter

answer = null; - - Class>[] filterTypes = - (Class>[]) valueOrDefault(annotation, - io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration::eventFilters, - new Object[] {}); - for (var filterType : filterTypes) { - try { - ResourceEventFilter

filter = filterType.getConstructor().newInstance(); - - if (answer == null) { - answer = filter; - } else { - answer = answer.and(filter); - } - } catch (Exception e) { - throw new IllegalArgumentException(e); - } - } - return answer; - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - private static List dependentResources( - io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration annotation, - ControllerConfiguration parent) { - final var dependents = - valueOrDefault(annotation, - io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration::dependents, - new Dependent[] {}); - if (dependents.length == 0) { - return Collections.emptyList(); - } - - final var specsMap = new LinkedHashMap(dependents.length); - for (Dependent dependent : dependents) { - final Class dependentType = dependent.type(); - - final var dependentName = getName(dependent.name(), dependentType); - var spec = specsMap.get(dependentName); - if (spec != null) { - throw new IllegalArgumentException( - "A DependentResource named '" + dependentName + "' already exists: " + spec); - } - - final var name = parent.getName(); - - var eventSourceName = dependent.useEventSourceWithName(); - eventSourceName = Constants.NO_VALUE_SET.equals(eventSourceName) ? null : eventSourceName; - final var context = Utils.contextFor(name, dependentType, null); - spec = new DependentResourceSpec(dependentType, dependentName, - Set.of(dependent.dependsOn()), - Utils.instantiate(dependent.readyPostcondition(), Condition.class, context), - Utils.instantiate(dependent.reconcilePrecondition(), Condition.class, context), - Utils.instantiate(dependent.deletePostcondition(), Condition.class, context), - Utils.instantiate(dependent.activationCondition(), Condition.class, context), - eventSourceName); - specsMap.put(dependentName, spec); - } - return specsMap.values().stream().collect(Collectors.toUnmodifiableList()); - } protected boolean createIfNeeded() { return true; @@ -245,43 +300,4 @@ protected boolean createIfNeeded() { public boolean checkCRDAndValidateLocalModel() { return Utils.shouldCheckCRDAndValidateLocalModel(); } - - private static T valueOrDefault( - io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration controllerConfiguration, - Function mapper, - T defaultValue) { - if (controllerConfiguration == null) { - return defaultValue; - } else { - return mapper.apply(controllerConfiguration); - } - } - - @SuppressWarnings("rawtypes") - private static String getName(String name, Class dependentType) { - if (name.isBlank()) { - name = DependentResource.defaultNameFor(dependentType); - } - return name; - } - - @SuppressWarnings("unused") - private static Configurator configuratorFor(Class instanceType, - Reconciler reconciler) { - return instance -> configureFromAnnotatedReconciler(instance, reconciler); - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - private static void configureFromAnnotatedReconciler(Object instance, Reconciler reconciler) { - if (instance instanceof AnnotationConfigurable) { - AnnotationConfigurable configurable = (AnnotationConfigurable) instance; - final Class configurationClass = - (Class) Utils.getFirstTypeArgumentFromSuperClassOrInterface( - instance.getClass(), AnnotationConfigurable.class); - final var configAnnotation = reconciler.getClass().getAnnotation(configurationClass); - if (configAnnotation != null) { - configurable.initFrom(configAnnotation); - } - } - } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java index 111ef03b1b..14a13bf0b6 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationService.java @@ -20,6 +20,7 @@ import io.fabric8.kubernetes.client.KubernetesClientBuilder; import io.fabric8.kubernetes.client.utils.KubernetesSerialization; import io.javaoperatorsdk.operator.api.monitoring.Metrics; +import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResourceFactory; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; @@ -27,6 +28,7 @@ import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResourceConfig; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.ResourceUpdaterMatcher; import io.javaoperatorsdk.operator.processing.dependent.workflow.ManagedWorkflowFactory; +import io.javaoperatorsdk.operator.processing.event.source.controller.ControllerEventSource; /** An interface from which to retrieve configuration information. */ public interface ConfigurationService { @@ -34,18 +36,79 @@ public interface ConfigurationService { Logger log = LoggerFactory.getLogger(ConfigurationService.class); int DEFAULT_MAX_CONCURRENT_REQUEST = 512; + /** + * The default numbers of concurrent reconciliations + */ + int DEFAULT_RECONCILIATION_THREADS_NUMBER = 50; + /** + * The default number of threads used to process dependent workflows + */ + int DEFAULT_WORKFLOW_EXECUTOR_THREAD_NUMBER = DEFAULT_RECONCILIATION_THREADS_NUMBER; + + /** + * Creates a new {@link ConfigurationService} instance used to configure an + * {@link io.javaoperatorsdk.operator.Operator} instance, starting from the specified base + * configuration and overriding specific aspects according to the provided + * {@link ConfigurationServiceOverrider} instance. + * + *

+ * NOTE: This overriding mechanism should only be used before creating + * your Operator instance as the configuration service is set at creation time and cannot be + * subsequently changed. As a result, overriding values this way after the Operator has been + * configured will not take effect. + *

+ * + * @param baseConfiguration the {@link ConfigurationService} to start from + * @param overrider the {@link ConfigurationServiceOverrider} used to change the values provided + * by the base configuration + * @return a new {@link ConfigurationService} starting from the configuration provided as base but + * with overridden values. + */ + static ConfigurationService newOverriddenConfigurationService( + ConfigurationService baseConfiguration, + Consumer overrider) { + if (overrider != null) { + final var toOverride = new ConfigurationServiceOverrider(baseConfiguration); + overrider.accept(toOverride); + return toOverride.build(); + } + return baseConfiguration; + } + + /** + * Creates a new {@link ConfigurationService} instance used to configure an + * {@link io.javaoperatorsdk.operator.Operator} instance, starting from the default configuration + * and overriding specific aspects according to the provided {@link ConfigurationServiceOverrider} + * instance. + * + *

+ * NOTE: This overriding mechanism should only be used before creating + * your Operator instance as the configuration service is set at creation time and cannot be + * subsequently changed. As a result, overriding values this way after the Operator has been + * configured will not take effect. + *

+ * + * @param overrider the {@link ConfigurationServiceOverrider} used to change the values provided + * by the default configuration + * @return a new {@link ConfigurationService} overriding the default values with the ones provided + * by the specified {@link ConfigurationServiceOverrider} + * @since 4.4.0 + */ + static ConfigurationService newOverriddenConfigurationService( + Consumer overrider) { + return newOverriddenConfigurationService(new BaseConfigurationService(), overrider); + } /** * Retrieves the configuration associated with the specified reconciler * * @param reconciler the reconciler we want the configuration of * @param the {@code CustomResource} type associated with the specified reconciler - * @return the {@link ControllerConfiguration} associated with the specified reconciler or {@code - * null} if no configuration exists for the reconciler + * @return the {@link ControllerConfiguration} associated with the specified reconciler or + * {@code null} if no configuration exists for the reconciler */ ControllerConfiguration getConfigurationFor(Reconciler reconciler); - /** * Used to clone custom resources. * @@ -129,13 +192,6 @@ default boolean checkCRDAndValidateLocalModel() { return false; } - int DEFAULT_RECONCILIATION_THREADS_NUMBER = 50; - /** - * @deprecated Not used anymore in the default implementation - */ - @Deprecated(forRemoval = true) - int MIN_DEFAULT_RECONCILIATION_THREADS_NUMBER = 10; - /** * The number of threads the operator can spin out to dispatch reconciliation requests to * reconcilers with the default executors @@ -146,24 +202,6 @@ default int concurrentReconciliationThreads() { return DEFAULT_RECONCILIATION_THREADS_NUMBER; } - /** - * The minimum number of threads the operator starts in the thread pool for reconciliations. - * - * @deprecated not used anymore by default executor implementation - * @return the minimum number of concurrent reconciliation threads - */ - @Deprecated(forRemoval = true) - default int minConcurrentReconciliationThreads() { - return MIN_DEFAULT_RECONCILIATION_THREADS_NUMBER; - } - - int DEFAULT_WORKFLOW_EXECUTOR_THREAD_NUMBER = DEFAULT_RECONCILIATION_THREADS_NUMBER; - /** - * @deprecated Not used anymore in the default implementation - */ - @Deprecated(forRemoval = true) - int MIN_DEFAULT_WORKFLOW_EXECUTOR_THREAD_NUMBER = MIN_DEFAULT_RECONCILIATION_THREADS_NUMBER; - /** * Number of threads the operator can spin out to be used in the workflows with the default * executor. @@ -175,53 +213,63 @@ default int concurrentWorkflowExecutorThreads() { } /** - * The minimum number of threads the operator starts in the thread pool for workflows. + * Override to provide a custom {@link Metrics} implementation * - * @deprecated not used anymore by default executor implementation - * @return the minimum number of concurrent workflow threads + * @return the {@link Metrics} implementation */ - @Deprecated(forRemoval = true) - default int minConcurrentWorkflowExecutorThreads() { - return MIN_DEFAULT_WORKFLOW_EXECUTOR_THREAD_NUMBER; + default Metrics getMetrics() { + return Metrics.NOOP; } - int DEFAULT_TERMINATION_TIMEOUT_SECONDS = 10; - /** - * Retrieves the number of seconds the SDK waits for reconciliation threads to terminate before - * shutting down. - * - * @deprecated use {@link io.javaoperatorsdk.operator.Operator#stop(Duration)} instead. Where the - * parameter can be passed to specify graceful timeout. + * Override to provide a custom {@link ExecutorService} implementation to change how threads + * handle concurrent reconciliations * - * @return the number of seconds to wait before terminating reconciliation threads + * @return the {@link ExecutorService} implementation to use for concurrent reconciliation + * processing */ - @Deprecated(forRemoval = true) - default int getTerminationTimeoutSeconds() { - return DEFAULT_TERMINATION_TIMEOUT_SECONDS; - } - - default Metrics getMetrics() { - return Metrics.NOOP; - } - default ExecutorService getExecutorService() { return Executors.newFixedThreadPool(concurrentReconciliationThreads()); } + /** + * Override to provide a custom {@link ExecutorService} implementation to change how dependent + * workflows are processed in parallel + * + * @return the {@link ExecutorService} implementation to use for dependent workflow processing + */ default ExecutorService getWorkflowExecutorService() { return Executors.newFixedThreadPool(concurrentWorkflowExecutorThreads()); } + /** + * Determines whether the associated Kubernetes client should be closed when the associated + * {@link io.javaoperatorsdk.operator.Operator} is stopped. + * + * @return {@code true} if the Kubernetes should be closed on stop, {@code false} otherwise + */ default boolean closeClientOnStop() { return true; } + /** + * Override to provide a custom {@link DependentResourceFactory} implementation to change how + * {@link io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource} are instantiated + * + * @return the custom {@link DependentResourceFactory} implementation + */ @SuppressWarnings("rawtypes") default DependentResourceFactory dependentResourceFactory() { return DependentResourceFactory.DEFAULT; } + /** + * Retrieves the optional {@link LeaderElectionConfiguration} to specify how the associated + * {@link io.javaoperatorsdk.operator.Operator} handles leader election to ensure only one + * instance of the operator runs on the cluster at any given time + * + * @return the {@link LeaderElectionConfiguration} + */ default Optional getLeaderElectionConfiguration() { return Optional.empty(); } @@ -230,8 +278,7 @@ default Optional getLeaderElectionConfiguration() { *

* if true, operator stops if there are some issues with informers * {@link io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource} or - * {@link io.javaoperatorsdk.operator.processing.event.source.controller.ControllerResourceEventSource} - * on startup. Other event sources may also respect this flag. + * {@link ControllerEventSource} on startup. Other event sources may also respect this flag. *

*

* if false, the startup will ignore recoverable errors, caused for example by RBAC issues, and @@ -255,6 +302,17 @@ default Duration cacheSyncTimeout() { return Duration.ofMinutes(2); } + /** + * This is the timeout value that allows the reconciliation threads to gracefully shut down. If no + * value is set, the default is immediate shutdown. + * + * @return The duration of time to wait before terminating the reconciliation threads + * @since 5.0.0 + */ + default Duration reconciliationTerminationTimeout() { + return Duration.ZERO; + } + /** * Handler for an informer stop. Informer stops if there is a non-recoverable error. Like received * a resource that cannot be deserialized. @@ -278,69 +336,23 @@ default Optional getInformerStoppedHandler() { }); } - @SuppressWarnings("rawtypes") - default ManagedWorkflowFactory getWorkflowFactory() { - return ManagedWorkflowFactory.DEFAULT; - } - - default ResourceClassResolver getResourceClassResolver() { - return new DefaultResourceClassResolver(); - } - /** - * Creates a new {@link ConfigurationService} instance used to configure an - * {@link io.javaoperatorsdk.operator.Operator} instance, starting from the specified base - * configuration and overriding specific aspects according to the provided - * {@link ConfigurationServiceOverrider} instance. + * Override to provide a custom {@link ManagedWorkflowFactory} implementation to change how + * {@link io.javaoperatorsdk.operator.processing.dependent.workflow.ManagedWorkflow} are + * instantiated * - *

- * NOTE: This overriding mechanism should only be used before creating - * your Operator instance as the configuration service is set at creation time and cannot be - * subsequently changed. As a result, overriding values this way after the Operator has been - * configured will not take effect. - *

- * - * @param baseConfiguration the {@link ConfigurationService} to start from - * @param overrider the {@link ConfigurationServiceOverrider} used to change the values provided - * by the base configuration - * @return a new {@link ConfigurationService} starting from the configuration provided as base but - * with overridden values. + * @return the custom {@link ManagedWorkflowFactory} implementation */ - static ConfigurationService newOverriddenConfigurationService( - ConfigurationService baseConfiguration, - Consumer overrider) { - if (overrider != null) { - final var toOverride = new ConfigurationServiceOverrider(baseConfiguration); - overrider.accept(toOverride); - return toOverride.build(); - } - return baseConfiguration; + @SuppressWarnings("rawtypes") + default ManagedWorkflowFactory getWorkflowFactory() { + return ManagedWorkflowFactory.DEFAULT; } /** - * Creates a new {@link ConfigurationService} instance used to configure an - * {@link io.javaoperatorsdk.operator.Operator} instance, starting from the default configuration - * and overriding specific aspects according to the provided {@link ConfigurationServiceOverrider} - * instance. + * Override to provide a custom {@link ExecutorServiceManager} implementation * - *

- * NOTE: This overriding mechanism should only be used before creating - * your Operator instance as the configuration service is set at creation time and cannot be - * subsequently changed. As a result, overriding values this way after the Operator has been - * configured will not take effect. - *

- * - * @param overrider the {@link ConfigurationServiceOverrider} used to change the values provided - * by the default configuration - * @return a new {@link ConfigurationService} overriding the default values with the ones provided - * by the specified {@link ConfigurationServiceOverrider} - * @since 4.4.0 + * @return the custom {@link ExecutorServiceManager} implementation */ - static ConfigurationService newOverriddenConfigurationService( - Consumer overrider) { - return newOverriddenConfigurationService(new BaseConfigurationService(), overrider); - } - default ExecutorServiceManager getExecutorServiceManager() { return new ExecutorServiceManager(this); } @@ -355,6 +367,7 @@ default ExecutorServiceManager getExecutorServiceManager() { * SSA based create/update can be still used with the legacy matching, just overriding the match * method of Kubernetes Dependent Resource. * + * @return {@code true} if SSA should be used for dependent resources, {@code false} otherwise * @since 4.4.0 */ default boolean ssaBasedCreateUpdateMatchForDependentResources() { @@ -397,7 +410,7 @@ default boolean shouldUseSSA(Class depend return false; } Boolean useSSAConfig = Optional.ofNullable(config) - .flatMap(KubernetesDependentResourceConfig::useSSA) + .map(KubernetesDependentResourceConfig::useSSA) .orElse(null); // don't use SSA for certain resources by default, only if explicitly overridden if (useSSAConfig == null) { @@ -440,7 +453,10 @@ default Set> defaultNonSSAResource() { *

* Disable this if you want to react to your own dependent resource updates * + * @return if special annotation should be used for dependent resource to filter events * @since 4.5.0 + * + * @return if special annotation should be used for dependent resource to filter events */ default boolean previousAnnotationForDependentResourcesEventFiltering() { return true; @@ -452,13 +468,52 @@ default boolean previousAnnotationForDependentResourcesEventFiltering() { *

* Disabled by default as Kubernetes does not support, and discourages, this interpretation of * resourceVersions. Enable only if your api server event processing seems to lag the operator - * logic and you want to further minimize the amount of work done / updates issued by the + * logic, and you want to further minimize the amount of work done / updates issued by the * operator. * + * @return if resource version should be parsed (as integer) * @since 4.5.0 + * + * @return if resource version should be parsed (as integer) */ default boolean parseResourceVersionsForEventFilteringAndCaching() { return false; } + /** + * {@link io.javaoperatorsdk.operator.api.reconciler.UpdateControl} patch resource or status can + * either use simple patches or SSA. Setting this to {@code true}, controllers will use SSA for + * adding finalizers, patching resources and status. + * + * @return {@code true} if Server-Side Apply (SSA) should be used when patching the primary + * resources, {@code false} otherwise + * @see ConfigurationServiceOverrider#withUseSSAToPatchPrimaryResource(boolean) + * @since 5.0.0 + */ + default boolean useSSAToPatchPrimaryResource() { + return true; + } + + /** + *

+ * Determines whether resources retrieved from caches such as via calls to + * {@link Context#getSecondaryResource(Class)} should be defensively cloned first. + *

+ * + *

+ * Defensive cloning to prevent problematic cache modifications (modifying the resource would + * otherwise modify the stored copy in the cache) was transparently done in previous JOSDK + * versions. This might have performance consequences and, with the more prevalent use of + * Server-Side Apply, where you should create a new copy of your resource with only modified + * fields, such modifications of these resources are less likely to occur. + *

+ * + * @return {@code true} if resources should be defensively cloned before returning them from + * caches, {@code false} otherwise + * @since 5.0.0 + */ + default boolean cloneSecondaryResourcesWhenGettingFromCache() { + return false; + } + } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java index 4996035943..7de9bcda43 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverrider.java @@ -4,7 +4,7 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutorService; -import java.util.function.Consumer; +import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -15,7 +15,7 @@ import io.javaoperatorsdk.operator.api.monitoring.Metrics; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResourceFactory; -@SuppressWarnings("unused") +@SuppressWarnings({"unused", "UnusedReturnValue"}) public class ConfigurationServiceOverrider { private static final Logger log = LoggerFactory.getLogger(ConfigurationServiceOverrider.class); @@ -23,11 +23,8 @@ public class ConfigurationServiceOverrider { private Metrics metrics; private Boolean checkCR; private Integer concurrentReconciliationThreads; - private Integer minConcurrentReconciliationThreads; private Integer concurrentWorkflowExecutorThreads; - private Integer minConcurrentWorkflowExecutorThreads; private Cloner cloner; - private Integer timeoutSeconds; private Boolean closeClientOnStop; private KubernetesClient client; private ExecutorService executorService; @@ -36,11 +33,13 @@ public class ConfigurationServiceOverrider { private InformerStoppedHandler informerStoppedHandler; private Boolean stopOnInformerErrorDuringStartup; private Duration cacheSyncTimeout; - private ResourceClassResolver resourceClassResolver; + private Duration reconciliationTerminationTimeout; private Boolean ssaBasedCreateUpdateMatchForDependentResources; private Set> defaultNonSSAResource; private Boolean previousAnnotationForDependentResources; private Boolean parseResourceVersions; + private Boolean useSSAToPatchPrimaryResource; + private Boolean cloneSecondaryResourcesWhenGettingFromCache; @SuppressWarnings("rawtypes") private DependentResourceFactory dependentResourceFactory; @@ -63,24 +62,6 @@ public ConfigurationServiceOverrider withConcurrentWorkflowExecutorThreads(int t return this; } - private int minimumMaxValueFor(Integer minValue) { - return minValue != null ? (minValue < 0 ? 0 : minValue) + 1 : 1; - } - - public ConfigurationServiceOverrider withMinConcurrentReconciliationThreads(int threadNumber) { - this.minConcurrentReconciliationThreads = Utils.ensureValid(threadNumber, - "minimum reconciliation threads", ExecutorServiceManager.MIN_THREAD_NUMBER, - original.minConcurrentReconciliationThreads()); - return this; - } - - public ConfigurationServiceOverrider withMinConcurrentWorkflowExecutorThreads(int threadNumber) { - this.minConcurrentWorkflowExecutorThreads = Utils.ensureValid(threadNumber, - "minimum workflow execution threads", ExecutorServiceManager.MIN_THREAD_NUMBER, - original.minConcurrentWorkflowExecutorThreads()); - return this; - } - @SuppressWarnings("rawtypes") public ConfigurationServiceOverrider withDependentResourceFactory( DependentResourceFactory dependentResourceFactory) { @@ -93,11 +74,6 @@ public ConfigurationServiceOverrider withResourceCloner(Cloner cloner) { return this; } - public ConfigurationServiceOverrider withTerminationTimeoutSeconds(int timeoutSeconds) { - this.timeoutSeconds = timeoutSeconds; - return this; - } - public ConfigurationServiceOverrider withMetrics(Metrics metrics) { this.metrics = metrics; return this; @@ -157,9 +133,9 @@ public ConfigurationServiceOverrider withCacheSyncTimeout(Duration cacheSyncTime return this; } - public ConfigurationServiceOverrider withResourceClassResolver( - ResourceClassResolver resourceClassResolver) { - this.resourceClassResolver = resourceClassResolver; + public ConfigurationServiceOverrider withReconciliationTerminationTimeout( + Duration reconciliationTerminationTimeout) { + this.reconciliationTerminationTimeout = reconciliationTerminationTimeout; return this; } @@ -203,6 +179,17 @@ public ConfigurationServiceOverrider wihtParseResourceVersions( return this; } + public ConfigurationServiceOverrider withUseSSAToPatchPrimaryResource(boolean value) { + this.useSSAToPatchPrimaryResource = value; + return this; + } + + public ConfigurationServiceOverrider withCloneSecondaryResourcesWhenGettingFromCache( + boolean value) { + this.cloneSecondaryResourcesWhenGettingFromCache = value; + return this; + } + public ConfigurationService build() { return new BaseConfigurationService(original.getVersion(), cloner, client) { @Override @@ -210,83 +197,63 @@ public Set getKnownReconcilerNames() { return original.getKnownReconcilerNames(); } + private T overriddenValueOrDefault(T value, + Function defaultValue) { + return value != null ? value : defaultValue.apply(original); + } + @Override public boolean checkCRDAndValidateLocalModel() { - return checkCR != null ? checkCR : original.checkCRDAndValidateLocalModel(); + return overriddenValueOrDefault(checkCR, + ConfigurationService::checkCRDAndValidateLocalModel); } @SuppressWarnings("rawtypes") @Override public DependentResourceFactory dependentResourceFactory() { - return dependentResourceFactory != null ? dependentResourceFactory - : DependentResourceFactory.DEFAULT; + return overriddenValueOrDefault(dependentResourceFactory, + ConfigurationService::dependentResourceFactory); } @Override public int concurrentReconciliationThreads() { return Utils.ensureValid( - concurrentReconciliationThreads != null ? concurrentReconciliationThreads - : original.concurrentReconciliationThreads(), + overriddenValueOrDefault(concurrentReconciliationThreads, + ConfigurationService::concurrentReconciliationThreads), "maximum reconciliation threads", - minimumMaxValueFor(minConcurrentReconciliationThreads), + 1, original.concurrentReconciliationThreads()); } @Override public int concurrentWorkflowExecutorThreads() { return Utils.ensureValid( - concurrentWorkflowExecutorThreads != null ? concurrentWorkflowExecutorThreads - : original.concurrentWorkflowExecutorThreads(), + overriddenValueOrDefault(concurrentWorkflowExecutorThreads, + ConfigurationService::concurrentWorkflowExecutorThreads), "maximum workflow execution threads", - minimumMaxValueFor(minConcurrentWorkflowExecutorThreads), + 1, original.concurrentWorkflowExecutorThreads()); } - /** - * @deprecated Not used anymore in the default implementation - */ - @Deprecated(forRemoval = true) - @Override - public int minConcurrentReconciliationThreads() { - return minConcurrentReconciliationThreads != null ? minConcurrentReconciliationThreads - : original.minConcurrentReconciliationThreads(); - } - - /** - * @deprecated Not used anymore in the default implementation - */ - @Override - @Deprecated(forRemoval = true) - public int minConcurrentWorkflowExecutorThreads() { - return minConcurrentWorkflowExecutorThreads != null ? minConcurrentWorkflowExecutorThreads - : original.minConcurrentWorkflowExecutorThreads(); - } - - @Override - public int getTerminationTimeoutSeconds() { - return timeoutSeconds != null ? timeoutSeconds : original.getTerminationTimeoutSeconds(); - } - @Override public Metrics getMetrics() { - return metrics != null ? metrics : original.getMetrics(); + return overriddenValueOrDefault(metrics, ConfigurationService::getMetrics); } @Override public boolean closeClientOnStop() { - return closeClientOnStop != null ? closeClientOnStop : original.closeClientOnStop(); + return overriddenValueOrDefault(closeClientOnStop, ConfigurationService::closeClientOnStop); } @Override public ExecutorService getExecutorService() { - return executorService != null ? executorService - : super.getExecutorService(); + return overriddenValueOrDefault(executorService, ConfigurationService::getExecutorService); } @Override public ExecutorService getWorkflowExecutorService() { - return workflowExecutorService != null ? workflowExecutorService - : super.getWorkflowExecutorService(); + return overriddenValueOrDefault(workflowExecutorService, + ConfigurationService::getWorkflowExecutorService); } @Override @@ -303,59 +270,57 @@ public Optional getInformerStoppedHandler() { @Override public boolean stopOnInformerErrorDuringStartup() { - return stopOnInformerErrorDuringStartup != null ? stopOnInformerErrorDuringStartup - : super.stopOnInformerErrorDuringStartup(); + return overriddenValueOrDefault(stopOnInformerErrorDuringStartup, + ConfigurationService::stopOnInformerErrorDuringStartup); } @Override public Duration cacheSyncTimeout() { - return cacheSyncTimeout != null ? cacheSyncTimeout : super.cacheSyncTimeout(); + return overriddenValueOrDefault(cacheSyncTimeout, ConfigurationService::cacheSyncTimeout); } @Override - public ResourceClassResolver getResourceClassResolver() { - return resourceClassResolver != null ? resourceClassResolver - : super.getResourceClassResolver(); + public Duration reconciliationTerminationTimeout() { + return overriddenValueOrDefault(reconciliationTerminationTimeout, + ConfigurationService::reconciliationTerminationTimeout); } @Override public boolean ssaBasedCreateUpdateMatchForDependentResources() { - return ssaBasedCreateUpdateMatchForDependentResources != null - ? ssaBasedCreateUpdateMatchForDependentResources - : super.ssaBasedCreateUpdateMatchForDependentResources(); + return overriddenValueOrDefault(ssaBasedCreateUpdateMatchForDependentResources, + ConfigurationService::ssaBasedCreateUpdateMatchForDependentResources); } @Override public Set> defaultNonSSAResources() { - return defaultNonSSAResource != null ? defaultNonSSAResource - : super.defaultNonSSAResources(); + return overriddenValueOrDefault(defaultNonSSAResource, + ConfigurationService::defaultNonSSAResources); } @Override public boolean previousAnnotationForDependentResourcesEventFiltering() { - return previousAnnotationForDependentResources != null - ? previousAnnotationForDependentResources - : super.previousAnnotationForDependentResourcesEventFiltering(); + return overriddenValueOrDefault(previousAnnotationForDependentResources, + ConfigurationService::previousAnnotationForDependentResourcesEventFiltering); } @Override public boolean parseResourceVersionsForEventFilteringAndCaching() { - return parseResourceVersions != null - ? parseResourceVersions - : super.parseResourceVersionsForEventFilteringAndCaching(); + return overriddenValueOrDefault(parseResourceVersions, + ConfigurationService::parseResourceVersionsForEventFilteringAndCaching); + } + + @Override + public boolean useSSAToPatchPrimaryResource() { + return overriddenValueOrDefault(useSSAToPatchPrimaryResource, + ConfigurationService::useSSAToPatchPrimaryResource); + } + + @Override + public boolean cloneSecondaryResourcesWhenGettingFromCache() { + return overriddenValueOrDefault(cloneSecondaryResourcesWhenGettingFromCache, + ConfigurationService::cloneSecondaryResourcesWhenGettingFromCache); } }; } - /** - * @deprecated Use - * {@link ConfigurationService#newOverriddenConfigurationService(ConfigurationService, Consumer)} - * instead - * @param original that will be overridden - * @return current overrider - */ - @Deprecated(since = "2.2.0") - public static ConfigurationServiceOverrider override(ConfigurationService original) { - return new ConfigurationServiceOverrider(original); - } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ControllerConfiguration.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ControllerConfiguration.java index 13ddd995ad..e03cf5626e 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ControllerConfiguration.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ControllerConfiguration.java @@ -1,24 +1,20 @@ package io.javaoperatorsdk.operator.api.config; import java.time.Duration; -import java.util.Collections; -import java.util.List; import java.util.Optional; import java.util.Set; import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.ReconcilerUtils; import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceSpec; +import io.javaoperatorsdk.operator.api.config.workflow.WorkflowSpec; import io.javaoperatorsdk.operator.api.reconciler.MaxReconciliationInterval; import io.javaoperatorsdk.operator.processing.event.rate.LinearRateLimiter; import io.javaoperatorsdk.operator.processing.event.rate.RateLimiter; -import io.javaoperatorsdk.operator.processing.event.source.controller.ResourceEventFilter; -import io.javaoperatorsdk.operator.processing.event.source.controller.ResourceEventFilters; import io.javaoperatorsdk.operator.processing.retry.GenericRetry; -import io.javaoperatorsdk.operator.processing.retry.GradualRetry; import io.javaoperatorsdk.operator.processing.retry.Retry; -public interface ControllerConfiguration

extends ResourceConfiguration

{ +public interface ControllerConfiguration

extends Informable

{ @SuppressWarnings("rawtypes") RateLimiter DEFAULT_RATE_LIMITER = LinearRateLimiter.deactivatedRateLimiter(); @@ -60,22 +56,7 @@ default boolean isGenerationAware() { String getAssociatedReconcilerClassName(); default Retry getRetry() { - final var configuration = getRetryConfiguration(); - return !RetryConfiguration.DEFAULT.equals(configuration) - ? GenericRetry.fromConfiguration(configuration) - : GenericRetry.DEFAULT; // NOSONAR - } - - /** - * Use {@link #getRetry()} instead. - * - * @return configuration for retry. - * @deprecated provide your own {@link Retry} implementation or use the {@link GradualRetry} - * annotation instead - */ - @Deprecated(forRemoval = true) - default RetryConfiguration getRetryConfiguration() { - return RetryConfiguration.DEFAULT; + return GenericRetry.DEFAULT; } @SuppressWarnings("rawtypes") @@ -83,50 +64,19 @@ default RateLimiter getRateLimiter() { return DEFAULT_RATE_LIMITER; } - /** - * Allow controllers to filter events before they are passed to the - * {@link io.javaoperatorsdk.operator.processing.event.EventHandler}. - * - *

- * Resource event filters only applies on events of the main custom resource. Not on events from - * other event sources nor the periodic events. - *

- * - * @return filter - * @deprecated use {@link ResourceConfiguration#onAddFilter()}, - * {@link ResourceConfiguration#onUpdateFilter()} or - * {@link ResourceConfiguration#genericFilter()} instead - */ - @Deprecated(forRemoval = true) - default ResourceEventFilter

getEventFilter() { - return ResourceEventFilters.passthrough(); - } - - @SuppressWarnings("rawtypes") - default List getDependentResources() { - return Collections.emptyList(); + default Optional getWorkflowSpec() { + return Optional.empty(); } default Optional maxReconciliationInterval() { return Optional.of(Duration.ofHours(MaxReconciliationInterval.DEFAULT_INTERVAL)); } - @SuppressWarnings("unused") ConfigurationService getConfigurationService(); - @SuppressWarnings("unchecked") - @Override - default Class

getResourceClass() { - // note that this implementation at the end not used within the boundaries of the core - // framework, should be removed in the future, (and marked as an API changed, or behavior - // change) - return (Class

) Utils.getFirstTypeArgumentFromSuperClassOrInterface(getClass(), - ControllerConfiguration.class); - } - @SuppressWarnings("unused") default Set getEffectiveNamespaces() { - return ResourceConfiguration.super.getEffectiveNamespaces(getConfigurationService()); + return getInformerConfig().getEffectiveNamespaces(this); } /** @@ -140,4 +90,5 @@ default String fieldManager() { return getName(); } + C getConfigurationFor(DependentResourceSpec spec); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ControllerConfigurationOverrider.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ControllerConfigurationOverrider.java index 328d912109..3d3eef5990 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ControllerConfigurationOverrider.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ControllerConfigurationOverrider.java @@ -10,55 +10,39 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.client.informers.cache.ItemStore; import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceSpec; +import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; import io.javaoperatorsdk.operator.processing.event.rate.RateLimiter; -import io.javaoperatorsdk.operator.processing.event.source.controller.ResourceEventFilter; 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 static io.javaoperatorsdk.operator.api.reconciler.Constants.DEFAULT_NAMESPACES_SET; -import static io.javaoperatorsdk.operator.api.reconciler.Constants.WATCH_CURRENT_NAMESPACE_SET; -@SuppressWarnings({"rawtypes", "unused"}) +@SuppressWarnings({"rawtypes", "unused", "UnusedReturnValue"}) public class ControllerConfigurationOverrider { + private final ControllerConfiguration original; + private String name; private String finalizer; private boolean generationAware; - private Set namespaces; private Retry retry; - private String labelSelector; - private ResourceEventFilter customResourcePredicate; - private final ControllerConfiguration original; - private Duration reconciliationMaxInterval; - private OnAddFilter onAddFilter; - private OnUpdateFilter onUpdateFilter; - private GenericFilter genericFilter; private RateLimiter rateLimiter; - private Map configurations; - private ItemStore itemStore; - private String name; private String fieldManager; - private Long informerListLimit; + private Duration reconciliationMaxInterval; + private Map configurations; + private final InformerConfiguration.Builder config; private ControllerConfigurationOverrider(ControllerConfiguration original) { this.finalizer = original.getFinalizerName(); this.generationAware = original.isGenerationAware(); - this.namespaces = new HashSet<>(original.getNamespaces()); + final var informerConfig = original.getInformerConfig(); + this.config = InformerConfiguration.builder(informerConfig); this.retry = original.getRetry(); - this.labelSelector = original.getLabelSelector(); - this.customResourcePredicate = original.getEventFilter(); this.reconciliationMaxInterval = original.maxReconciliationInterval().orElse(null); - this.onAddFilter = original.onAddFilter().orElse(null); - this.onUpdateFilter = original.onUpdateFilter().orElse(null); - this.genericFilter = original.genericFilter().orElse(null); this.original = original; this.rateLimiter = original.getRateLimiter(); this.name = original.getName(); this.fieldManager = original.fieldManager(); - this.informerListLimit = original.getInformerListLimit().orElse(null); - this.itemStore = original.getItemStore().orElse(null); } public ControllerConfigurationOverrider withFinalizer(String finalizer) { @@ -72,26 +56,36 @@ public ControllerConfigurationOverrider withGenerationAware(boolean generatio } public ControllerConfigurationOverrider watchingOnlyCurrentNamespace() { - this.namespaces = WATCH_CURRENT_NAMESPACE_SET; + config.withWatchCurrentNamespace(); return this; } public ControllerConfigurationOverrider addingNamespaces(String... namespaces) { - this.namespaces.addAll(List.of(namespaces)); + if (namespaces != null && namespaces.length > 0) { + final var current = config.namespaces(); + final var aggregated = new HashSet(current.size() + namespaces.length); + aggregated.addAll(current); + aggregated.addAll(Set.of(namespaces)); + config.withNamespaces(aggregated); + } return this; } public ControllerConfigurationOverrider removingNamespaces(String... namespaces) { - List.of(namespaces).forEach(this.namespaces::remove); - if (this.namespaces.isEmpty()) { - this.namespaces = DEFAULT_NAMESPACES_SET; + if (namespaces != null && namespaces.length > 0) { + final var current = new HashSet<>(config.namespaces()); + List.of(namespaces).forEach(current::remove); + if (current.isEmpty()) { + return watchingAllNamespaces(); + } else { + config.withNamespaces(current); + } } return this; } public ControllerConfigurationOverrider settingNamespaces(Set newNamespaces) { - this.namespaces.clear(); - this.namespaces.addAll(newNamespaces); + config.withNamespaces(newNamespaces); return this; } @@ -100,24 +94,12 @@ public ControllerConfigurationOverrider settingNamespaces(String... newNamesp } public ControllerConfigurationOverrider settingNamespace(String namespace) { - this.namespaces.clear(); - this.namespaces.add(namespace); + config.withNamespaces(Set.of(namespace)); return this; } public ControllerConfigurationOverrider watchingAllNamespaces() { - this.namespaces = DEFAULT_NAMESPACES_SET; - return this; - } - - /** - * @param retry configuration - * @return current instance of overrider - * @deprecated Use {@link #withRetry(Retry)} instead - */ - @Deprecated(forRemoval = true) - public ControllerConfigurationOverrider withRetry(RetryConfiguration retry) { - this.retry = GenericRetry.fromConfiguration(retry); + config.withWatchAllNamespaces(); return this; } @@ -132,13 +114,7 @@ public ControllerConfigurationOverrider withRateLimiter(RateLimiter rateLimit } public ControllerConfigurationOverrider withLabelSelector(String labelSelector) { - this.labelSelector = labelSelector; - return this; - } - - public ControllerConfigurationOverrider withCustomResourcePredicate( - ResourceEventFilter customResourcePredicate) { - this.customResourcePredicate = customResourcePredicate; + config.withLabelSelector(labelSelector); return this; } @@ -149,27 +125,28 @@ public ControllerConfigurationOverrider withReconciliationMaxInterval( } public ControllerConfigurationOverrider withOnAddFilter(OnAddFilter onAddFilter) { - this.onAddFilter = onAddFilter; + config.withOnAddFilter(onAddFilter); return this; } public ControllerConfigurationOverrider withOnUpdateFilter(OnUpdateFilter onUpdateFilter) { - this.onUpdateFilter = onUpdateFilter; + config.withOnUpdateFilter(onUpdateFilter); return this; } public ControllerConfigurationOverrider withGenericFilter(GenericFilter genericFilter) { - this.genericFilter = genericFilter; + config.withGenericFilter(genericFilter); return this; } public ControllerConfigurationOverrider withItemStore(ItemStore itemStore) { - this.itemStore = itemStore; + config.withItemStore(itemStore); return this; } public ControllerConfigurationOverrider withName(String name) { this.name = name; + config.withName(name); return this; } @@ -189,14 +166,14 @@ public ControllerConfigurationOverrider withFieldManager( */ public ControllerConfigurationOverrider withInformerListLimit( Long informerListLimit) { - this.informerListLimit = informerListLimit; + config.withInformerListLimit(informerListLimit); return this; } public ControllerConfigurationOverrider replacingNamedDependentResourceConfig(String name, Object dependentResourceConfig) { - final var specs = original.getDependentResources(); + final var specs = original.getWorkflowSpec().orElseThrow().getDependentResourceSpecs(); final var spec = specs.stream() .filter(drs -> drs.getName().equals(name)).findFirst() .orElseThrow( @@ -210,15 +187,14 @@ public ControllerConfigurationOverrider replacingNamedDependentResourceConfig } public ControllerConfiguration build() { - final var overridden = new ResolvedControllerConfiguration<>(original.getResourceClass(), + return new ResolvedControllerConfiguration<>( name, generationAware, original.getAssociatedReconcilerClassName(), retry, rateLimiter, - reconciliationMaxInterval, onAddFilter, onUpdateFilter, genericFilter, - original.getDependentResources(), - namespaces, finalizer, labelSelector, configurations, itemStore, fieldManager, - original.getConfigurationService(), informerListLimit); - overridden.setEventFilter(customResourcePredicate); - return overridden; + reconciliationMaxInterval, + finalizer, configurations, fieldManager, + original.getConfigurationService(), + config.buildForController(), + original.getWorkflowSpec().orElse(null)); } public static ControllerConfigurationOverrider override( diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/DefaultResourceClassResolver.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/DefaultResourceClassResolver.java index c038e7d966..cdd4c5540e 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/DefaultResourceClassResolver.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/DefaultResourceClassResolver.java @@ -7,7 +7,7 @@ public class DefaultResourceClassResolver implements ResourceClassResolver { @SuppressWarnings("unchecked") @Override - public Class getResourceClass( + public Class getPrimaryResourceClass( Class> reconcilerClass) { return (Class) Utils.getFirstTypeArgumentFromSuperClassOrInterface(reconcilerClass, Reconciler.class); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/DefaultResourceConfiguration.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/DefaultResourceConfiguration.java deleted file mode 100644 index f8ee9f4e84..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/DefaultResourceConfiguration.java +++ /dev/null @@ -1,91 +0,0 @@ -package io.javaoperatorsdk.operator.api.config; - -import java.util.Optional; -import java.util.Set; - -import io.fabric8.kubernetes.api.model.GenericKubernetesResource; -import io.fabric8.kubernetes.api.model.HasMetadata; -import io.fabric8.kubernetes.client.informers.cache.ItemStore; -import io.javaoperatorsdk.operator.ReconcilerUtils; -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; - -public class DefaultResourceConfiguration - implements ResourceConfiguration { - - private final Class resourceClass; - private final String resourceTypeName; - private final OnAddFilter onAddFilter; - private final OnUpdateFilter onUpdateFilter; - private final GenericFilter genericFilter; - private final String labelSelector; - private final Set namespaces; - private final ItemStore itemStore; - private final Long informerListLimit; - - protected DefaultResourceConfiguration(Class resourceClass, - Set namespaces, String labelSelector, OnAddFilter onAddFilter, - OnUpdateFilter onUpdateFilter, GenericFilter genericFilter, - ItemStore itemStore, Long informerListLimit) { - this.resourceClass = resourceClass; - this.resourceTypeName = resourceClass.isAssignableFrom(GenericKubernetesResource.class) - // in general this is irrelevant now for secondary resources it is used just by controller - // where GenericKubernetesResource now does not apply - ? GenericKubernetesResource.class.getSimpleName() - : ReconcilerUtils.getResourceTypeName(resourceClass); - this.onAddFilter = onAddFilter; - this.onUpdateFilter = onUpdateFilter; - this.genericFilter = genericFilter; - - this.namespaces = ResourceConfiguration.ensureValidNamespaces(namespaces); - this.labelSelector = ResourceConfiguration.ensureValidLabelSelector(labelSelector); - this.itemStore = itemStore; - this.informerListLimit = informerListLimit; - } - - @Override - public String getResourceTypeName() { - return resourceTypeName; - } - - @Override - public String getLabelSelector() { - return labelSelector; - } - - @Override - public Set getNamespaces() { - return namespaces; - } - - @Override - public Class getResourceClass() { - return resourceClass; - } - - @Override - public Optional> onAddFilter() { - return Optional.ofNullable(onAddFilter); - } - - @Override - public Optional> onUpdateFilter() { - return Optional.ofNullable(onUpdateFilter); - } - - @Override - public Optional> genericFilter() { - return Optional.ofNullable(genericFilter); - } - - @Override - public Optional> getItemStore() { - return Optional.ofNullable(itemStore); - } - - @Override - public Optional getInformerListLimit() { - return Optional.ofNullable(informerListLimit); - } -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/DefaultRetryConfiguration.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/DefaultRetryConfiguration.java deleted file mode 100644 index 40fbb38aa7..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/DefaultRetryConfiguration.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.javaoperatorsdk.operator.api.config; - -public class DefaultRetryConfiguration implements RetryConfiguration { - -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ExecutorServiceManager.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ExecutorServiceManager.java index 112ab7188a..c35281e822 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ExecutorServiceManager.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ExecutorServiceManager.java @@ -22,7 +22,6 @@ public class ExecutorServiceManager { private static final Logger log = LoggerFactory.getLogger(ExecutorServiceManager.class); - public static final int MIN_THREAD_NUMBER = 0; private ExecutorService executor; private ExecutorService workflowExecutor; private ExecutorService cachingExecutorService; diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/Informable.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/Informable.java new file mode 100644 index 0000000000..5b58836483 --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/Informable.java @@ -0,0 +1,18 @@ +package io.javaoperatorsdk.operator.api.config; + + +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; + +public interface Informable { + + default String getResourceTypeName() { + return getInformerConfig().getResourceTypeName(); + } + + InformerConfiguration getInformerConfig(); + + default Class getResourceClass() { + return getInformerConfig().getResourceClass(); + } +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/LeaderElectionConfiguration.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/LeaderElectionConfiguration.java index 0ab72ff165..cfce453e14 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/LeaderElectionConfiguration.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/LeaderElectionConfiguration.java @@ -20,6 +20,7 @@ public class LeaderElectionConfiguration { private final Duration retryPeriod; private final LeaderCallbacks leaderCallbacks; + private final boolean exitOnStopLeading; public LeaderElectionConfiguration(String leaseName, String leaseNamespace, String identity) { this( @@ -27,7 +28,7 @@ public LeaderElectionConfiguration(String leaseName, String leaseNamespace, Stri leaseNamespace, LEASE_DURATION_DEFAULT_VALUE, RENEW_DEADLINE_DEFAULT_VALUE, - RETRY_PERIOD_DEFAULT_VALUE, identity, null); + RETRY_PERIOD_DEFAULT_VALUE, identity, null, true); } public LeaderElectionConfiguration(String leaseName, String leaseNamespace) { @@ -36,7 +37,7 @@ public LeaderElectionConfiguration(String leaseName, String leaseNamespace) { leaseNamespace, LEASE_DURATION_DEFAULT_VALUE, RENEW_DEADLINE_DEFAULT_VALUE, - RETRY_PERIOD_DEFAULT_VALUE, null, null); + RETRY_PERIOD_DEFAULT_VALUE, null, null, true); } public LeaderElectionConfiguration(String leaseName) { @@ -45,7 +46,7 @@ public LeaderElectionConfiguration(String leaseName) { null, LEASE_DURATION_DEFAULT_VALUE, RENEW_DEADLINE_DEFAULT_VALUE, - RETRY_PERIOD_DEFAULT_VALUE, null, null); + RETRY_PERIOD_DEFAULT_VALUE, null, null, true); } public LeaderElectionConfiguration( @@ -54,7 +55,7 @@ public LeaderElectionConfiguration( Duration leaseDuration, Duration renewDeadline, Duration retryPeriod) { - this(leaseName, leaseNamespace, leaseDuration, renewDeadline, retryPeriod, null, null); + this(leaseName, leaseNamespace, leaseDuration, renewDeadline, retryPeriod, null, null, true); } public LeaderElectionConfiguration( @@ -64,7 +65,8 @@ public LeaderElectionConfiguration( Duration renewDeadline, Duration retryPeriod, String identity, - LeaderCallbacks leaderCallbacks) { + LeaderCallbacks leaderCallbacks, + boolean exitOnStopLeading) { this.leaseName = leaseName; this.leaseNamespace = leaseNamespace; this.leaseDuration = leaseDuration; @@ -72,6 +74,7 @@ public LeaderElectionConfiguration( this.retryPeriod = retryPeriod; this.identity = identity; this.leaderCallbacks = leaderCallbacks; + this.exitOnStopLeading = exitOnStopLeading; } public Optional getLeaseNamespace() { @@ -101,4 +104,8 @@ public Optional getIdentity() { public Optional getLeaderCallbacks() { return Optional.ofNullable(leaderCallbacks); } + + public boolean isExitOnStopLeading() { + return exitOnStopLeading; + } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/LeaderElectionConfigurationBuilder.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/LeaderElectionConfigurationBuilder.java index 4b21dd9d2d..eda262f9eb 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/LeaderElectionConfigurationBuilder.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/LeaderElectionConfigurationBuilder.java @@ -6,15 +6,17 @@ import static io.javaoperatorsdk.operator.api.config.LeaderElectionConfiguration.*; +@SuppressWarnings("unused") public final class LeaderElectionConfigurationBuilder { - private String leaseName; + private final String leaseName; private String leaseNamespace; private String identity; private Duration leaseDuration = LEASE_DURATION_DEFAULT_VALUE; private Duration renewDeadline = RENEW_DEADLINE_DEFAULT_VALUE; private Duration retryPeriod = RETRY_PERIOD_DEFAULT_VALUE; private LeaderCallbacks leaderCallbacks; + private boolean exitOnStopLeading = true; private LeaderElectionConfigurationBuilder(String leaseName) { this.leaseName = leaseName; @@ -54,8 +56,13 @@ public LeaderElectionConfigurationBuilder withLeaderCallbacks(LeaderCallbacks le return this; } + public LeaderElectionConfigurationBuilder withExitOnStopLeading(boolean exitOnStopLeading) { + this.exitOnStopLeading = exitOnStopLeading; + return this; + } + public LeaderElectionConfiguration build() { return new LeaderElectionConfiguration(leaseName, leaseNamespace, leaseDuration, renewDeadline, - retryPeriod, identity, leaderCallbacks); + retryPeriod, identity, leaderCallbacks, exitOnStopLeading); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ResolvedControllerConfiguration.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ResolvedControllerConfiguration.java index 307e75080f..7e8415f584 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ResolvedControllerConfiguration.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ResolvedControllerConfiguration.java @@ -1,27 +1,24 @@ package io.javaoperatorsdk.operator.api.config; import java.time.Duration; -import java.util.*; +import java.util.Collections; +import java.util.Map; +import java.util.Optional; import java.util.concurrent.TimeUnit; import io.fabric8.kubernetes.api.model.HasMetadata; -import io.fabric8.kubernetes.client.informers.cache.ItemStore; -import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceConfigurationProvider; 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.api.reconciler.Reconciler; import io.javaoperatorsdk.operator.processing.event.rate.RateLimiter; -import io.javaoperatorsdk.operator.processing.event.source.controller.ResourceEventFilter; -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.Retry; @SuppressWarnings("rawtypes") public class ResolvedControllerConfiguration

- extends DefaultResourceConfiguration

- implements io.javaoperatorsdk.operator.api.config.ControllerConfiguration

, - DependentResourceConfigurationProvider { + implements io.javaoperatorsdk.operator.api.config.ControllerConfiguration

{ + private final InformerConfiguration

informerConfig; private final String name; private final boolean generationAware; private final String associatedReconcilerClassName; @@ -30,71 +27,43 @@ public class ResolvedControllerConfiguration

private final Duration maxReconciliationInterval; private final String finalizer; private final Map configurations; - private final ItemStore

itemStore; private final ConfigurationService configurationService; private final String fieldManager; + private WorkflowSpec workflowSpec; - private ResourceEventFilter

eventFilter; - private List dependentResources; - - public ResolvedControllerConfiguration(Class

resourceClass, ControllerConfiguration

other) { - this(resourceClass, other.getName(), other.isGenerationAware(), + public ResolvedControllerConfiguration(ControllerConfiguration

other) { + this(other.getName(), other.isGenerationAware(), other.getAssociatedReconcilerClassName(), other.getRetry(), other.getRateLimiter(), other.maxReconciliationInterval().orElse(null), - other.onAddFilter().orElse(null), other.onUpdateFilter().orElse(null), - other.genericFilter().orElse(null), - other.getDependentResources(), other.getNamespaces(), - other.getFinalizerName(), other.getLabelSelector(), Collections.emptyMap(), - other.getItemStore().orElse(null), other.fieldManager(), + other.getFinalizerName(), Collections.emptyMap(), + other.fieldManager(), other.getConfigurationService(), - other.getInformerListLimit().orElse(null)); + other.getInformerConfig(), + other.getWorkflowSpec().orElse(null)); } - public static Duration getMaxReconciliationInterval(long interval, TimeUnit timeUnit) { - return interval > 0 ? Duration.of(interval, timeUnit.toChronoUnit()) : null; - } - - public static String getAssociatedReconcilerClassName( - Class reconcilerClass) { - return reconcilerClass.getCanonicalName(); - } - - protected Retry ensureRetry(Retry given) { - return given == null ? ControllerConfiguration.super.getRetry() : given; - } - - protected RateLimiter ensureRateLimiter(RateLimiter given) { - return given == null ? ControllerConfiguration.super.getRateLimiter() : given; - } - - public ResolvedControllerConfiguration(Class

resourceClass, String name, + public ResolvedControllerConfiguration(String name, boolean generationAware, String associatedReconcilerClassName, Retry retry, RateLimiter rateLimiter, Duration maxReconciliationInterval, - OnAddFilter onAddFilter, OnUpdateFilter onUpdateFilter, - GenericFilter genericFilter, - List dependentResources, - Set namespaces, String finalizer, String labelSelector, - Map configurations, ItemStore

itemStore, + String finalizer, + Map configurations, String fieldManager, - ConfigurationService configurationService, Long informerListLimit) { - this(resourceClass, name, generationAware, associatedReconcilerClassName, retry, rateLimiter, - maxReconciliationInterval, onAddFilter, onUpdateFilter, genericFilter, - namespaces, finalizer, labelSelector, configurations, itemStore, fieldManager, - configurationService, informerListLimit); - setDependentResources(dependentResources); + ConfigurationService configurationService, + InformerConfiguration

informerConfig, + WorkflowSpec workflowSpec) { + this(name, generationAware, associatedReconcilerClassName, retry, rateLimiter, + maxReconciliationInterval, finalizer, configurations, fieldManager, + configurationService, informerConfig); + setWorkflowSpec(workflowSpec); } - protected ResolvedControllerConfiguration(Class

resourceClass, String name, + protected ResolvedControllerConfiguration(String name, boolean generationAware, String associatedReconcilerClassName, Retry retry, - RateLimiter rateLimiter, Duration maxReconciliationInterval, - OnAddFilter onAddFilter, OnUpdateFilter onUpdateFilter, - GenericFilter genericFilter, - Set namespaces, String finalizer, String labelSelector, - Map configurations, ItemStore

itemStore, + RateLimiter rateLimiter, Duration maxReconciliationInterval, String finalizer, + Map configurations, String fieldManager, - ConfigurationService configurationService, Long informerListLimit) { - super(resourceClass, namespaces, labelSelector, onAddFilter, onUpdateFilter, genericFilter, - itemStore, informerListLimit); + ConfigurationService configurationService, InformerConfiguration

informerConfig) { + this.informerConfig = informerConfig; this.configurationService = configurationService; this.name = ControllerConfiguration.ensureValidName(name, associatedReconcilerClassName); this.generationAware = generationAware; @@ -103,7 +72,6 @@ protected ResolvedControllerConfiguration(Class

resourceClass, String name, this.rateLimiter = ensureRateLimiter(rateLimiter); this.maxReconciliationInterval = maxReconciliationInterval; this.configurations = configurations != null ? configurations : Collections.emptyMap(); - this.itemStore = itemStore; this.finalizer = ControllerConfiguration.ensureValidFinalizerName(finalizer, getResourceTypeName()); this.fieldManager = fieldManager; @@ -111,9 +79,31 @@ protected ResolvedControllerConfiguration(Class

resourceClass, String name, protected ResolvedControllerConfiguration(Class

resourceClass, String name, Class reconcilerClas, ConfigurationService configurationService) { - this(resourceClass, name, false, getAssociatedReconcilerClassName(reconcilerClas), null, null, - null, null, null, null, null, - null, null, null, null, null, configurationService, null); + this(name, false, getAssociatedReconcilerClassName(reconcilerClas), null, null, + null, null, null, null, configurationService, + InformerConfiguration.builder(resourceClass).buildForController()); + } + + @Override + public InformerConfiguration

getInformerConfig() { + return informerConfig; + } + + public static Duration getMaxReconciliationInterval(long interval, TimeUnit timeUnit) { + return interval > 0 ? Duration.of(interval, timeUnit.toChronoUnit()) : null; + } + + public static String getAssociatedReconcilerClassName( + Class reconcilerClass) { + return reconcilerClass.getCanonicalName(); + } + + protected Retry ensureRetry(Retry given) { + return given == null ? ControllerConfiguration.super.getRetry() : given; + } + + protected RateLimiter ensureRateLimiter(RateLimiter given) { + return given == null ? ControllerConfiguration.super.getRateLimiter() : given; } @Override @@ -146,14 +136,14 @@ public RateLimiter getRateLimiter() { return rateLimiter; } + @Override - public List getDependentResources() { - return dependentResources; + public Optional getWorkflowSpec() { + return Optional.ofNullable(workflowSpec); } - protected void setDependentResources(List dependentResources) { - this.dependentResources = dependentResources == null ? Collections.emptyList() - : Collections.unmodifiableList(dependentResources); + public void setWorkflowSpec(WorkflowSpec workflowSpec) { + this.workflowSpec = workflowSpec; } @Override @@ -167,28 +157,15 @@ public ConfigurationService getConfigurationService() { } @Override - public ResourceEventFilter

getEventFilter() { - return eventFilter; - } - - /** - * @deprecated Use {@link OnAddFilter}, {@link OnUpdateFilter} and {@link GenericFilter} instead - * - * @param eventFilter generic event filter - */ - @Deprecated(forRemoval = true) - protected void setEventFilter(ResourceEventFilter

eventFilter) { - this.eventFilter = eventFilter; - } - - @Override - public Object getConfigurationFor(DependentResourceSpec spec) { - return configurations.get(spec); - } - - @Override - public Optional> getItemStore() { - return Optional.ofNullable(itemStore); + @SuppressWarnings("unchecked") + public C getConfigurationFor(DependentResourceSpec spec) { + // first check if there's an overridden configuration at the controller level + var config = configurations.get(spec); + if (config == null) { + // if not, check the spec for configuration + config = spec.getConfiguration().orElse(null); + } + return (C) config; } @Override diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ResourceClassResolver.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ResourceClassResolver.java index e15d53016a..001eb3e0de 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ResourceClassResolver.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ResourceClassResolver.java @@ -5,6 +5,7 @@ public interface ResourceClassResolver { - Class getResourceClass(Class> reconcilerClass); +

Class

getPrimaryResourceClass( + Class> reconcilerClass); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ResourceConfiguration.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ResourceConfiguration.java deleted file mode 100644 index d94504f50f..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ResourceConfiguration.java +++ /dev/null @@ -1,156 +0,0 @@ -package io.javaoperatorsdk.operator.api.config; - -import java.util.Collection; -import java.util.Collections; -import java.util.Optional; -import java.util.Set; - -import io.fabric8.kubernetes.api.model.HasMetadata; -import io.fabric8.kubernetes.client.informers.cache.ItemStore; -import io.javaoperatorsdk.operator.OperatorException; -import io.javaoperatorsdk.operator.ReconcilerUtils; -import io.javaoperatorsdk.operator.api.reconciler.Constants; -import io.javaoperatorsdk.operator.processing.event.source.cache.BoundedItemStore; -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 static io.javaoperatorsdk.operator.api.reconciler.Constants.DEFAULT_NAMESPACES_SET; -import static io.javaoperatorsdk.operator.api.reconciler.Constants.WATCH_CURRENT_NAMESPACE_SET; - -public interface ResourceConfiguration { - - default String getResourceTypeName() { - return ReconcilerUtils.getResourceTypeName(getResourceClass()); - } - - default Optional> onAddFilter() { - return Optional.empty(); - } - - default Optional> onUpdateFilter() { - return Optional.empty(); - } - - default Optional> genericFilter() { - return Optional.empty(); - } - - /** - * Retrieves the label selector that is used to filter which resources are actually watched by the - * associated event source. See the official documentation on the - * topic - * for more details on syntax. - * - * @return the label selector filtering watched resources - */ - default String getLabelSelector() { - return null; - } - - static String ensureValidLabelSelector(String labelSelector) { - // might want to implement validation here? - return labelSelector; - } - - @SuppressWarnings("unchecked") - default Class getResourceClass() { - return (Class) Utils.getFirstTypeArgumentFromSuperClassOrInterface(getClass(), - ResourceConfiguration.class); - } - - default Set getNamespaces() { - return DEFAULT_NAMESPACES_SET; - } - - default boolean watchAllNamespaces() { - return allNamespacesWatched(getNamespaces()); - } - - static boolean allNamespacesWatched(Set namespaces) { - failIfNotValid(namespaces); - return DEFAULT_NAMESPACES_SET.equals(namespaces); - } - - default boolean watchCurrentNamespace() { - return currentNamespaceWatched(getNamespaces()); - } - - static boolean currentNamespaceWatched(Set namespaces) { - failIfNotValid(namespaces); - return WATCH_CURRENT_NAMESPACE_SET.equals(namespaces); - } - - static void failIfNotValid(Set namespaces) { - if (namespaces != null && !namespaces.isEmpty()) { - final var present = namespaces.contains(Constants.WATCH_CURRENT_NAMESPACE) - || namespaces.contains(Constants.WATCH_ALL_NAMESPACES); - if (!present || namespaces.size() == 1) { - return; - } - } - throw new IllegalArgumentException( - "Must specify namespaces. To watch all namespaces, use only '" - + Constants.WATCH_ALL_NAMESPACES - + "'. To watch only the namespace in which the operator is deployed, use only '" - + Constants.WATCH_CURRENT_NAMESPACE + "'"); - } - - static Set ensureValidNamespaces(Collection namespaces) { - if (namespaces != null && !namespaces.isEmpty()) { - return Set.copyOf(namespaces); - } else { - return Constants.DEFAULT_NAMESPACES_SET; - } - } - - /** - * Computes the effective namespaces based on the set specified by the user, in particular - * retrieves the current namespace from the client when the user specified that they wanted to - * watch the current namespace only. - * - * @return a Set of namespace names the associated controller will watch - */ - default Set getEffectiveNamespaces(ConfigurationService configurationService) { - var targetNamespaces = getNamespaces(); - if (watchCurrentNamespace()) { - final String namespace = - configurationService.getKubernetesClient().getConfiguration().getNamespace(); - if (namespace == null) { - throw new OperatorException( - "Couldn't retrieve the currently connected namespace. Make sure it's correctly set in your ~/.kube/config file, using, e.g. 'kubectl config set-context --namespace='"); - } - targetNamespaces = Collections.singleton(namespace); - } - return targetNamespaces; - } - - /** - * Replaces the item store in informer. See underlying method - * in fabric8 client informer implementation. - * - *

- * The main goal, is to be able to use limited caches or provide any custom implementation. - *

- * - *

- * See {@link BoundedItemStore} and CaffeineBoundedCache - *

- * - * @return Optional {@link ItemStore} implementation. If present this item store will be used by - * the informers. - */ - default Optional> getItemStore() { - return Optional.empty(); - } - - /** - * The maximum amount of items to return for a single list call when starting an informer. If this - * is a not null it will result in paginating for the initial load of the informer cache. - */ - default Optional getInformerListLimit() { - return Optional.empty(); - } -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/RetryConfiguration.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/RetryConfiguration.java deleted file mode 100644 index b293c7e33f..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/RetryConfiguration.java +++ /dev/null @@ -1,33 +0,0 @@ -package io.javaoperatorsdk.operator.api.config; - -import io.javaoperatorsdk.operator.processing.retry.GradualRetry; - -/** - * @deprecated specify your own {@link io.javaoperatorsdk.operator.processing.retry.Retry} - * implementation or use {@link GradualRetry} annotation instead - */ -@Deprecated(forRemoval = true) -public interface RetryConfiguration { - - RetryConfiguration DEFAULT = new DefaultRetryConfiguration(); - - int DEFAULT_MAX_ATTEMPTS = 5; - long DEFAULT_INITIAL_INTERVAL = 2000L; - double DEFAULT_MULTIPLIER = 1.5D; - - default int getMaxAttempts() { - return DEFAULT_MAX_ATTEMPTS; - } - - default long getInitialInterval() { - return DEFAULT_INITIAL_INTERVAL; - } - - default double getIntervalMultiplier() { - return DEFAULT_MULTIPLIER; - } - - default long getMaxInterval() { - return (long) (DEFAULT_INITIAL_INTERVAL * Math.pow(DEFAULT_MULTIPLIER, DEFAULT_MAX_ATTEMPTS)); - } -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/Utils.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/Utils.java index 6971de6476..ea776f3a6c 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/Utils.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/Utils.java @@ -33,11 +33,8 @@ public class Utils { * via the {@code git-commit-id-plugin} maven plugin. * * @return a {@link Version} object encapsulating the version information - * @deprecated use {@link #VERSION} instead, as this method will be made internal in a future - * release */ - @Deprecated - public static Version loadFromProperties() { + private static Version loadFromProperties() { final var is = Thread.currentThread().getContextClassLoader().getResourceAsStream("version.properties"); @@ -79,9 +76,8 @@ public static int ensureValid(int value, String description, int minValue, int d throw new IllegalArgumentException( "Default value for " + description + " must be greater than " + minValue); } - log.warn("Requested " + description + " should be greater than " + minValue + ". Requested: " - + value + ", using " + defaultValue + (defaultValue == minValue ? "" : " (default)") + - " instead"); + log.warn("Requested {} should be greater than {}. Requested: {}, using {}{} instead", + description, minValue, value, defaultValue, defaultValue == minValue ? "" : " (default)"); value = defaultValue; } return value; @@ -107,21 +103,22 @@ static boolean getBooleanFromSystemPropsOrDefault(String propertyName, boolean d return defaultValue; } else { property = property.trim().toLowerCase(); - switch (property) { - case "true": - return true; - case "false": - return false; - default: - return defaultValue; - } + return switch (property) { + case "true" -> true; + case "false" -> false; + default -> defaultValue; + }; } } public static Class getFirstTypeArgumentFromExtendedClass(Class clazz) { + return getTypeArgumentFromExtendedClassByIndex(clazz, 0); + } + + public static Class getTypeArgumentFromExtendedClassByIndex(Class clazz, int index) { try { Type type = clazz.getGenericSuperclass(); - return (Class) ((ParameterizedType) type).getActualTypeArguments()[0]; + return (Class) ((ParameterizedType) type).getActualTypeArguments()[index]; } catch (Exception e) { throw new RuntimeException(GENERIC_PARAMETER_TYPE_ERROR_PREFIX + clazz.getSimpleName() @@ -190,27 +187,31 @@ private static Optional> extractType(Class clazz, public static Class getFirstTypeArgumentFromSuperClassOrInterface(Class clazz, Class expectedImplementedInterface) { + return getTypeArgumentFromSuperClassOrInterfaceByIndex(clazz, expectedImplementedInterface, 0); + } + + public static Class getTypeArgumentFromSuperClassOrInterfaceByIndex(Class clazz, + Class expectedImplementedInterface, int index) { // first check super class if it exists try { final Class superclass = clazz.getSuperclass(); if (!superclass.equals(Object.class)) { try { - return getFirstTypeArgumentFromExtendedClass(clazz); + return getTypeArgumentFromExtendedClassByIndex(clazz, index); } catch (Exception e) { // try interfaces try { - return getFirstTypeArgumentFromInterface(clazz, expectedImplementedInterface); + return getTypeArgumentFromInterfaceByIndex(clazz, expectedImplementedInterface, index); } catch (Exception ex) { // try on the parent - return getFirstTypeArgumentFromSuperClassOrInterface(superclass, - expectedImplementedInterface); + return getTypeArgumentFromSuperClassOrInterfaceByIndex(superclass, + expectedImplementedInterface, index); } } } - return getFirstTypeArgumentFromInterface(clazz, expectedImplementedInterface); + return getTypeArgumentFromInterfaceByIndex(clazz, expectedImplementedInterface, index); } catch (Exception e) { - throw new OperatorException( - GENERIC_PARAMETER_TYPE_ERROR_PREFIX + clazz.getSimpleName(), e); + throw new OperatorException(GENERIC_PARAMETER_TYPE_ERROR_PREFIX + clazz.getSimpleName(), e); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/dependent/ConfigurationConverter.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/dependent/ConfigurationConverter.java index 68e0f521de..f0327514ae 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/dependent/ConfigurationConverter.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/dependent/ConfigurationConverter.java @@ -3,10 +3,9 @@ import java.lang.annotation.Annotation; import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; -import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.DependentResourceConfigurator; -public interface ConfigurationConverter> { +public interface ConfigurationConverter { - C configFrom(A configAnnotation, ControllerConfiguration parentConfiguration, - Class originatingClass); + C configFrom(A configAnnotation, DependentResourceSpec spec, + ControllerConfiguration parentConfiguration); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/dependent/DependentResourceConfigurationResolver.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/dependent/DependentResourceConfigurationResolver.java index ebe8b2ad0e..471b0f6a8e 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/dependent/DependentResourceConfigurationResolver.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/dependent/DependentResourceConfigurationResolver.java @@ -8,7 +8,6 @@ import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.config.Utils; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; -import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.DependentResourceConfigurator; @SuppressWarnings({"rawtypes", "unchecked"}) public class DependentResourceConfigurationResolver { @@ -20,41 +19,18 @@ private DependentResourceConfigurationResolver() {} private static final Map, ConfigurationConverter> knownConverters = new HashMap<>(); - public static > void configure( - DependentResource dependentResource, DependentResourceSpec spec, C parentConfiguration) { - if (dependentResource instanceof DependentResourceConfigurator) { - final var configurator = (DependentResourceConfigurator) dependentResource; - final var config = configurationFor(spec, parentConfiguration); - configurator.configureWith(config); - } - } - - public static > Object configurationFor( - DependentResourceSpec spec, C parentConfiguration) { - // first check if the parent configuration has potentially already resolved the configuration - if (parentConfiguration instanceof DependentResourceConfigurationProvider) { - final var provider = (DependentResourceConfigurationProvider) parentConfiguration; - final var configuration = provider.getConfigurationFor(spec); - if (configuration != null) { - return configuration; - } - } - - // find Configured-annotated class if it exists - return extractConfigurationFromConfigured(spec.getDependentResourceClass(), - parentConfiguration); - } - - public static > Object extractConfigurationFromConfigured( - Class dependentResourceClass, C parentConfiguration) { + public static > void configureSpecFromConfigured( + DependentResourceSpec spec, + C parentConfiguration, + Class dependentResourceClass) { var converterAnnotationPair = converters.get(dependentResourceClass); Annotation configAnnotation; if (converterAnnotationPair == null) { var configuredClassPair = getConfigured(dependentResourceClass); if (configuredClassPair == null) { - return null; + return; } // check if we already have a converter registered for the found Configured annotated class @@ -78,7 +54,8 @@ public static > Object // always called even if the annotation is null so that implementations can provide default // values - return converter.configFrom(configAnnotation, parentConfiguration, dependentResourceClass); + final var config = converter.configFrom(configAnnotation, spec, parentConfiguration); + spec.setNullableConfiguration(config); } private static ConfiguredClassPair getConfigured( diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/dependent/DependentResourceSpec.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/dependent/DependentResourceSpec.java index 1fcd0709fb..accccb3f6e 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/dependent/DependentResourceSpec.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/dependent/DependentResourceSpec.java @@ -8,23 +8,17 @@ import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; import io.javaoperatorsdk.operator.processing.dependent.workflow.Condition; -public class DependentResourceSpec { +public class DependentResourceSpec { private final Class> dependentResourceClass; - private final String name; - private final Set dependsOn; - private final Condition readyCondition; - private final Condition reconcileCondition; - private final Condition deletePostCondition; - private final Condition activationCondition; - private final String useEventSourceWithName; + private C nullableConfiguration; public DependentResourceSpec(Class> dependentResourceClass, String name, Set dependsOn, Condition readyCondition, @@ -62,7 +56,7 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } - DependentResourceSpec that = (DependentResourceSpec) o; + DependentResourceSpec that = (DependentResourceSpec) o; return name.equals(that.name); } @@ -98,4 +92,13 @@ public Condition getActivationCondition() { public Optional getUseEventSourceWithName() { return Optional.ofNullable(useEventSourceWithName); } + + public Optional getConfiguration() { + return Optional.ofNullable(nullableConfiguration); + } + + protected void setNullableConfiguration(C configuration) { + this.nullableConfiguration = configuration; + } + } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/Informer.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/Informer.java new file mode 100644 index 0000000000..3a425b786b --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/Informer.java @@ -0,0 +1,119 @@ +package io.javaoperatorsdk.operator.api.config.informer; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import io.fabric8.kubernetes.client.informers.cache.ItemStore; +import io.javaoperatorsdk.operator.api.reconciler.Constants; +import io.javaoperatorsdk.operator.processing.event.source.cache.BoundedItemStore; +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 static io.javaoperatorsdk.operator.api.reconciler.Constants.DEFAULT_FOLLOW_CONTROLLER_NAMESPACES_ON_CHANGE; +import static io.javaoperatorsdk.operator.api.reconciler.Constants.NO_LONG_VALUE_SET; +import static io.javaoperatorsdk.operator.api.reconciler.Constants.NO_VALUE_SET; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE}) +public @interface Informer { + + String name() default NO_VALUE_SET; + + /** + * Specified which namespaces the associated informer monitors for custom resources events. If no + * namespace is specified then which namespaces the informer will monitor will depend on the + * context in which the informer is configured: + *
    + *
  • all namespaces if configuring a controller informer
  • + *
  • the namespaces configured for the associated controller if configuring an event source
  • + *
+ * + * You can set a list of namespaces or use the following constants: + *
    + *
  • {@link Constants#WATCH_ALL_NAMESPACES}
  • + *
  • {@link Constants#WATCH_CURRENT_NAMESPACE}
  • + *
  • {@link Constants#SAME_AS_CONTROLLER}
  • + *
+ * + * @return the array of namespaces the associated informer monitors + */ + String[] namespaces() default {Constants.SAME_AS_CONTROLLER}; + + /** + * Optional label selector used to identify the set of custom resources the associated informer + * will act upon. The label selector can be made of multiple comma separated requirements that + * acts as a logical AND operator. + * + * @return the label selector + */ + String labelSelector() default NO_VALUE_SET; + + /** + * Optional {@link OnAddFilter} to filter add events sent to the associated informer + * + * @return the {@link OnAddFilter} filter implementation to use, defaulting to the interface + * itself if no value is set + */ + Class onAddFilter() default OnAddFilter.class; + + /** + * Optional {@link OnUpdateFilter} to filter update events sent to the associated informer + * + * @return the {@link OnUpdateFilter} filter implementation to use, defaulting to the interface + * itself if no value is set + */ + Class onUpdateFilter() default OnUpdateFilter.class; + + /** + * Optional {@link OnDeleteFilter} to filter delete events sent to the associated informer + * + * @return the {@link OnDeleteFilter} filter implementation to use, defaulting to the interface + * itself if no value is set + */ + Class onDeleteFilter() default OnDeleteFilter.class; + + /** + * Optional {@link GenericFilter} to filter events sent to the associated informer + * + * @return the {@link GenericFilter} filter implementation to use, defaulting to the interface + * itself if no value is set + */ + Class genericFilter() default GenericFilter.class; + + /** + * Set that in case of a runtime controller namespace changes, the informer should also follow the + * new namespace set. + */ + boolean followControllerNamespacesOnChange() default DEFAULT_FOLLOW_CONTROLLER_NAMESPACES_ON_CHANGE; + + /** + * Replaces the item store used by the informer for the associated primary resource controller. + * See underlying
+ * method in fabric8 client informer implementation. + * + *

+ * The main goal, is to be able to use limited caches or provide any custom implementation. + *

+ * + *

+ * See {@link BoundedItemStore} and CaffeinBoundedCache + *

+ * + * @return the class of the {@link ItemStore} implementation to use + */ + Class itemStore() default ItemStore.class; + + /** + * The maximum amount of items to return for a single list call when starting the primary resource + * related informers. If this is a not null it will result in paginating for the initial load of + * the informer cache. + */ + long informerListLimit() default NO_LONG_VALUE_SET; + +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerConfiguration.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerConfiguration.java index bca39b189c..8d7b232889 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerConfiguration.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerConfiguration.java @@ -1,85 +1,179 @@ package io.javaoperatorsdk.operator.api.config.informer; -import java.util.Objects; -import java.util.Optional; +import java.util.Collection; +import java.util.Collections; import java.util.Set; +import java.util.stream.Collectors; import io.fabric8.kubernetes.api.model.GenericKubernetesResource; import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.client.informers.cache.ItemStore; -import io.javaoperatorsdk.operator.api.config.DefaultResourceConfiguration; -import io.javaoperatorsdk.operator.api.config.ResourceConfiguration; +import io.javaoperatorsdk.operator.OperatorException; +import io.javaoperatorsdk.operator.ReconcilerUtils; +import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.config.Utils; -import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; -import io.javaoperatorsdk.operator.processing.GroupVersionKind; -import io.javaoperatorsdk.operator.processing.event.source.PrimaryToSecondaryMapper; -import io.javaoperatorsdk.operator.processing.event.source.SecondaryToPrimaryMapper; +import io.javaoperatorsdk.operator.api.reconciler.Constants; +import io.javaoperatorsdk.operator.processing.event.source.cache.BoundedItemStore; 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.javaoperatorsdk.operator.processing.event.source.informer.Mappers; - -import static io.javaoperatorsdk.operator.api.reconciler.Constants.DEFAULT_NAMESPACES_SET; - -public interface InformerConfiguration - extends ResourceConfiguration { - - class DefaultInformerConfiguration extends - DefaultResourceConfiguration implements InformerConfiguration { - - private final PrimaryToSecondaryMapper primaryToSecondaryMapper; - private final SecondaryToPrimaryMapper secondaryToPrimaryMapper; - private final boolean followControllerNamespaceChanges; - private final OnDeleteFilter onDeleteFilter; - private final GroupVersionKind groupVersionKind; - - protected DefaultInformerConfiguration(String labelSelector, - Class resourceClass, - GroupVersionKind groupVersionKind, - PrimaryToSecondaryMapper primaryToSecondaryMapper, - SecondaryToPrimaryMapper secondaryToPrimaryMapper, - Set namespaces, boolean followControllerNamespaceChanges, - OnAddFilter onAddFilter, - OnUpdateFilter onUpdateFilter, - OnDeleteFilter onDeleteFilter, - GenericFilter genericFilter, - ItemStore itemStore, Long informerListLimit) { - super(resourceClass, namespaces, labelSelector, onAddFilter, onUpdateFilter, genericFilter, - itemStore, informerListLimit); - this.followControllerNamespaceChanges = followControllerNamespaceChanges; - this.groupVersionKind = groupVersionKind; - this.primaryToSecondaryMapper = primaryToSecondaryMapper; - this.secondaryToPrimaryMapper = - Objects.requireNonNullElse(secondaryToPrimaryMapper, - Mappers.fromOwnerReference()); - this.onDeleteFilter = onDeleteFilter; - } - @Override - public boolean followControllerNamespaceChanges() { - return followControllerNamespaceChanges; - } +import static io.javaoperatorsdk.operator.api.reconciler.Constants.*; + + +@SuppressWarnings("unused") +public class InformerConfiguration { + private final Builder builder = new Builder(); + private final Class resourceClass; + private final String resourceTypeName; + private String name; + private Set namespaces; + private Boolean followControllerNamespacesOnChange; + private String labelSelector; + private OnAddFilter onAddFilter; + private OnUpdateFilter onUpdateFilter; + private OnDeleteFilter onDeleteFilter; + private GenericFilter genericFilter; + private ItemStore itemStore; + private Long informerListLimit; + + protected InformerConfiguration(Class resourceClass, String name, Set namespaces, + boolean followControllerNamespacesOnChange, + String labelSelector, OnAddFilter onAddFilter, + OnUpdateFilter onUpdateFilter, OnDeleteFilter onDeleteFilter, + GenericFilter genericFilter, ItemStore itemStore, Long informerListLimit) { + this(resourceClass); + this.name = name; + this.namespaces = namespaces; + this.followControllerNamespacesOnChange = followControllerNamespacesOnChange; + this.labelSelector = labelSelector; + this.onAddFilter = onAddFilter; + this.onUpdateFilter = onUpdateFilter; + this.onDeleteFilter = onDeleteFilter; + this.genericFilter = genericFilter; + this.itemStore = itemStore; + this.informerListLimit = informerListLimit; + } - @Override - public SecondaryToPrimaryMapper getSecondaryToPrimaryMapper() { - return secondaryToPrimaryMapper; + private InformerConfiguration(Class resourceClass) { + this.resourceClass = resourceClass; + this.resourceTypeName = resourceClass.isAssignableFrom(GenericKubernetesResource.class) + // in general this is irrelevant now for secondary resources it is used just by controller + // where GenericKubernetesResource now does not apply + ? GenericKubernetesResource.class.getSimpleName() + : ReconcilerUtils.getResourceTypeName(resourceClass); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public static InformerConfiguration.Builder builder( + Class resourceClass) { + return new InformerConfiguration(resourceClass).builder; + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public static InformerConfiguration.Builder builder( + InformerConfiguration original) { + return new InformerConfiguration(original.resourceClass, original.name, original.namespaces, + original.followControllerNamespacesOnChange, original.labelSelector, original.onAddFilter, + original.onUpdateFilter, original.onDeleteFilter, original.genericFilter, + original.itemStore, original.informerListLimit).builder; + } + + public static String ensureValidLabelSelector(String labelSelector) { + // might want to implement validation here? + return labelSelector; + } + + public static boolean allNamespacesWatched(Set namespaces) { + failIfNotValid(namespaces); + return DEFAULT_NAMESPACES_SET.equals(namespaces); + } + + public static boolean currentNamespaceWatched(Set namespaces) { + failIfNotValid(namespaces); + return WATCH_CURRENT_NAMESPACE_SET.equals(namespaces); + } + + public static void failIfNotValid(Set namespaces) { + if (namespaces != null && !namespaces.isEmpty()) { + final var present = namespaces.contains(WATCH_CURRENT_NAMESPACE) + || namespaces.contains(WATCH_ALL_NAMESPACES); + if (!present || namespaces.size() == 1) { + return; + } } + throw new IllegalArgumentException( + "Must specify namespaces. To watch all namespaces, use only '" + + WATCH_ALL_NAMESPACES + + "'. To watch only the namespace in which the operator is deployed, use only '" + + WATCH_CURRENT_NAMESPACE + "'"); + } - @Override - public Optional> onDeleteFilter() { - return Optional.ofNullable(onDeleteFilter); + public static Set ensureValidNamespaces(Collection namespaces) { + if (namespaces != null && !namespaces.isEmpty()) { + return namespaces.stream().map(String::trim).collect(Collectors.toSet()); + } else { + return Constants.DEFAULT_NAMESPACES_SET; } + } + + public static boolean inheritsNamespacesFromController(Set namespaces) { + return SAME_AS_CONTROLLER_NAMESPACES_SET.equals(namespaces); + } + + public Class getResourceClass() { + return resourceClass; + } - @Override - @SuppressWarnings("unchecked") - public

PrimaryToSecondaryMapper

getPrimaryToSecondaryMapper() { - return (PrimaryToSecondaryMapper

) primaryToSecondaryMapper; + public String getResourceTypeName() { + return resourceTypeName; + } + + public String getName() { + return name; + } + + public Set getNamespaces() { + return namespaces; + } + + public boolean watchAllNamespaces() { + return InformerConfiguration.allNamespacesWatched(getNamespaces()); + } + + public boolean watchCurrentNamespace() { + return InformerConfiguration.currentNamespaceWatched(getNamespaces()); + } + + public boolean inheritsNamespacesFromController() { + return inheritsNamespacesFromController(getNamespaces()); + } + + /** + * Computes the effective namespaces based on the set specified by the user, in particular + * retrieves the current namespace from the client when the user specified that they wanted to + * watch the current namespace only. + * + * @return a Set of namespace names the associated controller will watch + */ + public Set getEffectiveNamespaces(ControllerConfiguration controllerConfiguration) { + if (inheritsNamespacesFromController()) { + return controllerConfiguration.getEffectiveNamespaces(); } - public Optional getGroupVersionKind() { - return Optional.ofNullable(groupVersionKind); + var targetNamespaces = getNamespaces(); + if (watchCurrentNamespace()) { + final String namespace = + controllerConfiguration.getConfigurationService().getKubernetesClient().getConfiguration() + .getNamespace(); + if (namespace == null) { + throw new OperatorException( + "Couldn't retrieve the currently connected namespace. Make sure it's correctly set in your ~/.kube/config file, using, e.g. 'kubectl config set-context --namespace='"); + } + targetNamespaces = Collections.singleton(namespace); } + return targetNamespaces; } /** @@ -90,82 +184,151 @@ public Optional getGroupVersionKind() { * * @return if namespace changes should be followed */ - boolean followControllerNamespaceChanges(); + public boolean isFollowControllerNamespacesOnChange() { + return followControllerNamespacesOnChange; + } /** - * Returns the configured {@link SecondaryToPrimaryMapper} which will allow JOSDK to identify - * which secondary resources are associated with a given primary resource in cases where there is - * no explicit reference to the primary resource (e.g. using owner references) in the associated - * secondary resources. + * Retrieves the label selector that is used to filter which resources are actually watched by the + * associated informer. See the official documentation on the + * topic + * for more details on syntax. * - * @return the configured {@link SecondaryToPrimaryMapper} - * @see SecondaryToPrimaryMapper for more explanations on when using such a mapper is useful / - * needed + * @return the label selector filtering watched resources */ - SecondaryToPrimaryMapper getSecondaryToPrimaryMapper(); + public String getLabelSelector() { + return labelSelector; + } - @Override - Optional> onAddFilter(); + public OnAddFilter getOnAddFilter() { + return onAddFilter; + } - @Override - Optional> onUpdateFilter(); + public OnUpdateFilter getOnUpdateFilter() { + return onUpdateFilter; + } - Optional> onDeleteFilter(); + public OnDeleteFilter getOnDeleteFilter() { + return onDeleteFilter; + } - @Override - Optional> genericFilter(); + public GenericFilter getGenericFilter() { + return genericFilter; + } -

PrimaryToSecondaryMapper

getPrimaryToSecondaryMapper(); + /** + * Replaces the item store in informer. See underlying method + * in fabric8 client informer implementation. + * + *

+ * The main goal, is to be able to use limited caches or provide any custom implementation. + *

+ * + *

+ * See {@link BoundedItemStore} and CaffeineBoundedCache + *

+ * + * @return Optional {@link ItemStore} implementation. If present this item store will be used by + * the informers. + */ + public ItemStore getItemStore() { + return itemStore; + } - Optional getGroupVersionKind(); + /** + * The maximum amount of items to return for a single list call when starting an informer. If this + * is a not null it will result in paginating for the initial load of the informer cache. + */ + public Long getInformerListLimit() { + return informerListLimit; + } - @SuppressWarnings("unused") - class InformerConfigurationBuilder { - private final Class resourceClass; - private final GroupVersionKind groupVersionKind; - private PrimaryToSecondaryMapper primaryToSecondaryMapper; - private SecondaryToPrimaryMapper secondaryToPrimaryMapper; - private Set namespaces; - private String labelSelector; - private OnAddFilter onAddFilter; - private OnUpdateFilter onUpdateFilter; - private OnDeleteFilter onDeleteFilter; - private GenericFilter genericFilter; - private boolean inheritControllerNamespacesOnChange = false; - private ItemStore itemStore; - private Long informerListLimit; + @SuppressWarnings("UnusedReturnValue") + public class Builder { - private InformerConfigurationBuilder(Class resourceClass) { - this.resourceClass = resourceClass; - this.groupVersionKind = null; + public InformerConfiguration buildForController() { + // if the informer config uses the default "same as controller" value, reset the namespaces to + // the default set for controllers + if (namespaces == null || namespaces.isEmpty() + || inheritsNamespacesFromController(namespaces)) { + namespaces = Constants.DEFAULT_NAMESPACES_SET; + } + // to avoid potential NPE + followControllerNamespacesOnChange = false; + return InformerConfiguration.this; } - @SuppressWarnings("unchecked") - private InformerConfigurationBuilder(GroupVersionKind groupVersionKind) { - this.resourceClass = (Class) GenericKubernetesResource.class; - this.groupVersionKind = groupVersionKind; + public InformerConfiguration buildForInformerEventSource() { + if (namespaces == null || namespaces.isEmpty()) { + namespaces = Constants.SAME_AS_CONTROLLER_NAMESPACES_SET; + } + if (followControllerNamespacesOnChange == null) { + followControllerNamespacesOnChange = + DEFAULT_FOLLOW_CONTROLLER_NAMESPACES_ON_CHANGE; + } + return InformerConfiguration.this; } - public

InformerConfigurationBuilder withPrimaryToSecondaryMapper( - PrimaryToSecondaryMapper

primaryToSecondaryMapper) { - this.primaryToSecondaryMapper = primaryToSecondaryMapper; + @SuppressWarnings({"unchecked"}) + public InformerConfiguration.Builder initFromAnnotation(Informer informerConfig, + String context) { + if (informerConfig != null) { + + // override default name if more specific one is provided + if (!Constants.NO_VALUE_SET.equals(informerConfig.name())) { + withName(informerConfig.name()); + } + + var namespaces = Set.of(informerConfig.namespaces()); + withNamespaces(namespaces); + + final var fromAnnotation = informerConfig.labelSelector(); + var labelSelector = Constants.NO_VALUE_SET.equals(fromAnnotation) ? null : fromAnnotation; + withLabelSelector(labelSelector); + + withOnAddFilter(Utils.instantiate(informerConfig.onAddFilter(), + OnAddFilter.class, context)); + + withOnUpdateFilter(Utils.instantiate(informerConfig.onUpdateFilter(), + OnUpdateFilter.class, context)); + + withOnDeleteFilter(Utils.instantiate(informerConfig.onDeleteFilter(), + OnDeleteFilter.class, context)); + + withGenericFilter(Utils.instantiate(informerConfig.genericFilter(), + GenericFilter.class, + context)); + + withFollowControllerNamespacesOnChange( + informerConfig.followControllerNamespacesOnChange()); + + withItemStore(Utils.instantiate(informerConfig.itemStore(), + ItemStore.class, context)); + + final var informerListLimitValue = informerConfig.informerListLimit(); + final var informerListLimit = + informerListLimitValue == Constants.NO_LONG_VALUE_SET ? null : informerListLimitValue; + withInformerListLimit(informerListLimit); + } return this; } - public InformerConfigurationBuilder withSecondaryToPrimaryMapper( - SecondaryToPrimaryMapper secondaryToPrimaryMapper) { - this.secondaryToPrimaryMapper = secondaryToPrimaryMapper; + public Builder withName(String name) { + InformerConfiguration.this.name = name; return this; } - public InformerConfigurationBuilder withNamespaces(String... namespaces) { - return withNamespaces( - namespaces != null ? Set.of(namespaces) : DEFAULT_NAMESPACES_SET); + public Builder withNamespaces(Set namespaces) { + InformerConfiguration.this.namespaces = + ensureValidNamespaces(namespaces); + return this; } - public InformerConfigurationBuilder withNamespaces(Set namespaces) { - return withNamespaces(namespaces, false); + public Set namespaces() { + return Set.copyOf(namespaces); } /** @@ -178,31 +341,27 @@ public InformerConfigurationBuilder withNamespaces(Set namespaces) { * namespaces, {@code false} otherwise * @return the builder instance so that calls can be chained fluently */ - public InformerConfigurationBuilder withNamespaces(Set namespaces, - boolean followChanges) { - this.namespaces = namespaces != null ? namespaces : DEFAULT_NAMESPACES_SET; - this.inheritControllerNamespacesOnChange = true; + public Builder withNamespaces(Set namespaces, boolean followChanges) { + withNamespaces(namespaces).withFollowControllerNamespacesOnChange(followChanges); return this; } - /** - * Configures the informer to watch and track the same namespaces as the parent - * {@link io.javaoperatorsdk.operator.processing.Controller}, meaning that the informer will be - * restarted to watch the new namespaces if the parent controller's namespace configuration - * changes. - * - * @param context {@link EventSourceContext} from which the parent - * {@link io.javaoperatorsdk.operator.processing.Controller}'s configuration is retrieved - * @param

the primary resource type associated with the parent controller - * @return the builder instance so that calls can be chained fluently - */ - public

InformerConfigurationBuilder withNamespacesInheritedFromController( - EventSourceContext

context) { - namespaces = context.getControllerConfiguration().getEffectiveNamespaces(); - this.inheritControllerNamespacesOnChange = true; + public Builder withNamespacesInheritedFromController() { + withNamespaces(SAME_AS_CONTROLLER_NAMESPACES_SET); + return this; + } + + public Builder withWatchAllNamespaces() { + withNamespaces(WATCH_ALL_NAMESPACE_SET); + return this; + } + + public Builder withWatchCurrentNamespace() { + withNamespaces(WATCH_CURRENT_NAMESPACE_SET); return this; } + /** * Whether the associated informer should track changes made to the parent * {@link io.javaoperatorsdk.operator.processing.Controller}'s namespaces configuration. @@ -211,107 +370,50 @@ public

InformerConfigurationBuilder withNamespacesInh * controller's namespaces are reconfigured, {@code false} otherwise * @return the builder instance so that calls can be chained fluently */ - public InformerConfigurationBuilder followNamespaceChanges(boolean followChanges) { - this.inheritControllerNamespacesOnChange = followChanges; + public Builder withFollowControllerNamespacesOnChange(boolean followChanges) { + InformerConfiguration.this.followControllerNamespacesOnChange = + followChanges; return this; } - public InformerConfigurationBuilder withLabelSelector(String labelSelector) { - this.labelSelector = labelSelector; + public Builder withLabelSelector(String labelSelector) { + InformerConfiguration.this.labelSelector = + ensureValidLabelSelector(labelSelector); return this; } - public InformerConfigurationBuilder withOnAddFilter(OnAddFilter onAddFilter) { - this.onAddFilter = onAddFilter; + public Builder withOnAddFilter( + OnAddFilter onAddFilter) { + InformerConfiguration.this.onAddFilter = onAddFilter; return this; } - public InformerConfigurationBuilder withOnUpdateFilter( + public Builder withOnUpdateFilter( OnUpdateFilter onUpdateFilter) { - this.onUpdateFilter = onUpdateFilter; + InformerConfiguration.this.onUpdateFilter = onUpdateFilter; return this; } - public InformerConfigurationBuilder withOnDeleteFilter( + public Builder withOnDeleteFilter( OnDeleteFilter onDeleteFilter) { - this.onDeleteFilter = onDeleteFilter; + InformerConfiguration.this.onDeleteFilter = onDeleteFilter; return this; } - public InformerConfigurationBuilder withGenericFilter( + public Builder withGenericFilter( GenericFilter genericFilter) { - this.genericFilter = genericFilter; + InformerConfiguration.this.genericFilter = genericFilter; return this; } - public InformerConfigurationBuilder withItemStore(ItemStore itemStore) { - this.itemStore = itemStore; + public Builder withItemStore(ItemStore itemStore) { + InformerConfiguration.this.itemStore = itemStore; return this; } - /** - * Sets a max page size limit when starting the informer. This will result in pagination while - * populating the cache. This means that longer lists will take multiple requests to fetch. See - * {@link io.fabric8.kubernetes.client.dsl.Informable#withLimit(Long)} for more details. - * - * @param informerListLimit null (the default) results in no pagination - */ - public InformerConfigurationBuilder withInformerListLimit(Long informerListLimit) { - this.informerListLimit = informerListLimit; + public Builder withInformerListLimit(Long informerListLimit) { + InformerConfiguration.this.informerListLimit = informerListLimit; return this; } - - public InformerConfiguration build() { - return new DefaultInformerConfiguration<>(labelSelector, resourceClass, groupVersionKind, - primaryToSecondaryMapper, - secondaryToPrimaryMapper, - namespaces, inheritControllerNamespacesOnChange, onAddFilter, onUpdateFilter, - onDeleteFilter, genericFilter, itemStore, informerListLimit); - } - } - - static InformerConfigurationBuilder from( - Class resourceClass) { - return new InformerConfigurationBuilder<>(resourceClass); - } - - /** - * * For the case when want to use {@link GenericKubernetesResource} - */ - static InformerConfigurationBuilder from( - GroupVersionKind groupVersionKind) { - return new InformerConfigurationBuilder<>(groupVersionKind); - } - - /** - * Creates a configuration builder that inherits namespaces from the controller and follows - * namespaces changes. - * - * @param resourceClass secondary resource class - * @param eventSourceContext of the initializer - * @return builder - * @param secondary resource type - */ - static InformerConfigurationBuilder from( - Class resourceClass, EventSourceContext eventSourceContext) { - return new InformerConfigurationBuilder<>(resourceClass) - .withNamespacesInheritedFromController(eventSourceContext); - } - - /** - * * For the case when want to use {@link GenericKubernetesResource} - */ - @SuppressWarnings("unchecked") - static InformerConfigurationBuilder from( - GroupVersionKind groupVersionKind, EventSourceContext eventSourceContext) { - return new InformerConfigurationBuilder(groupVersionKind) - .withNamespacesInheritedFromController(eventSourceContext); - } - - @SuppressWarnings("unchecked") - @Override - default Class getResourceClass() { - return (Class) Utils.getFirstTypeArgumentFromSuperClassOrInterface(getClass(), - InformerConfiguration.class); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerEventSourceConfiguration.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerEventSourceConfiguration.java new file mode 100644 index 0000000000..9ad6dded4c --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/informer/InformerEventSourceConfiguration.java @@ -0,0 +1,225 @@ +package io.javaoperatorsdk.operator.api.config.informer; + +import java.util.Objects; +import java.util.Optional; +import java.util.function.Consumer; + +import io.fabric8.kubernetes.api.model.GenericKubernetesResource; +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.javaoperatorsdk.operator.api.config.Informable; +import io.javaoperatorsdk.operator.processing.GroupVersionKind; +import io.javaoperatorsdk.operator.processing.event.source.PrimaryToSecondaryMapper; +import io.javaoperatorsdk.operator.processing.event.source.SecondaryToPrimaryMapper; +import io.javaoperatorsdk.operator.processing.event.source.informer.Mappers; + +public interface InformerEventSourceConfiguration + extends Informable { + + static Builder from( + Class resourceClass, Class primaryResourceClass) { + return new Builder<>(resourceClass, primaryResourceClass); + } + + static Builder from( + GroupVersionKind groupVersionKind, Class primaryResourceClass) { + return new Builder<>(groupVersionKind, primaryResourceClass); + } + + /** + * Used in case the watched namespaces are changed dynamically, thus when operator is running (See + * {@link io.javaoperatorsdk.operator.RegisteredController}). If true, changing the target + * namespaces of a controller would result to change target namespaces for the + * InformerEventSource. + * + * @return if namespace changes should be followed + */ + default boolean followControllerNamespaceChanges() { + return getInformerConfig().isFollowControllerNamespacesOnChange(); + } + + /** + * Returns the configured {@link SecondaryToPrimaryMapper} which will allow JOSDK to identify + * which secondary resources are associated with a given primary resource in cases where there is + * no explicit reference to the primary resource (e.g. using owner references) in the associated + * secondary resources. + * + * @return the configured {@link SecondaryToPrimaryMapper} + * @see SecondaryToPrimaryMapper for more explanations on when using such a mapper is useful / + * needed + */ + SecondaryToPrimaryMapper getSecondaryToPrimaryMapper(); + +

PrimaryToSecondaryMapper

getPrimaryToSecondaryMapper(); + + Optional getGroupVersionKind(); + + default String name() { + return getInformerConfig().getName(); + } + + /** + * Optional, specific kubernetes client, typically to connect to a different cluster than the rest + * of the operator. Note that this is solely for multi cluster support. + */ + default Optional getKubernetesClient() { + return Optional.empty(); + } + + class DefaultInformerEventSourceConfiguration + implements InformerEventSourceConfiguration { + private final PrimaryToSecondaryMapper primaryToSecondaryMapper; + private final SecondaryToPrimaryMapper secondaryToPrimaryMapper; + private final GroupVersionKind groupVersionKind; + private final InformerConfiguration informerConfig; + private final KubernetesClient kubernetesClient; + + protected DefaultInformerEventSourceConfiguration( + GroupVersionKind groupVersionKind, + PrimaryToSecondaryMapper primaryToSecondaryMapper, + SecondaryToPrimaryMapper secondaryToPrimaryMapper, + InformerConfiguration informerConfig, + KubernetesClient kubernetesClient) { + this.informerConfig = Objects.requireNonNull(informerConfig); + this.groupVersionKind = groupVersionKind; + this.primaryToSecondaryMapper = primaryToSecondaryMapper; + this.secondaryToPrimaryMapper = secondaryToPrimaryMapper; + this.kubernetesClient = kubernetesClient; + } + + @Override + public InformerConfiguration getInformerConfig() { + return informerConfig; + } + + @Override + public SecondaryToPrimaryMapper getSecondaryToPrimaryMapper() { + return secondaryToPrimaryMapper; + } + + @Override + @SuppressWarnings("unchecked") + public

PrimaryToSecondaryMapper

getPrimaryToSecondaryMapper() { + return (PrimaryToSecondaryMapper

) primaryToSecondaryMapper; + } + + @Override + public Optional getGroupVersionKind() { + return Optional.ofNullable(groupVersionKind); + } + + @Override + public Optional getKubernetesClient() { + return Optional.ofNullable(kubernetesClient); + } + } + + @SuppressWarnings({"unused", "UnusedReturnValue"}) + class Builder { + + private final Class resourceClass; + private final GroupVersionKind groupVersionKind; + private final Class primaryResourceClass; + private final InformerConfiguration.Builder config; + private String name; + private PrimaryToSecondaryMapper primaryToSecondaryMapper; + private SecondaryToPrimaryMapper secondaryToPrimaryMapper; + private KubernetesClient kubernetesClient; + + private Builder(Class resourceClass, + Class primaryResourceClass) { + this(resourceClass, primaryResourceClass, null); + } + + @SuppressWarnings("unchecked") + private Builder(GroupVersionKind groupVersionKind, + Class primaryResourceClass) { + this((Class) GenericKubernetesResource.class, primaryResourceClass, groupVersionKind); + } + + private Builder(Class resourceClass, + Class primaryResourceClass, GroupVersionKind groupVersionKind) { + this.resourceClass = resourceClass; + this.groupVersionKind = groupVersionKind; + this.primaryResourceClass = primaryResourceClass; + this.config = InformerConfiguration.builder(resourceClass); + } + + public Builder withInformerConfiguration( + Consumer.Builder> configurator) { + configurator.accept(config); + return this; + } + + public Builder withName(String name) { + this.name = name; + config.withName(name); + return this; + } + + public

Builder withPrimaryToSecondaryMapper( + PrimaryToSecondaryMapper

primaryToSecondaryMapper) { + this.primaryToSecondaryMapper = primaryToSecondaryMapper; + return this; + } + + public Builder withSecondaryToPrimaryMapper( + SecondaryToPrimaryMapper secondaryToPrimaryMapper) { + this.secondaryToPrimaryMapper = secondaryToPrimaryMapper; + return this; + } + + /** + * Use this is case want to create an InformerEventSource that handles resources from different + * cluster. + */ + public Builder withKubernetesClient( + KubernetesClient kubernetesClient) { + this.kubernetesClient = kubernetesClient; + return this; + } + + public String getName() { + return name; + } + + public SecondaryToPrimaryMapper getSecondaryToPrimaryMapper() { + return secondaryToPrimaryMapper; + } + + public void updateFrom(InformerConfiguration informerConfig) { + if (informerConfig != null) { + final var informerConfigName = informerConfig.getName(); + if (informerConfigName != null) { + this.name = informerConfigName; + } + config.withNamespaces(informerConfig.getNamespaces()) + .withFollowControllerNamespacesOnChange( + informerConfig.isFollowControllerNamespacesOnChange()) + .withLabelSelector(informerConfig.getLabelSelector()) + .withItemStore(informerConfig.getItemStore()) + .withOnAddFilter(informerConfig.getOnAddFilter()) + .withOnUpdateFilter(informerConfig.getOnUpdateFilter()) + .withOnDeleteFilter(informerConfig.getOnDeleteFilter()) + .withGenericFilter(informerConfig.getGenericFilter()) + .withInformerListLimit(informerConfig.getInformerListLimit()); + } + } + + public InformerEventSourceConfiguration build() { + if (groupVersionKind != null + && !GenericKubernetesResource.class.isAssignableFrom(resourceClass)) { + throw new IllegalStateException( + "If GroupVersionKind is set the resource type must be GenericKubernetesDependentResource"); + } + + return new DefaultInformerEventSourceConfiguration<>( + groupVersionKind, + primaryToSecondaryMapper, + Objects.requireNonNullElse(secondaryToPrimaryMapper, + Mappers.fromOwnerReferences(HasMetadata.getApiVersion(primaryResourceClass), + HasMetadata.getKind(primaryResourceClass), false)), + config.buildForInformerEventSource(), kubernetesClient); + } + } +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/workflow/WorkflowSpec.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/workflow/WorkflowSpec.java new file mode 100644 index 0000000000..72d50f8050 --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/workflow/WorkflowSpec.java @@ -0,0 +1,15 @@ +package io.javaoperatorsdk.operator.api.config.workflow; + +import java.util.List; + +import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceSpec; + +public interface WorkflowSpec { + + @SuppressWarnings("rawtypes") + List getDependentResourceSpecs(); + + boolean isExplicitInvocation(); + + boolean handleExceptionsInReconciler(); +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/monitoring/Metrics.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/monitoring/Metrics.java index 42fee488d7..bb34e5f760 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/monitoring/Metrics.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/monitoring/Metrics.java @@ -1,6 +1,5 @@ package io.javaoperatorsdk.operator.api.monitoring; -import java.util.Collections; import java.util.Map; import io.fabric8.kubernetes.api.model.HasMetadata; @@ -37,16 +36,6 @@ default void controllerRegistered(Controller controller) */ default void receivedEvent(Event event, Map metadata) {} - /** - * @param metadata additional metadata - * @param resourceID of primary resource - * @param retryInfo for current execution - * @deprecated Use {@link #reconcileCustomResource(HasMetadata, RetryInfo, Map)} instead - */ - @Deprecated(forRemoval = true) - @SuppressWarnings("unused") - default void reconcileCustomResource(ResourceID resourceID, RetryInfo retryInfo, - Map metadata) {} /** * Called right before a resource is dispatched to the ExecutorService for reconciliation. @@ -56,19 +45,6 @@ default void reconcileCustomResource(ResourceID resourceID, RetryInfo retryInfo, * @param metadata metadata associated with the resource being processed */ default void reconcileCustomResource(HasMetadata resource, RetryInfo retryInfo, - Map metadata) { - reconcileCustomResource(ResourceID.fromResource(resource), retryInfo, metadata); - } - - /** - * @param exception actual exception - * @param metadata additional metadata - * @param resourceID of primary resource - * @deprecated Use {@link #failedReconciliation(HasMetadata, Exception, Map)} instead - */ - @Deprecated(forRemoval = true) - @SuppressWarnings("unused") - default void failedReconciliation(ResourceID resourceID, Exception exception, Map metadata) {} /** @@ -81,9 +57,7 @@ default void failedReconciliation(ResourceID resourceID, Exception exception, * @param metadata metadata associated with the resource being processed */ default void failedReconciliation(HasMetadata resource, Exception exception, - Map metadata) { - failedReconciliation(ResourceID.fromResource(resource), exception, metadata); - } + Map metadata) {} default void reconciliationExecutionStarted(HasMetadata resource, Map metadata) {} @@ -91,14 +65,6 @@ default void reconciliationExecutionStarted(HasMetadata resource, Map metadata) {} - /** - * @param resourceID of primary resource - * @deprecated Use (and implement) {@link #cleanupDoneFor(ResourceID, Map)} instead - */ - @Deprecated - default void cleanupDoneFor(ResourceID resourceID) { - cleanupDoneFor(resourceID, Collections.emptyMap()); - } /** * Called when the resource associated with the specified {@link ResourceID} has been successfully @@ -109,24 +75,6 @@ default void cleanupDoneFor(ResourceID resourceID) { */ default void cleanupDoneFor(ResourceID resourceID, Map metadata) {} - /** - * @param resourceID of primary resource - * @deprecated Use (and implement) {@link #finishedReconciliation(ResourceID, Map)} instead - */ - @Deprecated - default void finishedReconciliation(ResourceID resourceID) { - finishedReconciliation(resourceID, Collections.emptyMap()); - } - - /** - * @param resourceID of primary resource - * @param metadata additional metadata - * @deprecated Use {@link #finishedReconciliation(HasMetadata, Map)} instead - */ - @Deprecated(forRemoval = true) - @SuppressWarnings("unused") - default void finishedReconciliation(ResourceID resourceID, Map metadata) {} - /** * Called when the * {@link io.javaoperatorsdk.operator.api.reconciler.Reconciler#reconcile(HasMetadata, Context)} @@ -136,9 +84,7 @@ default void finishedReconciliation(ResourceID resourceID, Map m * @param resource the {@link ResourceID} associated with the resource being processed * @param metadata metadata associated with the resource being processed */ - default void finishedReconciliation(HasMetadata resource, Map metadata) { - finishedReconciliation(ResourceID.fromResource(resource), metadata); - } + default void finishedReconciliation(HasMetadata resource, Map metadata) {} /** * Encapsulates the information about a controller execution i.e. a call to either diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Cleaner.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Cleaner.java index 1e75764f80..cd683fbc31 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Cleaner.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Cleaner.java @@ -27,6 +27,6 @@ public interface Cleaner

{ * that it can be safely deleted. * @see DeleteControl#noFinalizerRemoval() */ - DeleteControl cleanup(P resource, Context

context); + DeleteControl cleanup(P resource, Context

context) throws Exception; } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Constants.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Constants.java index 9876fda558..8003d8f836 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Constants.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Constants.java @@ -5,24 +5,27 @@ public final class Constants { - public static final Set DEFAULT_NAMESPACES_SET = + public static final String WATCH_CURRENT_NAMESPACE = "JOSDK_WATCH_CURRENT"; + public static final String WATCH_ALL_NAMESPACES = "JOSDK_ALL_NAMESPACES"; + public static final String SAME_AS_CONTROLLER = "JOSDK_SAME_AS_CONTROLLER"; + + public static final Set WATCH_ALL_NAMESPACE_SET = Collections.singleton(Constants.WATCH_ALL_NAMESPACES); public static final Set WATCH_CURRENT_NAMESPACE_SET = Collections.singleton(Constants.WATCH_CURRENT_NAMESPACE); - public static final Set SAME_AS_CONTROLLER_NAMESPACES_SET = Collections.singleton(Constants.SAME_AS_CONTROLLER); + public static final Set DEFAULT_NAMESPACES_SET = WATCH_ALL_NAMESPACE_SET; + public static final String NO_VALUE_SET = ""; public static final long NO_LONG_VALUE_SET = -1L; - public static final String WATCH_CURRENT_NAMESPACE = "JOSDK_WATCH_CURRENT"; - public static final String WATCH_ALL_NAMESPACES = "JOSDK_ALL_NAMESPACES"; public static final long NO_MAX_RECONCILIATION_INTERVAL = -1L; - public static final String SAME_AS_CONTROLLER = "JOSDK_SAME_AS_CONTROLLER"; public static final String RESOURCE_GVK_KEY = "josdk.resource.gvk"; public static final String CONTROLLER_NAME = "controller.name"; + public static final boolean DEFAULT_FOLLOW_CONTROLLER_NAMESPACES_ON_CHANGE = true; private Constants() {} } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Context.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Context.java index e157ed5fd7..0134ea0a04 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Context.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Context.java @@ -8,7 +8,7 @@ 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.reconciler.dependent.managed.ManagedDependentResourceContext; +import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.ManagedWorkflowAndDependentResourceContext; import io.javaoperatorsdk.operator.processing.event.EventSourceRetriever; import io.javaoperatorsdk.operator.processing.event.source.IndexerResourceCache; @@ -17,7 +17,7 @@ public interface Context

{ Optional getRetryInfo(); default Optional getSecondaryResource(Class expectedType) { - return getSecondaryResource(expectedType, (String) null); + return getSecondaryResource(expectedType, null); } Set getSecondaryResources(Class expectedType); @@ -26,15 +26,18 @@ default Stream getSecondaryResourcesAsStream(Class expectedType) { return getSecondaryResources(expectedType).stream(); } - @Deprecated(forRemoval = true) Optional getSecondaryResource(Class expectedType, String eventSourceName); - Optional getSecondaryResource(Class expectedType, - ResourceDiscriminator discriminator); - ControllerConfiguration

getControllerConfiguration(); - ManagedDependentResourceContext managedDependentResourceContext(); + /** + * Retrieve the {@link ManagedWorkflowAndDependentResourceContext} used to interact with + * {@link io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource}s and associated + * {@link io.javaoperatorsdk.operator.processing.dependent.workflow.Workflow} + * + * @return the {@link ManagedWorkflowAndDependentResourceContext} + */ + ManagedWorkflowAndDependentResourceContext managedWorkflowAndDependentResourceContext(); EventSourceRetriever

eventSourceRetriever(); @@ -51,5 +54,18 @@ Optional getSecondaryResource(Class expectedType, * @return the {@link IndexerResourceCache} associated with the associated {@link Reconciler} for * this context */ + @SuppressWarnings("unused") IndexedResourceCache

getPrimaryCache(); + + /** + * Determines whether a new reconciliation will be triggered right after the current + * reconciliation is finished. This allows to optimize certain situations, helping avoid unneeded + * API calls. A reconciler might, for example, skip updating the status when it's known another + * reconciliation is already scheduled, which would in turn trigger another status update, thus + * rendering the current one moot. + * + * @return {@code true} is another reconciliation is already scheduled, {@code false} otherwise + **/ + boolean isNextReconciliationImminent(); + } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ControllerConfiguration.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ControllerConfiguration.java index c064e669e0..eb709b0d5a 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ControllerConfiguration.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ControllerConfiguration.java @@ -6,20 +6,13 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import io.fabric8.kubernetes.client.informers.cache.ItemStore; -import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; +import io.javaoperatorsdk.operator.api.config.informer.Informer; import io.javaoperatorsdk.operator.processing.event.rate.LinearRateLimiter; import io.javaoperatorsdk.operator.processing.event.rate.RateLimiter; -import io.javaoperatorsdk.operator.processing.event.source.cache.BoundedItemStore; -import io.javaoperatorsdk.operator.processing.event.source.controller.ResourceEventFilter; -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 static io.javaoperatorsdk.operator.api.config.ControllerConfiguration.CONTROLLER_NAME_AS_FIELD_MANAGER; -import static io.javaoperatorsdk.operator.api.reconciler.Constants.NO_LONG_VALUE_SET; @Inherited @Retention(RetentionPolicy.RUNTIME) @@ -28,6 +21,8 @@ String name() default Constants.NO_VALUE_SET; + Informer informer() default @Informer; + /** * Optional finalizer name, if it is not provided, one will be automatically generated. Note that * finalizers are only added when Reconciler implement {@link Cleaner} interface and/or at least @@ -47,57 +42,6 @@ */ boolean generationAwareEventProcessing() default true; - /** - * Specified which namespaces this Controller monitors for custom resources events. If no - * namespace is specified then the controller will monitor all namespaces by default. - * - * @return the array of namespaces this controller monitors - */ - String[] namespaces() default Constants.WATCH_ALL_NAMESPACES; - - /** - * Optional label selector used to identify the set of custom resources the controller will acc - * upon. The label selector can be made of multiple comma separated requirements that acts as a - * logical AND operator. - * - * @return the label selector - */ - String labelSelector() default Constants.NO_VALUE_SET; - - /** - * @deprecated Use onAddFilter, onUpdateFilter instead. - * - *

- * Resource event filters only applies on events of the main custom resource. Not on - * events from other event sources nor the periodic events. - *

- * - * @return the list of event filters. - */ - @Deprecated(forRemoval = true) - Class[] eventFilters() default {}; - - /** - * Filter of onAdd events of resources. - * - * @return on-add filter - **/ - Class onAddFilter() default OnAddFilter.class; - - /** - * Filter of onUpdate events of resources. - * - * @return on-update filter - */ - Class onUpdateFilter() default OnUpdateFilter.class; - - /** - * Filter applied to all operations (add, update, delete). Used to ignore some resources. - * - * @return generic filter - **/ - Class genericFilter() default GenericFilter.class; - /** * Optional configuration of the maximal interval the SDK will wait for a reconciliation request * to happen before one will be automatically triggered. @@ -107,15 +51,6 @@ MaxReconciliationInterval maxReconciliationInterval() default @MaxReconciliationInterval( interval = MaxReconciliationInterval.DEFAULT_INTERVAL); - - /** - * Optional list of {@link Dependent} configurations which associate a resource type to a - * {@link io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource} implementation - * - * @return the array of {@link Dependent} configurations - */ - Dependent[] dependents() default {}; - /** * Optional {@link Retry} implementation for the associated controller to use. * @@ -132,25 +67,6 @@ MaxReconciliationInterval maxReconciliationInterval() default @MaxReconciliation */ Class rateLimiter() default LinearRateLimiter.class; - /** - * Replaces the item store used by the informer for the associated primary resource controller. - * See underlying - * method in fabric8 client informer implementation. - * - *

- * The main goal, is to be able to use limited caches or provide any custom implementation. - *

- * - *

- * See {@link BoundedItemStore} and CaffeinBoundedCache - *

- * - * @return the class of the {@link ItemStore} implementation to use - */ - Class itemStore() default ItemStore.class; - /** * Retrieves the name used to assign as field manager for * Server-Side @@ -159,11 +75,4 @@ MaxReconciliationInterval maxReconciliationInterval() default @MaxReconciliation * @return the name used as field manager for SSA operations */ String fieldManager() default CONTROLLER_NAME_AS_FIELD_MANAGER; - - /** - * The maximum amount of items to return for a single list call when starting the primary resource - * related informers. If this is a not null it will result in paginating for the initial load of - * the informer cache. - */ - long informerListLimit() default NO_LONG_VALUE_SET; } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/DefaultContext.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/DefaultContext.java index 2b0f20ef33..45fc3705e6 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/DefaultContext.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/DefaultContext.java @@ -9,10 +9,12 @@ 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.reconciler.dependent.managed.DefaultManagedDependentResourceContext; -import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.ManagedDependentResourceContext; +import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.DefaultManagedWorkflowAndDependentResourceContext; +import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.ManagedWorkflowAndDependentResourceContext; import io.javaoperatorsdk.operator.processing.Controller; import io.javaoperatorsdk.operator.processing.event.EventSourceRetriever; +import io.javaoperatorsdk.operator.processing.event.NoEventSourceForClassException; +import io.javaoperatorsdk.operator.processing.event.ResourceID; public class DefaultContext

implements Context

{ @@ -20,14 +22,15 @@ public class DefaultContext

implements Context

{ private final Controller

controller; private final P primaryResource; private final ControllerConfiguration

controllerConfiguration; - private final DefaultManagedDependentResourceContext defaultManagedDependentResourceContext; + private final DefaultManagedWorkflowAndDependentResourceContext

defaultManagedDependentResourceContext; public DefaultContext(RetryInfo retryInfo, Controller

controller, P primaryResource) { this.retryInfo = retryInfo; this.controller = controller; this.primaryResource = primaryResource; this.controllerConfiguration = controller.getConfiguration(); - this.defaultManagedDependentResourceContext = new DefaultManagedDependentResourceContext(); + this.defaultManagedDependentResourceContext = + new DefaultManagedWorkflowAndDependentResourceContext<>(controller, primaryResource, this); } @Override @@ -42,28 +45,44 @@ public Set getSecondaryResources(Class expectedType) { @Override public IndexedResourceCache

getPrimaryCache() { - return controller.getEventSourceManager().getControllerResourceEventSource(); + return controller.getEventSourceManager().getControllerEventSource(); + } + + @Override + public boolean isNextReconciliationImminent() { + return controller.getEventProcessor() + .isNextReconciliationImminent(ResourceID.fromResource(primaryResource)); } @Override public Stream getSecondaryResourcesAsStream(Class expectedType) { - return controller.getEventSourceManager().getResourceEventSourcesFor(expectedType).stream() + return controller.getEventSourceManager().getEventSourcesFor(expectedType).stream() .map(es -> es.getSecondaryResources(primaryResource)) .flatMap(Set::stream); } @Override public Optional getSecondaryResource(Class expectedType, String eventSourceName) { - return controller - .getEventSourceManager() - .getResourceEventSourceFor(expectedType, eventSourceName) - .getSecondaryResource(primaryResource); - } - - @Override - public Optional getSecondaryResource(Class expectedType, - ResourceDiscriminator discriminator) { - return discriminator.distinguish(expectedType, primaryResource, this); + try { + return controller + .getEventSourceManager() + .getEventSourceFor(expectedType, eventSourceName) + .getSecondaryResource(primaryResource); + } catch (NoEventSourceForClassException e) { + /* + * If a workflow has an activation condition there can be event sources which are only + * registered if the activation condition holds, but to provide a consistent API we return an + * Optional instead of throwing an exception. + * + * Note that not only the resource which has an activation condition might not be registered + * but dependents which depend on it. + */ + if (eventSourceName == null && controller.workflowContainsDependentForType(expectedType)) { + return Optional.empty(); + } else { + throw e; + } + } } @Override @@ -72,7 +91,7 @@ public ControllerConfiguration

getControllerConfiguration() { } @Override - public ManagedDependentResourceContext managedDependentResourceContext() { + public ManagedWorkflowAndDependentResourceContext managedWorkflowAndDependentResourceContext() { return defaultManagedDependentResourceContext; } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ErrorStatusHandler.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ErrorStatusHandler.java deleted file mode 100644 index c7bd09a930..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ErrorStatusHandler.java +++ /dev/null @@ -1,28 +0,0 @@ -package io.javaoperatorsdk.operator.api.reconciler; - -import io.fabric8.kubernetes.api.model.HasMetadata; - -public interface ErrorStatusHandler

{ - - /** - *

- * Reconciler can implement this interface in order to update the status sub-resource in the case - * an exception in thrown. In that case - * {@link #updateErrorStatus(HasMetadata, Context, Exception)} is called automatically. - *

- * The result of the method call is used to make a status update on the custom resource. This is - * always a sub-resource update request, so no update on custom resource itself (like spec of - * metadata) happens. Note that this update request will also produce an event, and will result in - * a reconciliation if the controller is not generation aware. - *

- * Note that the scope of this feature is only the reconcile method of the reconciler, since there - * should not be updates on custom resource after it is marked for deletion. - * - * @param resource to update the status on - * @param context the current context - * @param e exception thrown from the reconciler - * @return the updated resource - */ - ErrorStatusUpdateControl

updateErrorStatus(P resource, Context

context, Exception e); - -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ErrorStatusUpdateControl.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ErrorStatusUpdateControl.java index 48c0e32946..e9073d613c 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ErrorStatusUpdateControl.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ErrorStatusUpdateControl.java @@ -9,24 +9,32 @@ public class ErrorStatusUpdateControl

extends BaseControl> { private final P resource; - private final boolean patch; private boolean noRetry = false; + private final boolean defaultErrorProcessing; public static ErrorStatusUpdateControl patchStatus(T resource) { - return new ErrorStatusUpdateControl<>(resource, true); + return new ErrorStatusUpdateControl<>(resource); } - public static ErrorStatusUpdateControl updateStatus(T resource) { - return new ErrorStatusUpdateControl<>(resource, false); + public static ErrorStatusUpdateControl noStatusUpdate() { + return new ErrorStatusUpdateControl<>(null); } - public static ErrorStatusUpdateControl noStatusUpdate() { + /** + * No special processing of the error, the error will be thrown and default error handling will + * apply + */ + public static ErrorStatusUpdateControl defaultErrorProcessing() { return new ErrorStatusUpdateControl<>(null, true); } - private ErrorStatusUpdateControl(P resource, boolean patch) { + private ErrorStatusUpdateControl(P resource) { + this(resource, false); + } + + private ErrorStatusUpdateControl(P resource, boolean defaultErrorProcessing) { this.resource = resource; - this.patch = patch; + this.defaultErrorProcessing = defaultErrorProcessing; } /** @@ -35,6 +43,9 @@ private ErrorStatusUpdateControl(P resource, boolean patch) { * @return ErrorStatusUpdateControl */ public ErrorStatusUpdateControl

withNoRetry() { + if (defaultErrorProcessing) { + throw new IllegalStateException("Cannot set no-retry for default error processing"); + } this.noRetry = true; return this; } @@ -47,8 +58,8 @@ public boolean isNoRetry() { return noRetry; } - public boolean isPatch() { - return patch; + public boolean isDefaultErrorProcessing() { + return defaultErrorProcessing; } /** diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/EventSourceContext.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/EventSourceContext.java index e8062e9651..4f0f08b3b8 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/EventSourceContext.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/EventSourceContext.java @@ -16,13 +16,16 @@ public class EventSourceContext

{ private final IndexerResourceCache

primaryCache; private final ControllerConfiguration

controllerConfiguration; private final KubernetesClient client; + private final Class

primaryResourceClass; public EventSourceContext(IndexerResourceCache

primaryCache, ControllerConfiguration

controllerConfiguration, - KubernetesClient client) { + KubernetesClient client, + Class

primaryResourceClass) { this.primaryCache = primaryCache; this.controllerConfiguration = controllerConfiguration; this.client = client; + this.primaryResourceClass = primaryResourceClass; } /** @@ -54,4 +57,8 @@ public ControllerConfiguration

getControllerConfiguration() { public KubernetesClient getClient() { return client; } + + public Class

getPrimaryResourceClass() { + return primaryResourceClass; + } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/EventSourceInitializer.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/EventSourceInitializer.java deleted file mode 100644 index 09c1687e1e..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/EventSourceInitializer.java +++ /dev/null @@ -1,89 +0,0 @@ -package io.javaoperatorsdk.operator.api.reconciler; - -import java.util.*; - -import io.fabric8.kubernetes.api.model.HasMetadata; -import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; -import io.javaoperatorsdk.operator.processing.dependent.workflow.Workflow; -import io.javaoperatorsdk.operator.processing.event.source.EventSource; -import io.javaoperatorsdk.operator.processing.event.source.ResourceEventSource; - -/** - * An interface that a {@link Reconciler} can implement to have the SDK register the provided - * {@link EventSource} - * - * @param

the primary resource type handled by the associated {@link Reconciler} - */ -public interface EventSourceInitializer

{ - - /** - * Prepares a map of {@link EventSource} implementations keyed by the name with which they need to - * be registered by the SDK. - * - * @param context a {@link EventSourceContext} providing access to information useful to event - * sources - * @return a map of event sources to register - */ - Map prepareEventSources(EventSourceContext

context); - - /** - * Utility method to easily create map with generated name for event sources. This is for the use - * case when the event sources are not access explicitly by name in the reconciler. - * - * @param eventSources to name - * @return even source with default names - */ - static Map nameEventSources(EventSource... eventSources) { - Map eventSourceMap = new HashMap<>(eventSources.length); - for (EventSource eventSource : eventSources) { - eventSourceMap.put(generateNameFor(eventSource), eventSource); - } - return eventSourceMap; - } - - @SuppressWarnings("unchecked") - static Map eventSourcesFromWorkflow( - EventSourceContext context, - Workflow workflow) { - Map result = new HashMap<>(); - for (var e : workflow.getDependentResourcesByNameWithoutActivationCondition().entrySet()) { - var eventSource = e.getValue().eventSource(context); - eventSource.ifPresent(es -> result.put(e.getKey(), (EventSource) es)); - } - return result; - } - - @SuppressWarnings("rawtypes") - static Map nameEventSourcesFromDependentResource( - EventSourceContext context, DependentResource... dependentResources) { - return nameEventSourcesFromDependentResource(context, Arrays.asList(dependentResources)); - } - - @SuppressWarnings("unchecked,rawtypes") - static Map nameEventSourcesFromDependentResource( - EventSourceContext context, Collection dependentResources) { - - if (dependentResources != null) { - Map eventSourceMap = new HashMap<>(dependentResources.size()); - for (DependentResource dependentResource : dependentResources) { - Optional es = dependentResource.eventSource(context); - es.ifPresent(e -> eventSourceMap.put(generateNameFor(e), e)); - } - return eventSourceMap; - } else { - return Collections.emptyMap(); - } - } - - /** - * Used when event sources are not explicitly named when created/registered. - * - * @param eventSource EventSource - * @return generated name - */ - static String generateNameFor(EventSource eventSource) { - // we can have multiple event sources for the same class - return eventSource.getClass().getName() + "#" + eventSource.hashCode(); - } - -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/EventSourceUtils.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/EventSourceUtils.java new file mode 100644 index 0000000000..9531599072 --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/EventSourceUtils.java @@ -0,0 +1,26 @@ +package io.javaoperatorsdk.operator.api.reconciler; + +import java.util.*; + +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; +import io.javaoperatorsdk.operator.processing.dependent.workflow.Workflow; +import io.javaoperatorsdk.operator.processing.event.source.EventSource; + +public class EventSourceUtils { + + @SuppressWarnings("unchecked") + public static

List> dependentEventSources( + EventSourceContext

eventSourceContext, DependentResource... dependentResources) { + return Arrays.stream(dependentResources) + .flatMap(dr -> dr.eventSource(eventSourceContext).stream()).toList(); + } + + @SuppressWarnings("unchecked") + public static

List> eventSourcesFromWorkflow( + EventSourceContext

context, + Workflow

workflow) { + return workflow.getDependentResourcesWithoutActivationCondition().stream() + .flatMap(dr -> dr.eventSource(context).stream()).toList(); + } +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/IndexDiscriminator.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/IndexDiscriminator.java deleted file mode 100644 index 7a27397b26..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/IndexDiscriminator.java +++ /dev/null @@ -1,50 +0,0 @@ -package io.javaoperatorsdk.operator.api.reconciler; - -import java.util.Optional; -import java.util.function.Function; - -import io.fabric8.kubernetes.api.model.HasMetadata; -import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; - -/** - * Uses a custom index of {@link InformerEventSource} to access the target resource. The index needs - * to be explicitly created when the event source is defined. This approach improves the performance - * to access the resource. - */ -public class IndexDiscriminator - implements ResourceDiscriminator { - - private final String indexName; - private final String eventSourceName; - private final Function keyMapper; - - public IndexDiscriminator(String indexName, Function keyMapper) { - this(indexName, null, keyMapper); - } - - public IndexDiscriminator(String indexName, String eventSourceName, - Function keyMapper) { - this.indexName = indexName; - this.eventSourceName = eventSourceName; - this.keyMapper = keyMapper; - } - - @Override - public Optional distinguish(Class resource, - P primary, - Context

context) { - - InformerEventSource eventSource = - (InformerEventSource) context - .eventSourceRetriever() - .getResourceEventSourceFor(resource, eventSourceName); - var resources = eventSource.byIndex(indexName, keyMapper.apply(primary)); - if (resources.isEmpty()) { - return Optional.empty(); - } else if (resources.size() > 1) { - throw new IllegalStateException("More than one resource found"); - } else { - return Optional.of(resources.get(0)); - } - } -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Reconciler.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Reconciler.java index 55df9d1cea..1545a87fe9 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Reconciler.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Reconciler.java @@ -1,8 +1,11 @@ package io.javaoperatorsdk.operator.api.reconciler; +import java.util.*; + import io.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.processing.event.source.EventSource; -public interface Reconciler { +public interface Reconciler

{ /** * The implementation of this operation is required to be idempotent. Always use the UpdateControl @@ -14,6 +17,42 @@ public interface Reconciler { * @return UpdateControl to manage updates on the custom resource (usually the status) after * reconciliation. */ - UpdateControl reconcile(R resource, Context context) throws Exception; + UpdateControl

reconcile(P resource, Context

context) throws Exception; + + /** + * Prepares a map of {@link EventSource} implementations keyed by the name with which they need to + * be registered by the SDK. + * + * @param context a {@link EventSourceContext} providing access to information useful to event + * sources + * @return a list of event sources + */ + default List> prepareEventSources(EventSourceContext

context) { + return Collections.emptyList(); + } + + /** + *

+ * Reconciler can override this method in order to update the status sub-resource in the case an + * exception in thrown. In that case {@link #updateErrorStatus(HasMetadata, Context, Exception)} + * is called automatically. + *

+ * The result of the method call is used to make a status update on the custom resource. This is + * always a sub-resource update request, so no update on custom resource itself (like spec of + * metadata) happens. Note that this update request will also produce an event, and will result in + * a reconciliation if the controller is not generation aware. + *

+ * Note that the scope of this feature is only the reconcile method of the reconciler, since there + * should not be updates on custom resource after it is marked for deletion. + * + * @param resource to update the status on + * @param context the current context + * @param e exception thrown from the reconciler + * @return the updated resource + */ + default ErrorStatusUpdateControl

updateErrorStatus(P resource, Context

context, + Exception e) { + return ErrorStatusUpdateControl.defaultErrorProcessing(); + } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ResourceDiscriminator.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ResourceDiscriminator.java deleted file mode 100644 index 072e7d8078..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ResourceDiscriminator.java +++ /dev/null @@ -1,11 +0,0 @@ -package io.javaoperatorsdk.operator.api.reconciler; - -import java.util.Optional; - -import io.fabric8.kubernetes.api.model.HasMetadata; - -public interface ResourceDiscriminator { - - Optional distinguish(Class resource, P primary, Context

context); - -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ResourceIDMatcherDiscriminator.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ResourceIDMatcherDiscriminator.java deleted file mode 100644 index da773fc210..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/ResourceIDMatcherDiscriminator.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.javaoperatorsdk.operator.api.reconciler; - -import java.util.Optional; -import java.util.function.Function; - -import io.fabric8.kubernetes.api.model.HasMetadata; -import io.javaoperatorsdk.operator.processing.event.ResourceID; -import io.javaoperatorsdk.operator.processing.event.source.Cache; - -public class ResourceIDMatcherDiscriminator - implements ResourceDiscriminator { - - - private final String eventSourceName; - private final Function mapper; - - public ResourceIDMatcherDiscriminator(Function mapper) { - this(null, mapper); - } - - public ResourceIDMatcherDiscriminator(String eventSourceName, Function mapper) { - this.eventSourceName = eventSourceName; - this.mapper = mapper; - } - - @SuppressWarnings("unchecked") - @Override - public Optional distinguish(Class resource, P primary, Context

context) { - var resourceID = mapper.apply(primary); - if (eventSourceName != null) { - return ((Cache) context.eventSourceRetriever().getResourceEventSourceFor(resource, - eventSourceName)) - .get(resourceID); - } else { - var eventSources = context.eventSourceRetriever().getResourceEventSourcesFor(resource); - if (eventSources.size() == 1) { - return ((Cache) eventSources.get(0)).get(resourceID); - } else { - return context.getSecondaryResourcesAsStream(resource) - .filter(resourceID::isSameResource) - .findFirst(); - } - } - } -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/UpdateControl.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/UpdateControl.java index 7eb7d2ae84..a8ae1331d7 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/UpdateControl.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/UpdateControl.java @@ -1,51 +1,35 @@ package io.javaoperatorsdk.operator.api.reconciler; +import java.util.Optional; + import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.client.CustomResource; public class UpdateControl

extends BaseControl> { private final P resource; - private final boolean updateStatus; - private final boolean updateResource; + private final boolean patchResource; private final boolean patchStatus; private UpdateControl( - P resource, boolean updateStatus, boolean updateResource, boolean patchStatus) { - if ((updateResource || updateStatus) && resource == null) { + P resource, boolean patchResource, boolean patchStatus) { + if ((patchResource || patchStatus) && resource == null) { throw new IllegalArgumentException("CustomResource cannot be null in case of update"); } this.resource = resource; - this.updateStatus = updateStatus; - this.updateResource = updateResource; + this.patchResource = patchResource; this.patchStatus = patchStatus; } - /** - * Creates an update control instance that instructs the framework to do an update on resource - * itself, not on the status. Note that usually as a results of a reconciliation should be a - * status update not an update to the resource itself. - * - * Using this update makes sure that the resource in the next reconciliation is the updated one - - * this is not guaranteed by default if you do an update on a resource by the Kubernetes client. - * - * @param custom resource type - * @param customResource customResource to use for update - * @return initialized update control - */ - public static UpdateControl updateResource(T customResource) { - return new UpdateControl<>(customResource, false, true, false); - } - /** * Preferred way to update the status. It does not do optimistic locking. Uses JSON Patch to patch * the resource. *

- * Note that this does not work, if the {@link CustomResource#initStatus() initStatus} is - * implemented, since it breaks the diffing process. Don't implement it if using this method. + * Note that this does not work, if the {@link CustomResource#initStatus()} is implemented, since + * it breaks the diffing process. Don't implement it if using this method. *

- * There is also an issue with setting value to null with older Kubernetes versions (1.19 and - * below). See:
https://github.com/fabric8io/kubernetes-client/issues/4158 * * @param resource type @@ -53,86 +37,32 @@ public static UpdateControl updateResource(T customRe * @return UpdateControl instance */ public static UpdateControl patchStatus(T customResource) { - return new UpdateControl<>(customResource, true, false, true); - } - - /** - * Note that usually "patchStatus" is advised to be used instead of this method. - *

- * Updates the status with optimistic locking regarding current resource version reconciled. Note - * that this also ensures that on next reconciliation is the most up-to-date custom resource is - * used. - *

- * - * @param resource type - * @param customResource the custom resource with target status - * @return UpdateControl instance - */ - public static UpdateControl updateStatus(T customResource) { - return new UpdateControl<>(customResource, true, false, false); - } - - /** - * As a results of this there will be two call to K8S API. First the custom resource will be - * updates then the status sub-resource. - * - * Using this update makes sure that the resource in the next reconciliation is the updated one - - * this is not guaranteed by default if you do an update on a resource by the Kubernetes client. - * - * @param resource type - * @param customResource - custom resource to use in both API calls - * @return UpdateControl instance - */ - public static UpdateControl updateResourceAndStatus( - T customResource) { - return new UpdateControl<>(customResource, true, true, false); + return new UpdateControl<>(customResource, false, true); } - /** - * Updates the resource - with optimistic locking - and patches the status without optimistic - * locking in place. - * - * Note that using this method, it is not guaranteed that the most recent updated resource will be - * in case for next reconciliation. - * - * @param customResource to update - * @return UpdateControl instance - * @param resource type - */ - public static UpdateControl updateResourceAndPatchStatus( - T customResource) { - return new UpdateControl<>(customResource, true, true, true); + public static UpdateControl patchResource(T customResource) { + return new UpdateControl<>(customResource, true, false); } /** - * Marked for removal, because of confusing name. It does not patch the resource but rather - * updates it. - * - * @deprecated use {@link UpdateControl#updateResourceAndPatchStatus(HasMetadata)} - * * @param customResource to update * @return UpdateControl instance * @param resource type */ - @Deprecated(forRemoval = true) public static UpdateControl patchResourceAndStatus(T customResource) { - return updateResourceAndStatus(customResource); + return new UpdateControl<>(customResource, true, true); } public static UpdateControl noUpdate() { - return new UpdateControl<>(null, false, false, false); - } - - public P getResource() { - return resource; + return new UpdateControl<>(null, false, false); } - public boolean isUpdateStatus() { - return updateStatus; + public Optional

getResource() { + return Optional.ofNullable(resource); } - public boolean isUpdateResource() { - return updateResource; + public boolean isPatchResource() { + return patchResource; } public boolean isPatchStatus() { @@ -140,11 +70,11 @@ public boolean isPatchStatus() { } public boolean isNoUpdate() { - return !updateResource && !updateStatus; + return !patchResource && !patchStatus; } - public boolean isUpdateResourceAndStatus() { - return updateResource && updateStatus; + public boolean isPatchResourceAndStatus() { + return patchResource && patchStatus; } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Workflow.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Workflow.java new file mode 100644 index 0000000000..3fb6c2c830 --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/Workflow.java @@ -0,0 +1,42 @@ +package io.javaoperatorsdk.operator.api.reconciler; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; +import io.javaoperatorsdk.operator.processing.dependent.workflow.WorkflowCleanupResult; +import io.javaoperatorsdk.operator.processing.dependent.workflow.WorkflowReconcileResult; + +@Inherited +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE}) +public @interface Workflow { + + Dependent[] dependents(); + + /** + * If {@code true}, the managed workflow should be explicitly invoked within the reconciler + * implementation. If {@code false}, the workflow is invoked just before the + * {@link Reconciler#reconcile(HasMetadata, Context)} method. + */ + boolean explicitInvocation() default false; + + /** + * If {@code true} and exceptions are thrown during the workflow's execution, the reconciler won't + * throw an {@link io.javaoperatorsdk.operator.AggregatedOperatorException} at the end of the + * execution as would normally be the case. Instead, it will proceed to its + * {@link Reconciler#reconcile(HasMetadata, Context)} method as if no error occurred. It is then + * up to the developer to decide how to proceed by retrieving the errored dependents (and their + * associated exception) via {@link WorkflowReconcileResult#getErroredDependents()} or + * {@link WorkflowCleanupResult#getErroredDependents()}, the workflow result itself being accessed + * from {@link Context#managedWorkflowAndDependentResourceContext()}. If {@code false}, an + * exception will be automatically thrown at the end of the workflow execution, presenting an + * aggregated view of what happened. + */ + boolean handleExceptionsInReconciler() default false; + +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/DependentResource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/DependentResource.java index 8230dc4cf9..7c4e530ce2 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/DependentResource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/DependentResource.java @@ -5,7 +5,7 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; -import io.javaoperatorsdk.operator.processing.event.source.ResourceEventSource; +import io.javaoperatorsdk.operator.processing.event.source.EventSource; /** * An interface to implement and provide dependent resource support. @@ -15,6 +15,18 @@ */ public interface DependentResource { + /** + * Computes a default name for the specified DependentResource class + * + * @param dependentResourceClass the DependentResource class for which we want to compute a + * default name + * @return the default name for the specified DependentResource class + */ + @SuppressWarnings("rawtypes") + static String defaultNameFor(Class dependentResourceClass) { + return dependentResourceClass.getName(); + } + /** * Reconciles the dependent resource given the desired primary state * @@ -32,8 +44,8 @@ public interface DependentResource { Class resourceType(); /** - * Dependent resources are designed to by default provide event sources. There are cases where - * they might not: + * Dependent resources are designed to provide event sources by default. There are, however, cases + * where they might not: *

    *
  • If an event source is shared between multiple dependent resources. In this case only one or * none of the dependent resources sharing the event source should provide one, if any.
  • @@ -42,30 +54,48 @@ public interface DependentResource { *
* * @param eventSourceContext context of event source initialization - * @return an optional event source + * @return an optional event source initialized from the specified context + * @since 5.0.0 */ - default Optional> eventSource( + default Optional> eventSource( EventSourceContext

eventSourceContext) { return Optional.empty(); } + /** + * Retrieves the secondary resource (if it exists) associated with the specified primary resource + * for this DependentResource. + * + * @param primary the primary resource for which we want to retrieve the secondary resource + * associated with this DependentResource + * @param context the current {@link Context} in which the operation is called + * @return the secondary resource or {@link Optional#empty()} if it doesn't exist + * @throws IllegalStateException if more than one secondary is found to match the primary resource + */ default Optional getSecondaryResource(P primary, Context

context) { return Optional.empty(); } /** - * Computes a default name for the specified DependentResource class + * Determines whether resources associated with this dependent need explicit handling when + * deleted, usually meaning that the dependent implements {@link Deleter} * - * @param dependentResourceClass the DependentResource class for which we want to compute a - * default name - * @return the default name for the specified DependentResource class + * @return {@code true} if explicit handling of resource deletion is needed, {@code false} + * otherwise */ - @SuppressWarnings("rawtypes") - static String defaultNameFor(Class dependentResourceClass) { - return dependentResourceClass.getName(); - } - default boolean isDeletable() { return this instanceof Deleter; } + + + /** + * Retrieves the name identifying this DependentResource implementation, useful to refer to this + * in {@link io.javaoperatorsdk.operator.processing.dependent.workflow.Workflow} instances + * + * @return the name identifying this DependentResource implementation + */ + default String name() { + return defaultNameFor(getClass()); + } + } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/DependentResourceFactory.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/DependentResourceFactory.java index e9e47f6d97..cc9a1dd6c3 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/DependentResourceFactory.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/DependentResourceFactory.java @@ -3,19 +3,35 @@ import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.config.Utils; import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceSpec; - -import static io.javaoperatorsdk.operator.api.config.dependent.DependentResourceConfigurationResolver.configure; +import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.ConfiguredDependentResource; @SuppressWarnings({"rawtypes", "unchecked"}) -public interface DependentResourceFactory> { +public interface DependentResourceFactory, D extends DependentResourceSpec> { DependentResourceFactory DEFAULT = new DependentResourceFactory() {}; - default DependentResource createFrom(DependentResourceSpec spec, C configuration) { + default DependentResource createFrom(D spec, C controllerConfiguration) { final var dependentResourceClass = spec.getDependentResourceClass(); return Utils.instantiateAndConfigureIfNeeded(dependentResourceClass, DependentResource.class, - Utils.contextFor(configuration, dependentResourceClass, Dependent.class), - (instance) -> configure(instance, spec, configuration)); + Utils.contextFor(controllerConfiguration, dependentResourceClass, Dependent.class), + (instance) -> configure(instance, spec, controllerConfiguration)); + } + + default void configure(DependentResource instance, D spec, C controllerConfiguration) { + if (instance instanceof ConfiguredDependentResource configurable) { + final var config = controllerConfiguration.getConfigurationFor(spec); + if (config != null) { + configurable.configureWith(config); + } + } + } + + default Class associatedResourceType(D spec) { + final var dependentResourceClass = spec.getDependentResourceClass(); + final var dr = Utils.instantiateAndConfigureIfNeeded(dependentResourceClass, + DependentResource.class, + null, null); + return dr != null ? dr.resourceType() : null; } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/EventSourceProvider.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/EventSourceProvider.java deleted file mode 100644 index c83af1270a..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/EventSourceProvider.java +++ /dev/null @@ -1,18 +0,0 @@ -package io.javaoperatorsdk.operator.api.reconciler.dependent; - -import io.fabric8.kubernetes.api.model.HasMetadata; -import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; -import io.javaoperatorsdk.operator.processing.event.source.EventSource; - -/** - * @deprecated now event source related methods are directly on {@link DependentResource} - * @param

primary resource - */ -@Deprecated(forRemoval = true) -public interface EventSourceProvider

{ - /** - * @param context - event source context where the event source is initialized - * @return the initiated event source. - */ - EventSource initEventSource(EventSourceContext

context); -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/NameSetter.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/NameSetter.java new file mode 100644 index 0000000000..952bf14490 --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/NameSetter.java @@ -0,0 +1,7 @@ +package io.javaoperatorsdk.operator.api.reconciler.dependent; + +public interface NameSetter { + + void setName(String name); + +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/DependentResourceConfigurator.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/ConfiguredDependentResource.java similarity index 76% rename from operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/DependentResourceConfigurator.java rename to operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/ConfiguredDependentResource.java index 2b361626aa..326482aab0 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/DependentResourceConfigurator.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/ConfiguredDependentResource.java @@ -2,7 +2,8 @@ import java.util.Optional; -public interface DependentResourceConfigurator { + +public interface ConfiguredDependentResource { void configureWith(C config); Optional configuration(); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/DefaultManagedDependentResourceContext.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/DefaultManagedDependentResourceContext.java deleted file mode 100644 index 61414468c8..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/DefaultManagedDependentResourceContext.java +++ /dev/null @@ -1,48 +0,0 @@ -package io.javaoperatorsdk.operator.api.reconciler.dependent.managed; - -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; - -import io.javaoperatorsdk.operator.processing.dependent.workflow.WorkflowCleanupResult; -import io.javaoperatorsdk.operator.processing.dependent.workflow.WorkflowReconcileResult; - -@SuppressWarnings("rawtypes") -public class DefaultManagedDependentResourceContext implements ManagedDependentResourceContext { - public static final Object RECONCILE_RESULT_KEY = new Object(); - public static final Object CLEANUP_RESULT_KEY = new Object(); - private final ConcurrentHashMap attributes = new ConcurrentHashMap(); - - @Override - public Optional get(Object key, Class expectedType) { - return Optional.ofNullable(attributes.get(key)) - .filter(expectedType::isInstance) - .map(expectedType::cast); - } - - @Override - @SuppressWarnings("unchecked") - public T put(Object key, T value) { - if (value == null) { - return (T) Optional.ofNullable(attributes.remove(key)); - } - return (T) Optional.ofNullable(attributes.put(key, value)); - } - - @Override - @SuppressWarnings("unused") - public T getMandatory(Object key, Class expectedType) { - return get(key, expectedType).orElseThrow(() -> new IllegalStateException( - "Mandatory attribute (key: " + key + ", type: " + expectedType.getName() - + ") is missing or not of the expected type")); - } - - @Override - public Optional getWorkflowReconcileResult() { - return get(RECONCILE_RESULT_KEY, WorkflowReconcileResult.class); - } - - @Override - public Optional getWorkflowCleanupResult() { - return get(CLEANUP_RESULT_KEY, WorkflowCleanupResult.class); - } -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/DefaultManagedWorkflowAndDependentResourceContext.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/DefaultManagedWorkflowAndDependentResourceContext.java new file mode 100644 index 0000000000..161c38210f --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/DefaultManagedWorkflowAndDependentResourceContext.java @@ -0,0 +1,81 @@ +package io.javaoperatorsdk.operator.api.reconciler.dependent.managed; + +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.processing.Controller; +import io.javaoperatorsdk.operator.processing.dependent.workflow.WorkflowCleanupResult; +import io.javaoperatorsdk.operator.processing.dependent.workflow.WorkflowReconcileResult; + +@SuppressWarnings("rawtypes") +public class DefaultManagedWorkflowAndDependentResourceContext

+ implements ManagedWorkflowAndDependentResourceContext { + + public static final Object RECONCILE_RESULT_KEY = new Object(); + public static final Object CLEANUP_RESULT_KEY = new Object(); + private final ConcurrentHashMap attributes = new ConcurrentHashMap(); + private final Controller

controller; + private final P primaryResource; + private final Context

context; + + public DefaultManagedWorkflowAndDependentResourceContext(Controller

controller, + P primaryResource, + Context

context) { + this.controller = controller; + this.primaryResource = primaryResource; + this.context = context; + } + + @Override + public Optional get(Object key, Class expectedType) { + return Optional.ofNullable(attributes.get(key)) + .filter(expectedType::isInstance) + .map(expectedType::cast); + } + + @Override + @SuppressWarnings("unchecked") + public T put(Object key, T value) { + if (value == null) { + return (T) Optional.ofNullable(attributes.remove(key)); + } + return (T) Optional.ofNullable(attributes.put(key, value)); + } + + @Override + @SuppressWarnings("unused") + public T getMandatory(Object key, Class expectedType) { + return get(key, expectedType).orElseThrow(() -> new IllegalStateException( + "Mandatory attribute (key: " + key + ", type: " + expectedType.getName() + + ") is missing or not of the expected type")); + } + + @Override + public WorkflowReconcileResult getWorkflowReconcileResult() { + return getMandatory(RECONCILE_RESULT_KEY, WorkflowReconcileResult.class); + } + + @Override + public WorkflowCleanupResult getWorkflowCleanupResult() { + return getMandatory(CLEANUP_RESULT_KEY, WorkflowCleanupResult.class); + } + + @Override + public void reconcileManagedWorkflow() { + if (!controller.isWorkflowExplicitInvocation()) { + throw new IllegalStateException("Workflow explicit invocation is not set."); + } + controller.reconcileManagedWorkflow(primaryResource, context); + } + + @Override + public void cleanupManageWorkflow() { + if (!controller.isWorkflowExplicitInvocation()) { + throw new IllegalStateException("Workflow explicit invocation is not set."); + } + controller.cleanupManagedWorkflow(primaryResource, context); + } + +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/KubernetesClientAware.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/KubernetesClientAware.java deleted file mode 100644 index d6c743f22b..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/KubernetesClientAware.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.javaoperatorsdk.operator.api.reconciler.dependent.managed; - -import io.fabric8.kubernetes.client.KubernetesClient; -import io.javaoperatorsdk.operator.api.reconciler.Context; - -/** - * @deprecated It shouldn't be needed to pass a {@link KubernetesClient} instance anymore as the - * client should be accessed via {@link Context#getClient()} instead. - */ -@Deprecated(since = "4.5.0", forRemoval = true) -public interface KubernetesClientAware { - void setKubernetesClient(KubernetesClient kubernetesClient); - - KubernetesClient getKubernetesClient(); -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/ManagedDependentResourceContext.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/ManagedWorkflowAndDependentResourceContext.java similarity index 72% rename from operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/ManagedDependentResourceContext.java rename to operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/ManagedWorkflowAndDependentResourceContext.java index 9c5b3dddb1..f5a25a6d9c 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/ManagedDependentResourceContext.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/reconciler/dependent/managed/ManagedWorkflowAndDependentResourceContext.java @@ -10,7 +10,7 @@ * Contextual information related to {@link DependentResource} either to retrieve the actual * implementations to interact with them or to pass information between them and/or the reconciler */ -public interface ManagedDependentResourceContext { +public interface ManagedWorkflowAndDependentResourceContext { /** * Retrieve a contextual object, if it exists and is of the specified expected type, associated @@ -37,7 +37,6 @@ public interface ManagedDependentResourceContext { * @return an Optional containing the previous value associated with the key or * {@link Optional#empty()} if none existed */ - @SuppressWarnings("unchecked") T put(Object key, T value); /** @@ -52,7 +51,27 @@ public interface ManagedDependentResourceContext { @SuppressWarnings("unused") T getMandatory(Object key, Class expectedType); - Optional getWorkflowReconcileResult(); + WorkflowReconcileResult getWorkflowReconcileResult(); + + @SuppressWarnings("unused") + WorkflowCleanupResult getWorkflowCleanupResult(); + + /** + * Explicitly reconcile the declared workflow for the associated + * {@link io.javaoperatorsdk.operator.api.reconciler.Reconciler} + * + * @throws IllegalStateException if called when explicit invocation is not requested + */ + void reconcileManagedWorkflow(); + + /** + * Explicitly clean-up dependent resources in the declared workflow for the associated + * {@link io.javaoperatorsdk.operator.api.reconciler.Reconciler}. Note that calling this method is + * only needed if the associated reconciler implements the + * {@link io.javaoperatorsdk.operator.api.reconciler.Cleaner} interface. + * + * @throws IllegalStateException if called when explicit invocation is not requested + */ + void cleanupManageWorkflow(); - Optional getWorkflowCleanupResult(); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/ControllerHealthInfo.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/ControllerHealthInfo.java index fe90b99ef3..1d65922f11 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/ControllerHealthInfo.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/ControllerHealthInfo.java @@ -4,6 +4,8 @@ import java.util.stream.Collectors; import io.javaoperatorsdk.operator.processing.event.EventSourceManager; +import io.javaoperatorsdk.operator.processing.event.source.EventSource; +import io.javaoperatorsdk.operator.processing.event.source.controller.ControllerEventSource; @SuppressWarnings("rawtypes") public class ControllerHealthInfo { @@ -15,36 +17,35 @@ public ControllerHealthInfo(EventSourceManager eventSourceManager) { } public Map eventSourceHealthIndicators() { - return eventSourceManager.allEventSources().entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + return eventSourceManager.allEventSources().stream() + .collect(Collectors.toMap(EventSource::name, e -> e)); } public Map unhealthyEventSources() { - return eventSourceManager.allEventSources().entrySet().stream() - .filter(e -> e.getValue().getStatus() == Status.UNHEALTHY) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + return eventSourceManager.allEventSources().stream() + .filter(e -> e.getStatus() == Status.UNHEALTHY) + .collect(Collectors.toMap(EventSource::name, e -> e)); } public Map informerEventSourceHealthIndicators() { - return eventSourceManager.allEventSources().entrySet().stream() - .filter(e -> e.getValue() instanceof InformerWrappingEventSourceHealthIndicator) - .collect(Collectors.toMap(Map.Entry::getKey, - e -> (InformerWrappingEventSourceHealthIndicator) e.getValue())); + return eventSourceManager.allEventSources().stream() + .filter(e -> e instanceof InformerWrappingEventSourceHealthIndicator) + .collect(Collectors.toMap(EventSource::name, + e -> (InformerWrappingEventSourceHealthIndicator) e)); } /** * @return Map with event sources that wraps an informer. Thus, either a - * {@link io.javaoperatorsdk.operator.processing.event.source.controller.ControllerResourceEventSource} - * or an + * {@link ControllerEventSource} or an * {@link io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource}. */ public Map unhealthyInformerEventSourceHealthIndicators() { - return eventSourceManager.allEventSources().entrySet().stream() - .filter(e -> e.getValue().getStatus() == Status.UNHEALTHY) - .filter(e -> e.getValue() instanceof InformerWrappingEventSourceHealthIndicator) - .collect(Collectors.toMap(Map.Entry::getKey, - e -> (InformerWrappingEventSourceHealthIndicator) e.getValue())); + return eventSourceManager.allEventSources().stream() + .filter(e -> e.getStatus() == Status.UNHEALTHY) + .filter(e -> e instanceof InformerWrappingEventSourceHealthIndicator) + .collect(Collectors.toMap(EventSource::name, + e -> (InformerWrappingEventSourceHealthIndicator) e)); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/EventSourceHealthIndicator.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/EventSourceHealthIndicator.java index e44fcb5b72..2732c16707 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/EventSourceHealthIndicator.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/EventSourceHealthIndicator.java @@ -2,5 +2,12 @@ public interface EventSourceHealthIndicator { + /** + * Retrieves the health status of an + * {@link io.javaoperatorsdk.operator.processing.event.source.EventSource} + * + * @return the health status + * @see Status + */ Status getStatus(); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/InformerWrappingEventSourceHealthIndicator.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/InformerWrappingEventSourceHealthIndicator.java index 5a603ad321..da9b2ace2c 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/InformerWrappingEventSourceHealthIndicator.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/InformerWrappingEventSourceHealthIndicator.java @@ -3,7 +3,6 @@ import java.util.Map; import io.fabric8.kubernetes.api.model.HasMetadata; -import io.javaoperatorsdk.operator.api.config.ResourceConfiguration; public interface InformerWrappingEventSourceHealthIndicator extends EventSourceHealthIndicator { @@ -17,6 +16,4 @@ default Status getStatus() { return nonUp.isPresent() ? Status.UNHEALTHY : Status.HEALTHY; } - - ResourceConfiguration getInformerConfiguration(); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/Status.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/Status.java index d3a300b7d8..272c360a87 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/Status.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/health/Status.java @@ -1,5 +1,8 @@ package io.javaoperatorsdk.operator.health; +/** + * The health status of an {@link io.javaoperatorsdk.operator.processing.event.source.EventSource} + */ public enum Status { HEALTHY, UNHEALTHY, diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/Controller.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/Controller.java index 93f10d3e21..76c8401249 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/Controller.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/Controller.java @@ -23,6 +23,7 @@ import io.javaoperatorsdk.operator.RegisteredController; import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.config.ExecutorServiceManager; +import io.javaoperatorsdk.operator.api.config.workflow.WorkflowSpec; import io.javaoperatorsdk.operator.api.monitoring.Metrics; import io.javaoperatorsdk.operator.api.monitoring.Metrics.ControllerExecution; import io.javaoperatorsdk.operator.api.reconciler.Cleaner; @@ -31,12 +32,10 @@ import io.javaoperatorsdk.operator.api.reconciler.ContextInitializer; import io.javaoperatorsdk.operator.api.reconciler.DeleteControl; import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; -import io.javaoperatorsdk.operator.api.reconciler.EventSourceInitializer; import io.javaoperatorsdk.operator.api.reconciler.Ignore; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.javaoperatorsdk.operator.api.reconciler.dependent.EventSourceNotFoundException; -import io.javaoperatorsdk.operator.api.reconciler.dependent.EventSourceProvider; import io.javaoperatorsdk.operator.api.reconciler.dependent.EventSourceReferencer; import io.javaoperatorsdk.operator.health.ControllerHealthInfo; import io.javaoperatorsdk.operator.processing.dependent.workflow.Workflow; @@ -44,7 +43,7 @@ import io.javaoperatorsdk.operator.processing.event.EventProcessor; import io.javaoperatorsdk.operator.processing.event.EventSourceManager; import io.javaoperatorsdk.operator.processing.event.ResourceID; -import io.javaoperatorsdk.operator.processing.event.source.ResourceEventSource; +import io.javaoperatorsdk.operator.processing.event.source.EventSource; import static io.javaoperatorsdk.operator.api.reconciler.Constants.WATCH_CURRENT_NAMESPACE; @@ -71,6 +70,7 @@ public class Controller

private final boolean isCleaner; private final Metrics metrics; private final Workflow

managedWorkflow; + private final boolean explicitWorkflowInvocation; private final GroupVersionKind associatedGVK; private final EventProcessor

eventProcessor; @@ -93,13 +93,17 @@ public Controller(Reconciler

reconciler, final var managed = configurationService.getWorkflowFactory().workflowFor(configuration); managedWorkflow = managed.resolve(kubernetesClient, configuration); + explicitWorkflowInvocation = + configuration.getWorkflowSpec().map(WorkflowSpec::isExplicitInvocation) + .orElse(false); eventSourceManager = new EventSourceManager<>(this); eventProcessor = new EventProcessor<>(eventSourceManager, configurationService); eventSourceManager.postProcessDefaultEventSourcesAfterProcessorInitializer(); controllerHealthInfo = new ControllerHealthInfo(eventSourceManager); eventSourceContext = new EventSourceContext<>( - eventSourceManager.getControllerResourceEventSource(), configuration, kubernetesClient); + eventSourceManager.getControllerEventSource(), configuration, kubernetesClient, + configuration.getResourceClass()); initAndRegisterEventSources(eventSourceContext); configurationService.getMetrics().controllerRegistered(this); } @@ -121,10 +125,10 @@ public String controllerName() { @Override public String successTypeName(UpdateControl

result) { String successType = RESOURCE; - if (result.isUpdateStatus()) { + if (result.isPatchStatus()) { successType = STATUS; } - if (result.isUpdateResourceAndStatus()) { + if (result.isPatchResourceAndStatus()) { successType = BOTH; } return successType; @@ -143,9 +147,11 @@ public Map metadata() { @Override public UpdateControl

execute() throws Exception { initContextIfNeeded(resource, context); - if (!managedWorkflow.isEmpty()) { - managedWorkflow.reconcile(resource, context); - } + configuration.getWorkflowSpec().ifPresent(ws -> { + if (!managedWorkflow.isEmpty() && !explicitWorkflowInvocation) { + managedWorkflow.reconcile(resource, context); + } + }); return reconciler.reconcile(resource, context); } }); @@ -182,12 +188,16 @@ public Map metadata() { } @Override - public DeleteControl execute() { + public DeleteControl execute() throws Exception { initContextIfNeeded(resource, context); WorkflowCleanupResult workflowCleanupResult = null; - if (managedWorkflow.hasCleaner()) { + + // The cleanup is called also when explicit invocation is true, but the cleaner is not + // implemented + if (managedWorkflow.hasCleaner() || !explicitWorkflowInvocation) { workflowCleanupResult = managedWorkflow.cleanup(resource, context); } + if (isCleaner) { var cleanupResult = ((Cleaner

) reconciler).cleanup(resource, context); if (!cleanupResult.isRemoveFinalizer()) { @@ -223,31 +233,22 @@ private void initContextIfNeeded(P resource, Context

context) { } public void initAndRegisterEventSources(EventSourceContext

context) { - if (reconciler instanceof EventSourceInitializer) { - final var provider = (EventSourceInitializer

) this.reconciler; - final var ownSources = provider.prepareEventSources(context); - ownSources.forEach(eventSourceManager::registerEventSource); - } + final var ownSources = this.reconciler.prepareEventSources(context); + ownSources.forEach(eventSourceManager::registerEventSource); // register created event sources final var dependentResourcesByName = - managedWorkflow.getDependentResourcesByNameWithoutActivationCondition(); + managedWorkflow.getDependentResourcesWithoutActivationCondition(); final var size = dependentResourcesByName.size(); if (size > 0) { - dependentResourcesByName.forEach((key, dependentResource) -> { - if (dependentResource instanceof EventSourceProvider) { - final var provider = (EventSourceProvider) dependentResource; - final var source = provider.initEventSource(context); - eventSourceManager.registerEventSource(key, source); - } else { - Optional eventSource = dependentResource.eventSource(context); - eventSource.ifPresent(es -> eventSourceManager.registerEventSource(key, es)); - } + dependentResourcesByName.forEach(dependentResource -> { + Optional eventSource = dependentResource.eventSource(context); + eventSource.ifPresent(eventSourceManager::registerEventSource); }); // resolve event sources referenced by name for dependents that reuse an existing event source final Map> unresolvable = new HashMap<>(size); - dependentResourcesByName.values().stream() + dependentResourcesByName.stream() .filter(EventSourceReferencer.class::isInstance) .map(EventSourceReferencer.class::cast) .forEach(dr -> { @@ -447,4 +448,26 @@ public ExecutorServiceManager getExecutorServiceManager() { public EventSourceContext

eventSourceContext() { return eventSourceContext; } + + public void reconcileManagedWorkflow(P primary, Context

context) { + if (!managedWorkflow.isEmpty()) { + managedWorkflow.reconcile(primary, context); + } + } + + public void cleanupManagedWorkflow(P resource, Context

context) { + if (managedWorkflow.hasCleaner()) { + managedWorkflow.cleanup(resource, context); + } + } + + public boolean isWorkflowExplicitInvocation() { + return explicitWorkflowInvocation; + } + + public boolean workflowContainsDependentForType(Class clazz) { + return managedWorkflow.getDependentResourcesByName().values().stream() + .anyMatch(d -> d.resourceType().equals(clazz)); + } + } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/GroupVersionKind.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/GroupVersionKind.java index 1f51a2d282..68c2a7988f 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/GroupVersionKind.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/GroupVersionKind.java @@ -43,6 +43,44 @@ public GroupVersionKind(String group, String version, String kind) { this.apiVersion = (group == null || group.isBlank()) ? version : group + "/" + version; } + /** + * Parse GVK from a String representation. Expected format is: [group]/[version]/[kind] + * + *

+   *   Sample: "apps/v1/Deployment"
+   * 
+ * + * or: [version]/[kind] + * + *
+   *     Sample: v1/ConfigMap
+   * 
+ **/ + public static GroupVersionKind fromString(String gvk) { + String[] parts = gvk.split("/"); + if (parts.length == 3) { + return new GroupVersionKind(parts[0], parts[1], parts[2]); + } else if (parts.length == 2) { + return new GroupVersionKind(null, parts[0], parts[1]); + } else { + throw new IllegalArgumentException( + "Cannot parse gvk: " + gvk + ". Needs to be in form [group]/[version]/[kind]"); + } + } + + /** + * Reverse to {@link #fromString(String)}. + * + * @return gvk encoded in simple string. + */ + public String toSimpleString() { + var res = ""; + if (group != null) { + res += group + "/"; + } + return res + version + "/" + kind; + } + public String getGroup() { return group; } @@ -81,4 +119,5 @@ public String toString() { ", kind='" + kind + '\'' + '}'; } + } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/AbstractDependentResource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/AbstractDependentResource.java index 566f0f7625..db69d8134b 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/AbstractDependentResource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/AbstractDependentResource.java @@ -1,6 +1,7 @@ package io.javaoperatorsdk.operator.processing.dependent; import java.util.Optional; +import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -8,35 +9,47 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.Ignore; -import io.javaoperatorsdk.operator.api.reconciler.ResourceDiscriminator; import io.javaoperatorsdk.operator.api.reconciler.dependent.Deleter; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; +import io.javaoperatorsdk.operator.api.reconciler.dependent.NameSetter; import io.javaoperatorsdk.operator.api.reconciler.dependent.ReconcileResult; import io.javaoperatorsdk.operator.processing.dependent.Matcher.Result; import io.javaoperatorsdk.operator.processing.event.ResourceID; +/** + * An abstract implementation of {@link DependentResource} to be used as base for custom + * implementations, providing, in particular, the core {@link #reconcile(HasMetadata, Context)} + * logic for dependents + * + * @param the dependent resource type + * @param

the associated primary resource type + */ @Ignore public abstract class AbstractDependentResource - implements DependentResource { + implements DependentResource, NameSetter { private static final Logger log = LoggerFactory.getLogger(AbstractDependentResource.class); private final boolean creatable = this instanceof Creator; private final boolean updatable = this instanceof Updater; private final boolean deletable = this instanceof Deleter; - + private final DependentResourceReconciler dependentResourceReconciler; protected Creator creator; protected Updater updater; - private ResourceDiscriminator resourceDiscriminator; - private final DependentResourceReconciler dependentResourceReconciler; + protected String name; - @SuppressWarnings({"unchecked"}) protected AbstractDependentResource() { + this(null); + } + + @SuppressWarnings("unchecked") + protected AbstractDependentResource(String name) { creator = creatable ? (Creator) this : null; updater = updatable ? (Updater) this : null; dependentResourceReconciler = this instanceof BulkDependentResource ? new BulkDependentResourceReconciler<>((BulkDependentResource) this) : new SingleDependentResourceReconciler<>(this); + this.name = name == null ? DependentResource.defaultNameFor(this.getClass()) : name; } /** @@ -53,7 +66,7 @@ public ReconcileResult reconcile(P primary, Context

context) { } protected ReconcileResult reconcile(P primary, R actualResource, Context

context) { - if (creatable || updatable) { + if (creatable() || updatable()) { if (actualResource == null) { if (creatable) { var desired = desired(primary, context); @@ -63,7 +76,7 @@ protected ReconcileResult reconcile(P primary, R actualResource, Context

c return ReconcileResult.resourceCreated(createdResource); } } else { - if (updatable) { + if (updatable()) { final Matcher.Result match = match(actualResource, primary, context); if (!match.matched()) { final var desired = match.computedDesired().orElseGet(() -> desired(primary, context)); @@ -96,8 +109,38 @@ protected ReconcileResult reconcile(P primary, R actualResource, Context

c @Override public Optional getSecondaryResource(P primary, Context

context) { - return resourceDiscriminator == null ? context.getSecondaryResource(resourceType()) - : resourceDiscriminator.distinguish(resourceType(), primary, context); + + var secondaryResources = context.getSecondaryResources(resourceType()); + if (secondaryResources.isEmpty()) { + return Optional.empty(); + } else { + return selectTargetSecondaryResource(secondaryResources, primary, context); + } + + } + + /** + * Selects the actual secondary resource matching the desired state derived from the primary + * resource when several resources of the same type are found in the context. This method allows + * for optimized implementations in subclasses since this default implementation will check each + * secondary candidates for equality with the specified desired state, which might end up costly. + * + * @param secondaryResources to select the target resource from + * @param primary the primary resource + * @param context the context in which this method is called + * @return the matching secondary resource or {@link Optional#empty()} if none matches + * @throws IllegalStateException if more than one candidate is found, in which case some other + * mechanism might be necessary to distinguish between candidate secondary resources + */ + protected Optional selectTargetSecondaryResource(Set secondaryResources, P primary, + Context

context) { + R desired = desired(primary, context); + var targetResources = secondaryResources.stream().filter(r -> r.equals(desired)).toList(); + if (targetResources.size() > 1) { + throw new IllegalStateException( + "More than one secondary resource related to primary: " + targetResources); + } + return targetResources.isEmpty() ? Optional.empty() : Optional.of(targetResources.get(0)); } private void throwIfNull(R desired, P primary, String descriptor) { @@ -165,11 +208,6 @@ protected void handleDelete(P primary, R secondary, Context

context) { "handleDelete method must be implemented if Deleter trait is supported"); } - public void setResourceDiscriminator( - ResourceDiscriminator resourceDiscriminator) { - this.resourceDiscriminator = resourceDiscriminator; - } - protected boolean isCreatable() { return creatable; } @@ -183,4 +221,21 @@ protected boolean isUpdatable() { public boolean isDeletable() { return deletable; } + + @Override + public String name() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + protected boolean creatable() { + return creatable; + } + + protected boolean updatable() { + return updatable; + } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/AbstractEventSourceHolderDependentResource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/AbstractEventSourceHolderDependentResource.java index 6562afd09f..6745a45a72 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/AbstractEventSourceHolderDependentResource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/AbstractEventSourceHolderDependentResource.java @@ -11,26 +11,23 @@ import io.javaoperatorsdk.operator.api.reconciler.dependent.RecentOperationCacheFiller; import io.javaoperatorsdk.operator.processing.event.EventSourceRetriever; import io.javaoperatorsdk.operator.processing.event.ResourceID; -import io.javaoperatorsdk.operator.processing.event.source.ResourceEventSource; -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.javaoperatorsdk.operator.processing.event.source.EventSource; @Ignore -public abstract class AbstractEventSourceHolderDependentResource> +public abstract class AbstractEventSourceHolderDependentResource> extends AbstractDependentResource implements EventSourceReferencer

{ private T eventSource; private final Class resourceType; private boolean isCacheFillerEventSource; - protected OnAddFilter onAddFilter; - protected OnUpdateFilter onUpdateFilter; - protected OnDeleteFilter onDeleteFilter; - protected GenericFilter genericFilter; protected String eventSourceNameToUse; protected AbstractEventSourceHolderDependentResource(Class resourceType) { + this(resourceType, null); + } + + protected AbstractEventSourceHolderDependentResource(Class resourceType, String name) { + super(name); this.resourceType = resourceType; } @@ -52,7 +49,6 @@ public synchronized Optional eventSource(EventSourceContext

context) { if (eventSource == null && eventSourceNameToUse == null) { setEventSource(createEventSource(context)); - applyFilters(); } return Optional.ofNullable(eventSource); } @@ -62,7 +58,7 @@ public synchronized Optional eventSource(EventSourceContext

context) { public void resolveEventSource(EventSourceRetriever

eventSourceRetriever) { if (eventSourceNameToUse != null && eventSource == null) { final var source = - eventSourceRetriever.getResourceEventSourceFor(resourceType(), eventSourceNameToUse); + eventSourceRetriever.getEventSourceFor(resourceType(), eventSourceNameToUse); if (source == null) { throw new EventSourceNotFoundException(eventSourceNameToUse); } @@ -92,18 +88,11 @@ public Class resourceType() { protected abstract T createEventSource(EventSourceContext

context); - protected void setEventSource(T eventSource) { + public void setEventSource(T eventSource) { isCacheFillerEventSource = eventSource instanceof RecentOperationCacheFiller; this.eventSource = eventSource; } - protected void applyFilters() { - this.eventSource.setOnAddFilter(onAddFilter); - this.eventSource.setOnUpdateFilter(onUpdateFilter); - this.eventSource.setOnDeleteFilter(onDeleteFilter); - this.eventSource.setGenericFilter(genericFilter); - } - public Optional eventSource() { return Optional.ofNullable(eventSource); } @@ -127,15 +116,4 @@ private RecentOperationCacheFiller recentOperationCacheFiller() { return (RecentOperationCacheFiller) eventSource; } - public void setOnAddFilter(OnAddFilter onAddFilter) { - this.onAddFilter = onAddFilter; - } - - public void setOnUpdateFilter(OnUpdateFilter onUpdateFilter) { - this.onUpdateFilter = onUpdateFilter; - } - - public void setOnDeleteFilter(OnDeleteFilter onDeleteFilter) { - this.onDeleteFilter = onDeleteFilter; - } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/AbstractExternalDependentResource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/AbstractExternalDependentResource.java index ef825ef71f..acb6cb99d3 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/AbstractExternalDependentResource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/AbstractExternalDependentResource.java @@ -5,10 +5,10 @@ import io.javaoperatorsdk.operator.api.reconciler.dependent.RecentOperationCacheFiller; import io.javaoperatorsdk.operator.processing.event.EventSourceRetriever; import io.javaoperatorsdk.operator.processing.event.ResourceID; -import io.javaoperatorsdk.operator.processing.event.source.ResourceEventSource; +import io.javaoperatorsdk.operator.processing.event.source.EventSource; import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; -public abstract class AbstractExternalDependentResource> +public abstract class AbstractExternalDependentResource> extends AbstractEventSourceHolderDependentResource { private final boolean isDependentResourceWithExplicitState = @@ -34,7 +34,7 @@ public void resolveEventSource(EventSourceRetriever

eventSourceRetriever) { final var eventSourceName = (String) dependentResourceWithExplicitState .eventSourceName().orElse(null); externalStateEventSource = (InformerEventSource) eventSourceRetriever - .getResourceEventSourceFor(dependentResourceWithExplicitState.stateResourceClass(), + .getEventSourceFor(dependentResourceWithExplicitState.stateResourceClass(), eventSourceName); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/BulkDependentResource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/BulkDependentResource.java index a86b6ee0e8..957a969ecc 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/BulkDependentResource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/BulkDependentResource.java @@ -8,13 +8,14 @@ import io.javaoperatorsdk.operator.processing.dependent.Matcher.Result; /** - * Manages dynamic number of resources created for a primary resource. Since the point of a bulk - * dependent resource is to manage the number of secondary resources dynamically it implement - * {@link Creator} and {@link Deleter} interfaces out of the box. A concrete dependent resource can - * implement additionally also {@link Updater}. + * Manages dynamic number of resources created for a primary resource. A dependent resource + * implementing this interface will typically also implement one or more additional interfaces such + * as {@link Creator}, {@link Updater}, {@link Deleter}. + * + * @param the dependent resource type + * @param

the primary resource type */ -public interface BulkDependentResource - extends Creator, Deleter

{ +public interface BulkDependentResource { /** * Retrieves a map of desired secondary resources associated with the specified primary resource, @@ -26,7 +27,10 @@ public interface BulkDependentResource * @return a Map associating desired secondary resources with the specified primary via arbitrary * identifiers */ - Map desiredResources(P primary, Context

context); + default Map desiredResources(P primary, Context

context) { + throw new IllegalStateException( + "Implement desiredResources in case a non read-only bulk dependent resource"); + } /** * Retrieves the actual secondary resources currently existing on the server and associated with diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/BulkDependentResourceReconciler.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/BulkDependentResourceReconciler.java index e740ef3773..1ed36edaa2 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/BulkDependentResourceReconciler.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/BulkDependentResourceReconciler.java @@ -24,18 +24,26 @@ class BulkDependentResourceReconciler @Override public ReconcileResult reconcile(P primary, Context

context) { - final var desiredResources = bulkDependentResource.desiredResources(primary, context); + Map actualResources = bulkDependentResource.getSecondaryResources(primary, context); + if (!(bulkDependentResource instanceof Creator) + && !(bulkDependentResource instanceof Deleter) + && !(bulkDependentResource instanceof Updater)) { + return ReconcileResult + .aggregatedResult(actualResources.values().stream().map(ReconcileResult::noOperation) + .toList()); + } - // remove existing resources that are not needed anymore according to the primary state - deleteExtraResources(desiredResources.keySet(), actualResources, primary, context); + final var desiredResources = bulkDependentResource.desiredResources(primary, context); + + if (bulkDependentResource instanceof Deleter) { + // remove existing resources that are not needed anymore according to the primary state + deleteExtraResources(desiredResources.keySet(), actualResources, primary, context); + } final List> results = new ArrayList<>(desiredResources.size()); - final var updatable = bulkDependentResource instanceof Updater; desiredResources.forEach((key, value) -> { - final var instance = - updatable ? new UpdatableBulkDependentResourceInstance<>(bulkDependentResource, value) - : new BulkDependentResourceInstance<>(bulkDependentResource, value); + final var instance = new BulkDependentResourceInstance<>(bulkDependentResource, value); results.add(instance.reconcile(primary, actualResources.get(key), context)); }); @@ -67,7 +75,7 @@ private void deleteExtraResources(Set expectedKeys, @Ignore private static class BulkDependentResourceInstance extends AbstractDependentResource - implements Creator, Deleter

{ + implements Creator, Deleter

, Updater { private final BulkDependentResource bulkDependentResource; private final R desired; @@ -112,26 +120,24 @@ public Class resourceType() { return asAbstractDependentResource().resourceType(); } - @Override + @SuppressWarnings("unchecked") public R create(R desired, P primary, Context

context) { - return bulkDependentResource.create(desired, primary, context); + return ((Creator) bulkDependentResource).create(desired, primary, context); } - } - /** - * Makes sure that the instance implements Updater if its precursor does as well. - * - * @param - * @param

- */ - @Ignore - private static class UpdatableBulkDependentResourceInstance - extends BulkDependentResourceInstance implements Updater { + @Override + protected boolean isCreatable() { + return bulkDependentResource instanceof Creator; + } - private UpdatableBulkDependentResourceInstance( - BulkDependentResource bulkDependentResource, - R desired) { - super(bulkDependentResource, desired); + @Override + protected boolean isUpdatable() { + return bulkDependentResource instanceof Updater; + } + + @Override + public boolean isDeletable() { + return bulkDependentResource instanceof Deleter; } } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/CRUDBulkDependentResource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/CRUDBulkDependentResource.java new file mode 100644 index 0000000000..aa650bf1b5 --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/CRUDBulkDependentResource.java @@ -0,0 +1,11 @@ +package io.javaoperatorsdk.operator.processing.dependent; + +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.api.reconciler.dependent.Deleter; + +public interface CRUDBulkDependentResource + extends BulkDependentResource, + Creator, + BulkUpdater, + Deleter

{ +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/DependentResourceWithExplicitState.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/DependentResourceWithExplicitState.java index 05206731db..4609b4a9c7 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/DependentResourceWithExplicitState.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/DependentResourceWithExplicitState.java @@ -11,6 +11,10 @@ * are non Kubernetes resources which when created their ID is generated, so cannot be determined * based only on primary resources. In order to manage such dependent resource use this interface * for a resource that extends {@link AbstractExternalDependentResource}. + * + * @param the dependent resource type + * @param

the primary resource type + * @param the state type */ public interface DependentResourceWithExplicitState extends Creator, Deleter

{ diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/external/AbstractPollingDependentResource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/external/AbstractPollingDependentResource.java index 6355ec39c7..659b8b4720 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/external/AbstractPollingDependentResource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/external/AbstractPollingDependentResource.java @@ -1,5 +1,7 @@ package io.javaoperatorsdk.operator.processing.dependent.external; +import java.time.Duration; + import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.api.reconciler.Ignore; import io.javaoperatorsdk.operator.processing.dependent.AbstractExternalDependentResource; @@ -11,23 +13,23 @@ public abstract class AbstractPollingDependentResource extends AbstractExternalDependentResource> implements CacheKeyMapper { - public static final int DEFAULT_POLLING_PERIOD = 5000; - private long pollingPeriod; + public static final Duration DEFAULT_POLLING_PERIOD = Duration.ofMillis(5000); + private Duration pollingPeriod; protected AbstractPollingDependentResource(Class resourceType) { this(resourceType, DEFAULT_POLLING_PERIOD); } - public AbstractPollingDependentResource(Class resourceType, long pollingPeriod) { + public AbstractPollingDependentResource(Class resourceType, Duration pollingPeriod) { super(resourceType); this.pollingPeriod = pollingPeriod; } - public void setPollingPeriod(long pollingPeriod) { + public void setPollingPeriod(Duration pollingPeriod) { this.pollingPeriod = pollingPeriod; } - public long getPollingPeriod() { + public Duration getPollingPeriod() { return pollingPeriod; } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/external/PerResourcePollingDependentResource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/external/PerResourcePollingDependentResource.java index affc63cfd3..f315619cde 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/external/PerResourcePollingDependentResource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/external/PerResourcePollingDependentResource.java @@ -6,6 +6,7 @@ import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; import io.javaoperatorsdk.operator.api.reconciler.Ignore; import io.javaoperatorsdk.operator.processing.event.source.ExternalResourceCachingEventSource; +import io.javaoperatorsdk.operator.processing.event.source.polling.PerResourcePollingConfigurationBuilder; import io.javaoperatorsdk.operator.processing.event.source.polling.PerResourcePollingEventSource; @Ignore @@ -18,15 +19,19 @@ public PerResourcePollingDependentResource(Class resourceType) { super(resourceType); } - public PerResourcePollingDependentResource(Class resourceType, long pollingPeriod) { + public PerResourcePollingDependentResource(Class resourceType, Duration pollingPeriod) { super(resourceType, pollingPeriod); } @Override protected ExternalResourceCachingEventSource createEventSource( EventSourceContext

context) { - return new PerResourcePollingEventSource<>(this, context, - Duration.ofMillis(getPollingPeriod()), resourceType(), this); - } + return new PerResourcePollingEventSource<>(resourceType(), context, + new PerResourcePollingConfigurationBuilder<>( + this, getPollingPeriod()) + .withCacheKeyMapper(this) + .withName(name()) + .build()); + } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/external/PollingDependentResource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/external/PollingDependentResource.java index 3df1390d69..01860cb4c5 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/external/PollingDependentResource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/external/PollingDependentResource.java @@ -1,10 +1,13 @@ package io.javaoperatorsdk.operator.processing.dependent.external; +import java.time.Duration; + import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; import io.javaoperatorsdk.operator.api.reconciler.Ignore; import io.javaoperatorsdk.operator.processing.event.source.CacheKeyMapper; import io.javaoperatorsdk.operator.processing.event.source.ExternalResourceCachingEventSource; +import io.javaoperatorsdk.operator.processing.event.source.polling.PollingConfiguration; import io.javaoperatorsdk.operator.processing.event.source.polling.PollingEventSource; @Ignore @@ -19,7 +22,7 @@ public PollingDependentResource(Class resourceType, CacheKeyMapper cacheKe this.cacheKeyMapper = cacheKeyMapper; } - public PollingDependentResource(Class resourceType, long pollingPeriod, + public PollingDependentResource(Class resourceType, Duration pollingPeriod, CacheKeyMapper cacheKeyMapper) { super(resourceType, pollingPeriod); this.cacheKeyMapper = cacheKeyMapper; @@ -28,7 +31,8 @@ public PollingDependentResource(Class resourceType, long pollingPeriod, @Override protected ExternalResourceCachingEventSource createEventSource( EventSourceContext

context) { - return new PollingEventSource<>(this, getPollingPeriod(), resourceType(), cacheKeyMapper); + return new PollingEventSource<>(resourceType(), + new PollingConfiguration<>(name(), this, getPollingPeriod(), cacheKeyMapper)); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/CRUDKubernetesDependentResource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/CRUDKubernetesDependentResource.java index 5b0a1c3235..f4ccf647ed 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/CRUDKubernetesDependentResource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/CRUDKubernetesDependentResource.java @@ -22,4 +22,8 @@ public abstract class CRUDKubernetesDependentResource resourceType) { super(resourceType); } + + public CRUDKubernetesDependentResource(Class resourceType, String name) { + super(resourceType, name); + } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesDependentResource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesDependentResource.java index 266872bd38..c5dd08069e 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesDependentResource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesDependentResource.java @@ -2,7 +2,8 @@ import io.fabric8.kubernetes.api.model.GenericKubernetesResource; import io.fabric8.kubernetes.api.model.HasMetadata; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; import io.javaoperatorsdk.operator.processing.GroupVersionKind; public class GenericKubernetesDependentResource

@@ -19,8 +20,10 @@ public GenericKubernetesDependentResource(GroupVersionKindPlural groupVersionKin this.groupVersionKind = groupVersionKind; } - protected InformerConfiguration.InformerConfigurationBuilder informerConfigurationBuilder() { - return InformerConfiguration.from(groupVersionKind); + protected InformerEventSourceConfiguration.Builder informerConfigurationBuilder( + EventSourceContext

context) { + return InformerEventSourceConfiguration.from(groupVersionKind, + context.getPrimaryResourceClass()); } @SuppressWarnings("unused") diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesResourceMatcher.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesResourceMatcher.java index c71da5d5ad..00f68f36a7 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesResourceMatcher.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesResourceMatcher.java @@ -4,17 +4,14 @@ import java.util.Collections; import java.util.List; -import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.HasMetadata; -import io.fabric8.kubernetes.api.model.Secret; import io.fabric8.zjsonpatch.JsonDiff; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.processing.dependent.Matcher; import com.fasterxml.jackson.databind.JsonNode; -public class GenericKubernetesResourceMatcher - implements Matcher { +public class GenericKubernetesResourceMatcher { private static final String SPEC = "/spec"; private static final String METADATA = "/metadata"; @@ -26,40 +23,7 @@ public class GenericKubernetesResourceMatcher dependentResource; - private GenericKubernetesResourceMatcher(KubernetesDependentResource dependentResource) { - this.dependentResource = dependentResource; - } - - @SuppressWarnings({"unchecked", "rawtypes", "unused"}) - static Matcher matcherFor( - KubernetesDependentResource dependentResource) { - return new GenericKubernetesResourceMatcher(dependentResource); - } - - /** - * {@inheritDoc} - *

- * This implementation attempts to cover most common cases out of the box by considering - * non-additive changes to the resource's spec (if the resource in question has a {@code spec} - * field), making special provisions for {@link ConfigMap} and {@link Secret} resources. Additive - * changes (i.e. a field is added that previously didn't exist) are not considered as triggering a - * mismatch by default to account for validating webhooks that might add default values - * automatically when not present or some other controller adding labels and/or annotations. - *

- *

- * It should be noted that this implementation is potentially intensive because it generically - * attempts to cover common use cases by performing diffs on the JSON representation of objects. - * If performance is a concern, it might be easier / simpler to provide a {@link Matcher} - * implementation optimized for your use case. - *

- */ - @Override - public Result match(R actualResource, P primary, Context

context) { - var desired = dependentResource.desired(primary, context); - return match(desired, actualResource, false, false, false, context); - } /** * Determines whether the specified actual resource matches the specified desired resource, @@ -67,9 +31,6 @@ public Result match(R actualResource, P primary, Context

context) { * * @param desired the desired resource * @param actualResource the actual resource - * @param considerLabelsAndAnnotations {@code true} if labels and annotations will be checked for - * equality, {@code false} otherwise (meaning that metadata changes will be ignored for - * matching purposes) * @param labelsAndAnnotationsEquality if true labels and annotation match exactly in the actual * and desired state if false, additional elements are allowed in actual annotations. * Considered only if considerLabelsAndAnnotations is true. @@ -87,23 +48,26 @@ public Result match(R actualResource, P primary, Context

context) { * @param resource * @return results of matching */ - public static Result match(R desired, + public static Matcher.Result match(R desired, R actualResource, - boolean considerLabelsAndAnnotations, boolean labelsAndAnnotationsEquality, + boolean labelsAndAnnotationsEquality, boolean valuesEquality, Context

context) { - return match(desired, actualResource, considerLabelsAndAnnotations, + return match(desired, actualResource, labelsAndAnnotationsEquality, valuesEquality, context, EMPTY_ARRAY); } + public static Matcher.Result match(R desired, + R actualResource, Context

context) { + return match(desired, actualResource, + false, false, context, EMPTY_ARRAY); + } + /** * Determines whether the specified actual resource matches the specified desired resource, * possibly considering metadata and deeper equality checks. * * @param desired the desired resource * @param actualResource the actual resource - * @param considerLabelsAndAnnotations {@code true} if labels and annotations will be checked for - * equality, {@code false} otherwise (meaning that metadata changes will be ignored for - * matching purposes) * @param labelsAndAnnotationsEquality if true labels and annotation match exactly in the actual * and desired state if false, additional elements are allowed in actual annotations. * Considered only if considerLabelsAndAnnotations is true. @@ -114,11 +78,11 @@ public static Result match(R d * @param resource * @return results of matching */ - public static Result match(R desired, + public static Matcher.Result match(R desired, R actualResource, - boolean considerLabelsAndAnnotations, boolean labelsAndAnnotationsEquality, + boolean labelsAndAnnotationsEquality, Context

context, String... ignorePaths) { - return match(desired, actualResource, considerLabelsAndAnnotations, + return match(desired, actualResource, labelsAndAnnotationsEquality, false, context, ignorePaths); } @@ -133,9 +97,6 @@ public static Result match(R d * matches the desired state or not * @param primary the primary resource from which we want to compute the desired state * @param context the {@link Context} instance within which this method is called - * @param considerLabelsAndAnnotations {@code true} to consider the metadata of the actual - * resource when determining if it matches the desired state, {@code false} if matching - * should occur only considering the spec of the resources * @param labelsAndAnnotationsEquality if true labels and annotation match exactly in the actual * and desired state if false, additional elements are allowed in actual annotations. * Considered only if considerLabelsAndAnnotations is true. @@ -148,30 +109,30 @@ public static Result match(R d * match fails. * @return a {@link io.javaoperatorsdk.operator.processing.dependent.Matcher.Result} object */ - public static Result match( + public static Matcher.Result match( KubernetesDependentResource dependentResource, R actualResource, P primary, - Context

context, boolean considerLabelsAndAnnotations, + Context

context, boolean labelsAndAnnotationsEquality, String... ignorePaths) { final var desired = dependentResource.desired(primary, context); - return match(desired, actualResource, considerLabelsAndAnnotations, + return match(desired, actualResource, labelsAndAnnotationsEquality, context, ignorePaths); } - public static Result match( + public static Matcher.Result match( KubernetesDependentResource dependentResource, R actualResource, P primary, - Context

context, boolean considerLabelsAndAnnotations, + Context

context, + boolean specEquality, boolean labelsAndAnnotationsEquality, - boolean specEquality) { + String... ignorePaths) { final var desired = dependentResource.desired(primary, context); - return match(desired, actualResource, considerLabelsAndAnnotations, - labelsAndAnnotationsEquality, specEquality, context); + return match(desired, actualResource, + labelsAndAnnotationsEquality, specEquality, context, ignorePaths); } - public static Result match(R desired, - R actualResource, - boolean considerMetadata, boolean labelsAndAnnotationsEquality, boolean valuesEquality, + public static Matcher.Result match(R desired, + R actualResource, boolean labelsAndAnnotationsEquality, boolean valuesEquality, Context

context, String... ignoredPaths) { final List ignoreList = @@ -195,8 +156,7 @@ public static Result match(R d matched = match(valuesEquality, node, ignoreList); } else if (nodeIsChildOf(node, List.of(METADATA))) { // conditionally consider labels and annotations - if (considerMetadata - && nodeIsChildOf(node, List.of(METADATA_LABELS, METADATA_ANNOTATIONS))) { + if (nodeIsChildOf(node, List.of(METADATA_LABELS, METADATA_ANNOTATIONS))) { matched = match(labelsAndAnnotationsEquality, node, Collections.emptyList()); } } else if (!nodeIsChildOf(node, IGNORED_FIELDS)) { @@ -204,7 +164,7 @@ && nodeIsChildOf(node, List.of(METADATA_LABELS, METADATA_ANNOTATIONS))) { } } - return Result.computed(matched, desired); + return Matcher.Result.computed(matched, desired); } private static boolean match(boolean equality, JsonNode diff, @@ -227,20 +187,4 @@ static String getPath(JsonNode n) { return n.get(PATH).asText(); } - @Deprecated(forRemoval = true) - public static Result match( - KubernetesDependentResource dependentResource, R actualResource, P primary, - Context

context, boolean considerLabelsAndAnnotations, boolean specEquality) { - final var desired = dependentResource.desired(primary, context); - return match(desired, actualResource, considerLabelsAndAnnotations, specEquality, context); - } - - @Deprecated(forRemoval = true) - public static Result match( - KubernetesDependentResource dependentResource, R actualResource, P primary, - Context

context, boolean considerLabelsAndAnnotations, String... ignorePaths) { - final var desired = dependentResource.desired(primary, context); - return match(desired, actualResource, considerLabelsAndAnnotations, true, context, ignorePaths); - } - } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/updatermatcher/GenericResourceUpdaterMatcher.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericResourceUpdater.java similarity index 61% rename from operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/updatermatcher/GenericResourceUpdaterMatcher.java rename to operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericResourceUpdater.java index 43d0b2fedf..4a8fef01e9 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/updatermatcher/GenericResourceUpdaterMatcher.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericResourceUpdater.java @@ -1,30 +1,17 @@ -package io.javaoperatorsdk.operator.processing.dependent.kubernetes.updatermatcher; +package io.javaoperatorsdk.operator.processing.dependent.kubernetes; import java.util.Map; import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.client.utils.KubernetesSerialization; import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.processing.dependent.kubernetes.GenericKubernetesResourceMatcher; -import io.javaoperatorsdk.operator.processing.dependent.kubernetes.ResourceUpdaterMatcher; -public class GenericResourceUpdaterMatcher implements - ResourceUpdaterMatcher { +public class GenericResourceUpdater { private static final String METADATA = "metadata"; - private static final ResourceUpdaterMatcher INSTANCE = new GenericResourceUpdaterMatcher<>(); - - protected GenericResourceUpdaterMatcher() {} - - @SuppressWarnings("unchecked") - public static ResourceUpdaterMatcher updaterMatcherFor( - Class resourceType) { - return (ResourceUpdaterMatcher) INSTANCE; - } @SuppressWarnings("unchecked") - @Override - public R updateResource(R actual, R desired, Context context) { + public static R updateResource(R actual, R desired, Context context) { KubernetesSerialization kubernetesSerialization = context.getClient().getKubernetesSerialization(); Map actualMap = kubernetesSerialization.convertValue(actual, Map.class); @@ -41,12 +28,6 @@ public R updateResource(R actual, R desired, Context context) { return clonedActual; } - @Override - public boolean matches(R actual, R desired, Context context) { - return GenericKubernetesResourceMatcher.match(desired, actual, true, - false, false, context).matched(); - } - public static void updateLabelsAndAnnotation(K actual, K desired) { actual.getMetadata().getLabels().putAll(desired.getMetadata().getLabels()); actual.getMetadata().getAnnotations().putAll(desired.getMetadata().getAnnotations()); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependent.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependent.java index eb4c9cf9b0..818768474c 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependent.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependent.java @@ -5,73 +5,14 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import io.javaoperatorsdk.operator.api.reconciler.Constants; -import io.javaoperatorsdk.operator.api.reconciler.ResourceDiscriminator; -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.javaoperatorsdk.operator.api.config.informer.Informer; + -import static io.javaoperatorsdk.operator.api.reconciler.Constants.NO_VALUE_SET; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface KubernetesDependent { - String[] DEFAULT_NAMESPACES = {Constants.SAME_AS_CONTROLLER}; - - /** - * Specified which namespaces this Controller monitors for custom resources events. If no - * namespace is specified then the controller will monitor the namespaces configured for the - * controller. - * - * @return the array of namespaces this controller monitors - */ - String[] namespaces() default {Constants.SAME_AS_CONTROLLER}; - - /** - * Optional label selector used to identify the set of custom resources the controller will act - * upon. The label selector can be made of multiple comma separated requirements that acts as a - * logical AND operator. - * - * @return the label selector - */ - String labelSelector() default NO_VALUE_SET; - - /** - * Optional {@link OnAddFilter} to filter events sent to this KubernetesDependent - * - * @return the {@link OnAddFilter} filter implementation to use, defaulting to the interface - * itself if no value is set - */ - Class onAddFilter() default OnAddFilter.class; - - /** - * Optional {@link OnUpdateFilter} to filter events sent to this KubernetesDependent - * - * @return the {@link OnUpdateFilter} filter implementation to use, defaulting to the interface - * itself if no value is set - */ - Class onUpdateFilter() default OnUpdateFilter.class; - - /** - * Optional {@link OnDeleteFilter} to filter events sent to this KubernetesDependent - * - * @return the {@link OnDeleteFilter} filter implementation to use, defaulting to the interface - * itself if no value is set - */ - Class onDeleteFilter() default OnDeleteFilter.class; - - /** - * Optional {@link GenericFilter} to filter events sent to this KubernetesDependent - * - * @return the {@link GenericFilter} filter implementation to use, defaulting to the interface - * itself if no value is set - */ - Class genericFilter() default GenericFilter.class; - - Class resourceDiscriminator() default ResourceDiscriminator.class; - /** * Creates the resource only if did not exist before, this applies only if SSA is used. */ @@ -88,4 +29,7 @@ * global configuration */ BooleanWithUndefined useSSA() default BooleanWithUndefined.UNDEFINED; + + Informer informer() default @Informer; + } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependentConverter.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependentConverter.java index 7a434aecf1..3bfa8351d3 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependentConverter.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependentConverter.java @@ -1,69 +1,58 @@ package io.javaoperatorsdk.operator.processing.dependent.kubernetes; -import java.util.Arrays; -import java.util.Set; - import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.config.Utils; import io.javaoperatorsdk.operator.api.config.dependent.ConfigurationConverter; -import io.javaoperatorsdk.operator.api.reconciler.Constants; -import io.javaoperatorsdk.operator.api.reconciler.ResourceDiscriminator; -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.javaoperatorsdk.operator.api.config.dependent.DependentResourceSpec; +import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; import static io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResourceConfig.DEFAULT_CREATE_RESOURCE_ONLY_IF_NOT_EXISTING_WITH_SSA; public class KubernetesDependentConverter implements - ConfigurationConverter, KubernetesDependentResource> { + ConfigurationConverter> { @Override - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings("unchecked") public KubernetesDependentResourceConfig configFrom(KubernetesDependent configAnnotation, - ControllerConfiguration parentConfiguration, - Class> originatingClass) { - var namespaces = parentConfiguration.getNamespaces(); - var configuredNS = false; - String labelSelector = null; + DependentResourceSpec> spec, + ControllerConfiguration controllerConfig) { var createResourceOnlyIfNotExistingWithSSA = DEFAULT_CREATE_RESOURCE_ONLY_IF_NOT_EXISTING_WITH_SSA; - OnAddFilter onAddFilter = null; - OnUpdateFilter onUpdateFilter = null; - OnDeleteFilter onDeleteFilter = null; - GenericFilter genericFilter = null; - ResourceDiscriminator resourceDiscriminator = null; + Boolean useSSA = null; if (configAnnotation != null) { - if (!Arrays.equals(KubernetesDependent.DEFAULT_NAMESPACES, configAnnotation.namespaces())) { - namespaces = Set.of(configAnnotation.namespaces()); - configuredNS = true; - } - - final var fromAnnotation = configAnnotation.labelSelector(); - labelSelector = Constants.NO_VALUE_SET.equals(fromAnnotation) ? null : fromAnnotation; - - final var context = Utils.contextFor(parentConfiguration, originatingClass, - configAnnotation.annotationType()); - onAddFilter = Utils.instantiate(configAnnotation.onAddFilter(), OnAddFilter.class, context); - onUpdateFilter = - Utils.instantiate(configAnnotation.onUpdateFilter(), OnUpdateFilter.class, context); - onDeleteFilter = - Utils.instantiate(configAnnotation.onDeleteFilter(), OnDeleteFilter.class, context); - genericFilter = - Utils.instantiate(configAnnotation.genericFilter(), GenericFilter.class, context); - - resourceDiscriminator = - Utils.instantiate(configAnnotation.resourceDiscriminator(), ResourceDiscriminator.class, - context); createResourceOnlyIfNotExistingWithSSA = configAnnotation.createResourceOnlyIfNotExistingWithSSA(); useSSA = configAnnotation.useSSA().asBoolean(); } - return new KubernetesDependentResourceConfig(namespaces, labelSelector, configuredNS, - createResourceOnlyIfNotExistingWithSSA, - resourceDiscriminator, useSSA, onAddFilter, onUpdateFilter, onDeleteFilter, genericFilter); + var informerConfiguration = createInformerConfig(configAnnotation, + (DependentResourceSpec>) spec, + controllerConfig); + + return new KubernetesDependentResourceConfig<>(useSSA, createResourceOnlyIfNotExistingWithSSA, + informerConfiguration); + } + + @SuppressWarnings({"unchecked"}) + private InformerConfiguration createInformerConfig( + KubernetesDependent configAnnotation, + DependentResourceSpec> spec, + ControllerConfiguration controllerConfig) { + Class> dependentResourceClass = + (Class>) spec.getDependentResourceClass(); + + final var resourceType = controllerConfig.getConfigurationService().dependentResourceFactory() + .associatedResourceType(spec); + + InformerConfiguration.Builder config = InformerConfiguration.builder(resourceType); + if (configAnnotation != null) { + final var informerConfig = configAnnotation.informer(); + final var context = Utils.contextFor(controllerConfig, dependentResourceClass, + configAnnotation.annotationType()); + config = config.initFromAnnotation(informerConfig, context); + } + return config.buildForInformerEventSource(); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependentResource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependentResource.java index e7c7dbc0a7..dc401f654d 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependentResource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependentResource.java @@ -1,6 +1,7 @@ package io.javaoperatorsdk.operator.processing.dependent.kubernetes; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -8,20 +9,19 @@ import org.slf4j.LoggerFactory; import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.dsl.Resource; -import io.javaoperatorsdk.operator.OperatorException; import io.javaoperatorsdk.operator.ReconcilerUtils; import io.javaoperatorsdk.operator.api.config.dependent.Configured; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; -import io.javaoperatorsdk.operator.api.reconciler.Constants; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; import io.javaoperatorsdk.operator.api.reconciler.Ignore; import io.javaoperatorsdk.operator.api.reconciler.dependent.GarbageCollected; -import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.DependentResourceConfigurator; +import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.ConfiguredDependentResource; +import io.javaoperatorsdk.operator.processing.GroupVersionKind; import io.javaoperatorsdk.operator.processing.dependent.AbstractEventSourceHolderDependentResource; import io.javaoperatorsdk.operator.processing.dependent.Matcher.Result; -import io.javaoperatorsdk.operator.processing.dependent.kubernetes.updatermatcher.GenericResourceUpdaterMatcher; import io.javaoperatorsdk.operator.processing.event.ResourceID; import io.javaoperatorsdk.operator.processing.event.source.SecondaryToPrimaryMapper; import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; @@ -32,75 +32,24 @@ converter = KubernetesDependentConverter.class) public abstract class KubernetesDependentResource extends AbstractEventSourceHolderDependentResource> - implements DependentResourceConfigurator> { + implements ConfiguredDependentResource> { private static final Logger log = LoggerFactory.getLogger(KubernetesDependentResource.class); - private final ResourceUpdaterMatcher updaterMatcher; private final boolean garbageCollected = this instanceof GarbageCollected; private KubernetesDependentResourceConfig kubernetesDependentResourceConfig; private volatile Boolean useSSA; - @SuppressWarnings("unchecked") public KubernetesDependentResource(Class resourceType) { - super(resourceType); + this(resourceType, null); + } - updaterMatcher = this instanceof ResourceUpdaterMatcher - ? (ResourceUpdaterMatcher) this - : GenericResourceUpdaterMatcher.updaterMatcherFor(resourceType); + public KubernetesDependentResource(Class resourceType, String name) { + super(resourceType, name); } - @SuppressWarnings("unchecked") @Override public void configureWith(KubernetesDependentResourceConfig config) { this.kubernetesDependentResourceConfig = config; - var discriminator = kubernetesDependentResourceConfig.getResourceDiscriminator(); - if (discriminator != null) { - setResourceDiscriminator(discriminator); - } - } - - private void configureWith(String labelSelector, Set namespaces, - boolean inheritNamespacesOnChange, EventSourceContext

context) { - - if (namespaces.equals(Constants.SAME_AS_CONTROLLER_NAMESPACES_SET)) { - namespaces = context.getControllerConfiguration().getNamespaces(); - } - - var ic = informerConfigurationBuilder() - .withLabelSelector(labelSelector) - .withSecondaryToPrimaryMapper(getSecondaryToPrimaryMapper()) - .withNamespaces(namespaces, inheritNamespacesOnChange) - .build(); - - configureWith(new InformerEventSource<>(ic, context)); - } - - // just to seamlessly handle GenericKubernetesDependentResource - protected InformerConfiguration.InformerConfigurationBuilder informerConfigurationBuilder() { - return InformerConfiguration.from(resourceType()); - } - - @SuppressWarnings("unchecked") - private SecondaryToPrimaryMapper getSecondaryToPrimaryMapper() { - if (this instanceof SecondaryToPrimaryMapper) { - return (SecondaryToPrimaryMapper) this; - } else if (garbageCollected) { - return Mappers.fromOwnerReferences(false); - } else if (useNonOwnerRefBasedSecondaryToPrimaryMapping()) { - return Mappers.fromDefaultAnnotations(); - } else { - throw new OperatorException("Provide a SecondaryToPrimaryMapper to associate " + - "this resource with the primary resource. DependentResource: " + getClass().getName()); - } - } - - /** - * Use to share informers between event more resources. - * - * @param informerEventSource informer to use - */ - public void configureWith(InformerEventSource informerEventSource) { - setEventSource(informerEventSource); } @SuppressWarnings("unused") @@ -136,7 +85,7 @@ public R update(R actual, R desired, P primary, Context

context) { .fieldManager(context.getControllerConfiguration().fieldManager()) .forceConflicts().serverSideApply(); } else { - var updatedActual = updaterMatcher.updateResource(actual, desired, context); + var updatedActual = GenericResourceUpdater.updateResource(actual, desired, context); updatedResource = prepare(context, updatedActual, primary, "Updating").update(); } log.debug("Resource version after update: {}", @@ -147,18 +96,10 @@ public R update(R actual, R desired, P primary, Context

context) { @Override public Result match(R actualResource, P primary, Context

context) { final var desired = desired(primary, context); - return match(actualResource, desired, primary, updaterMatcher, context); + return match(actualResource, desired, primary, context); } - @SuppressWarnings({"unused", "unchecked"}) - public Result match(R actualResource, R desired, P primary, Context

context) { - return match(actualResource, desired, primary, - (ResourceUpdaterMatcher) GenericResourceUpdaterMatcher - .updaterMatcherFor(actualResource.getClass()), - context); - } - - public Result match(R actualResource, R desired, P primary, ResourceUpdaterMatcher matcher, + public Result match(R actualResource, R desired, P primary, Context

context) { final boolean matches; addMetadata(true, actualResource, desired, primary, context); @@ -166,7 +107,8 @@ public Result match(R actualResource, R desired, P primary, ResourceUpdaterMa matches = SSABasedGenericKubernetesResourceMatcher.getInstance() .matches(actualResource, desired, context); } else { - matches = matcher.matches(actualResource, desired, context); + matches = GenericKubernetesResourceMatcher.match(desired, actualResource, + false, false, context).matched(); } return Result.computed(matches, desired); } @@ -236,48 +178,72 @@ protected void addReferenceHandlingMetadata(R desired, P primary) { } @Override - @SuppressWarnings("unchecked") protected InformerEventSource createEventSource(EventSourceContext

context) { - if (kubernetesDependentResourceConfig != null) { - // sets the filters for the dependent resource, which are applied by parent class - onAddFilter = kubernetesDependentResourceConfig.onAddFilter(); - onUpdateFilter = kubernetesDependentResourceConfig.onUpdateFilter(); - onDeleteFilter = kubernetesDependentResourceConfig.onDeleteFilter(); - genericFilter = kubernetesDependentResourceConfig.genericFilter(); - var discriminator = kubernetesDependentResourceConfig.getResourceDiscriminator(); - if (discriminator != null) { - setResourceDiscriminator(discriminator); - } - configureWith(kubernetesDependentResourceConfig.labelSelector(), - kubernetesDependentResourceConfig.namespaces(), - !kubernetesDependentResourceConfig.wereNamespacesConfigured(), context); - } else { - configureWith(null, context.getControllerConfiguration().getNamespaces(), - true, context); - log.warn( - "Using default configuration for {} KubernetesDependentResource, call configureWith to provide configuration", - resourceType().getSimpleName()); + final InformerEventSourceConfiguration.Builder configBuilder = + informerConfigurationBuilder(context) + .withSecondaryToPrimaryMapper(getSecondaryToPrimaryMapper(context).orElseThrow()) + .withName(name()); + + // update configuration from annotation if specified + if (kubernetesDependentResourceConfig != null + && kubernetesDependentResourceConfig.informerConfig() != null) { + configBuilder.updateFrom(kubernetesDependentResourceConfig.informerConfig()); } + + var es = new InformerEventSource<>(configBuilder.build(), context); + setEventSource(es); return eventSource().orElseThrow(); } + /** + * To handle {@link io.fabric8.kubernetes.api.model.GenericKubernetesResource} based dependents. + */ + protected InformerEventSourceConfiguration.Builder informerConfigurationBuilder( + EventSourceContext

context) { + return InformerEventSourceConfiguration.from(resourceType(), context.getPrimaryResourceClass()); + } + private boolean useNonOwnerRefBasedSecondaryToPrimaryMapping() { return !garbageCollected && isCreatable(); } protected void addSecondaryToPrimaryMapperAnnotations(R desired, P primary) { addSecondaryToPrimaryMapperAnnotations(desired, primary, Mappers.DEFAULT_ANNOTATION_FOR_NAME, - Mappers.DEFAULT_ANNOTATION_FOR_NAMESPACE); + Mappers.DEFAULT_ANNOTATION_FOR_NAMESPACE, Mappers.DEFAULT_ANNOTATION_FOR_PRIMARY_TYPE); } protected void addSecondaryToPrimaryMapperAnnotations(R desired, P primary, String nameKey, - String namespaceKey) { + String namespaceKey, String typeKey) { var annotations = desired.getMetadata().getAnnotations(); annotations.put(nameKey, primary.getMetadata().getName()); var primaryNamespaces = primary.getMetadata().getNamespace(); if (primaryNamespaces != null) { annotations.put(namespaceKey, primary.getMetadata().getNamespace()); } + annotations.put(typeKey, GroupVersionKind.gvkFor(primary.getClass()).toSimpleString()); + } + + @Override + protected Optional selectTargetSecondaryResource(Set secondaryResources, P primary, + Context

context) { + ResourceID managedResourceID = targetSecondaryResourceID(primary, context); + return secondaryResources.stream() + .filter(r -> r.getMetadata().getName().equals(managedResourceID.getName()) && + Objects.equals(r.getMetadata().getNamespace(), + managedResourceID.getNamespace().orElse(null))) + .findFirst(); + } + + /** + * Override this method in order to optimize and not compute the desired when selecting the target + * secondary resource. Simply, a static ResourceID can be returned. + * + * @param primary resource + * @param context of current reconciliation + * @return id of the target managed resource + */ + protected ResourceID targetSecondaryResourceID(P primary, Context

context) { + return ResourceID.fromResource(desired(primary, context)); } protected boolean addOwnerReference() { @@ -299,4 +265,20 @@ public boolean isDeletable() { return super.isDeletable() && !garbageCollected; } + @SuppressWarnings("unchecked") + protected Optional> getSecondaryToPrimaryMapper( + EventSourceContext

context) { + if (this instanceof SecondaryToPrimaryMapper) { + return Optional.of((SecondaryToPrimaryMapper) this); + } else { + var clustered = !Namespaced.class.isAssignableFrom(context.getPrimaryResourceClass()); + if (garbageCollected) { + return Optional + .of(Mappers.fromOwnerReferences(context.getPrimaryResourceClass(), clustered)); + } else if (isCreatable()) { + return Optional.of(Mappers.fromDefaultAnnotations(context.getPrimaryResourceClass())); + } + } + return Optional.empty(); + } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependentResourceConfig.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependentResourceConfig.java index 9b3838831d..2b419c2d0d 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependentResourceConfig.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependentResourceConfig.java @@ -1,122 +1,36 @@ package io.javaoperatorsdk.operator.processing.dependent.kubernetes; -import java.util.Optional; -import java.util.Set; -import io.javaoperatorsdk.operator.api.reconciler.Constants; -import io.javaoperatorsdk.operator.api.reconciler.ResourceDiscriminator; -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.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; -import static io.javaoperatorsdk.operator.api.reconciler.Constants.NO_VALUE_SET; -public class KubernetesDependentResourceConfig { +public class KubernetesDependentResourceConfig { public static final boolean DEFAULT_CREATE_RESOURCE_ONLY_IF_NOT_EXISTING_WITH_SSA = true; - private Set namespaces; - private String labelSelector; - private final boolean namespacesWereConfigured; - private final boolean createResourceOnlyIfNotExistingWithSSA; - private final ResourceDiscriminator resourceDiscriminator; private final Boolean useSSA; + private final boolean createResourceOnlyIfNotExistingWithSSA; + private final InformerConfiguration informerConfig; - private final OnAddFilter onAddFilter; - private final OnUpdateFilter onUpdateFilter; - private final OnDeleteFilter onDeleteFilter; - private final GenericFilter genericFilter; - - public KubernetesDependentResourceConfig() { - this(Constants.SAME_AS_CONTROLLER_NAMESPACES_SET, NO_VALUE_SET, true, - DEFAULT_CREATE_RESOURCE_ONLY_IF_NOT_EXISTING_WITH_SSA, - null, null, null, - null, null, null); - } - - public KubernetesDependentResourceConfig(Set namespaces, - String labelSelector, - boolean configuredNS, - boolean createResourceOnlyIfNotExistingWithSSA, - ResourceDiscriminator resourceDiscriminator, + public KubernetesDependentResourceConfig( Boolean useSSA, - OnAddFilter onAddFilter, - OnUpdateFilter onUpdateFilter, - OnDeleteFilter onDeleteFilter, GenericFilter genericFilter) { - this.namespaces = namespaces; - this.labelSelector = labelSelector; - this.namespacesWereConfigured = configuredNS; - this.createResourceOnlyIfNotExistingWithSSA = createResourceOnlyIfNotExistingWithSSA; - this.onAddFilter = onAddFilter; - this.onUpdateFilter = onUpdateFilter; - this.onDeleteFilter = onDeleteFilter; - this.genericFilter = genericFilter; - this.resourceDiscriminator = resourceDiscriminator; + boolean createResourceOnlyIfNotExistingWithSSA, + InformerConfiguration informerConfig) { this.useSSA = useSSA; - } - - // use builder instead - @Deprecated(forRemoval = true) - public KubernetesDependentResourceConfig(Set namespaces, String labelSelector) { - this(namespaces, labelSelector, true, DEFAULT_CREATE_RESOURCE_ONLY_IF_NOT_EXISTING_WITH_SSA, - null, null, null, - null, null, null); - } - - // use builder instead - @Deprecated(forRemoval = true) - public KubernetesDependentResourceConfig setLabelSelector(String labelSelector) { - this.labelSelector = labelSelector; - return this; - } - - public Set namespaces() { - return namespaces; - } - - public String labelSelector() { - return labelSelector; - } - - public boolean wereNamespacesConfigured() { - return namespacesWereConfigured; - } - - @SuppressWarnings("rawtypes") - public OnAddFilter onAddFilter() { - return onAddFilter; + this.createResourceOnlyIfNotExistingWithSSA = createResourceOnlyIfNotExistingWithSSA; + this.informerConfig = informerConfig; } public boolean createResourceOnlyIfNotExistingWithSSA() { return createResourceOnlyIfNotExistingWithSSA; } - public OnUpdateFilter onUpdateFilter() { - return onUpdateFilter; - } - - public OnDeleteFilter onDeleteFilter() { - return onDeleteFilter; - } - - public GenericFilter genericFilter() { - return genericFilter; - } - - @SuppressWarnings("rawtypes") - public ResourceDiscriminator getResourceDiscriminator() { - return resourceDiscriminator; - } - - @SuppressWarnings("unused") - protected void setNamespaces(Set namespaces) { - if (!wereNamespacesConfigured() && namespaces != null && !namespaces.isEmpty()) { - this.namespaces = namespaces; - } + public Boolean useSSA() { + return useSSA; } - public Optional useSSA() { - return Optional.ofNullable(useSSA); + public InformerConfiguration informerConfig() { + return informerConfig; } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependentResourceConfigBuilder.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependentResourceConfigBuilder.java index a18d8b8a41..3610cb074b 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependentResourceConfigBuilder.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/KubernetesDependentResourceConfigBuilder.java @@ -1,86 +1,38 @@ package io.javaoperatorsdk.operator.processing.dependent.kubernetes; -import java.util.Set; -import io.javaoperatorsdk.operator.api.reconciler.Constants; -import io.javaoperatorsdk.operator.api.reconciler.ResourceDiscriminator; -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.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; -public final class KubernetesDependentResourceConfigBuilder { +public final class KubernetesDependentResourceConfigBuilder { - private Set namespaces = Constants.SAME_AS_CONTROLLER_NAMESPACES_SET; - private String labelSelector; private boolean createResourceOnlyIfNotExistingWithSSA; - private ResourceDiscriminator resourceDiscriminator; - private Boolean useSSA; - private OnAddFilter onAddFilter; - private OnUpdateFilter onUpdateFilter; - private OnDeleteFilter onDeleteFilter; - private GenericFilter genericFilter; + private Boolean useSSA = null; + private InformerConfiguration informerConfiguration; public KubernetesDependentResourceConfigBuilder() {} - public static KubernetesDependentResourceConfigBuilder aKubernetesDependentResourceConfig() { - return new KubernetesDependentResourceConfigBuilder<>(); - } - - public KubernetesDependentResourceConfigBuilder withNamespaces(Set namespaces) { - this.namespaces = namespaces; - return this; - } - - public KubernetesDependentResourceConfigBuilder withLabelSelector(String labelSelector) { - this.labelSelector = labelSelector; - return this; - } - + @SuppressWarnings("unused") public KubernetesDependentResourceConfigBuilder withCreateResourceOnlyIfNotExistingWithSSA( boolean createResourceOnlyIfNotExistingWithSSA) { this.createResourceOnlyIfNotExistingWithSSA = createResourceOnlyIfNotExistingWithSSA; return this; } - public KubernetesDependentResourceConfigBuilder withResourceDiscriminator( - ResourceDiscriminator resourceDiscriminator) { - this.resourceDiscriminator = resourceDiscriminator; - return this; - } - - public KubernetesDependentResourceConfigBuilder withUseSSA(Boolean useSSA) { + public KubernetesDependentResourceConfigBuilder withUseSSA(boolean useSSA) { this.useSSA = useSSA; return this; } - public KubernetesDependentResourceConfigBuilder withOnAddFilter(OnAddFilter onAddFilter) { - this.onAddFilter = onAddFilter; - return this; - } - - public KubernetesDependentResourceConfigBuilder withOnUpdateFilter( - OnUpdateFilter onUpdateFilter) { - this.onUpdateFilter = onUpdateFilter; - return this; - } - - public KubernetesDependentResourceConfigBuilder withOnDeleteFilter( - OnDeleteFilter onDeleteFilter) { - this.onDeleteFilter = onDeleteFilter; - return this; - } - - public KubernetesDependentResourceConfigBuilder withGenericFilter( - GenericFilter genericFilter) { - this.genericFilter = genericFilter; + public KubernetesDependentResourceConfigBuilder withKubernetesDependentInformerConfig( + InformerConfiguration informerConfiguration) { + this.informerConfiguration = informerConfiguration; return this; } public KubernetesDependentResourceConfig build() { - return new KubernetesDependentResourceConfig<>(namespaces, labelSelector, - namespaces != Constants.SAME_AS_CONTROLLER_NAMESPACES_SET, - createResourceOnlyIfNotExistingWithSSA, resourceDiscriminator, useSSA, onAddFilter, - onUpdateFilter, onDeleteFilter, genericFilter); + return new KubernetesDependentResourceConfig<>( + useSSA, createResourceOnlyIfNotExistingWithSSA, + informerConfiguration); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/SSABasedGenericKubernetesResourceMatcher.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/SSABasedGenericKubernetesResourceMatcher.java index 5987352960..261ab6c825 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/SSABasedGenericKubernetesResourceMatcher.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/SSABasedGenericKubernetesResourceMatcher.java @@ -4,6 +4,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -11,7 +12,6 @@ import java.util.Optional; import java.util.Set; import java.util.TreeMap; -import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,6 +28,9 @@ import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.processing.LoggingUtils; +import com.github.difflib.DiffUtils; +import com.github.difflib.UnifiedDiffUtils; + import static io.javaoperatorsdk.operator.processing.dependent.kubernetes.ResourceRequirementsSanitizer.sanitizeResourceRequirements; /** @@ -104,20 +107,73 @@ public boolean matches(R actual, R desired, Context context) { removeIrrelevantValues(desiredMap); - if (LoggingUtils.isNotSensitiveResource(desired)) { - log.debug("Pruned actual: \n {} \n desired: \n {} ", prunedActual, desiredMap); + var matches = prunedActual.equals(desiredMap); + if (!matches && log.isDebugEnabled() && LoggingUtils.isNotSensitiveResource(desired)) { + var diff = getDiff(prunedActual, desiredMap, objectMapper); + log.debug( + "Diff between actual and desired state for resource: {} with name: {} in namespace: {} is:\n{}", + actual.getKind(), actual.getMetadata().getName(), actual.getMetadata().getNamespace(), + diff); + } + return matches; + } + + private String getDiff(Map prunedActualMap, Map desiredMap, + KubernetesSerialization serialization) { + var actualYaml = serialization.asYaml(sortMap(prunedActualMap)); + var desiredYaml = serialization.asYaml(sortMap(desiredMap)); + if (log.isTraceEnabled()) { + log.trace("Pruned actual resource:\n {} \ndesired resource:\n {} ", actualYaml, desiredYaml); } - return prunedActual.equals(desiredMap); + var patch = DiffUtils.diff(actualYaml.lines().toList(), desiredYaml.lines().toList()); + var unifiedDiff = + UnifiedDiffUtils.generateUnifiedDiff("", "", actualYaml.lines().toList(), patch, 1); + return String.join("\n", unifiedDiff); + } + + @SuppressWarnings("unchecked") + Map sortMap(Map map) { + var sortedKeys = new ArrayList<>(map.keySet()); + Collections.sort(sortedKeys); + + var sortedMap = new LinkedHashMap(); + for (var key : sortedKeys) { + var value = map.get(key); + if (value instanceof Map) { + sortedMap.put(key, sortMap((Map) value)); + } else if (value instanceof List) { + sortedMap.put(key, sortListItems((List) value)); + } else { + sortedMap.put(key, value); + } + } + return sortedMap; + } + + @SuppressWarnings("unchecked") + List sortListItems(List list) { + var sortedList = new ArrayList<>(); + for (var item : list) { + if (item instanceof Map) { + sortedList.add(sortMap((Map) item)); + } else if (item instanceof List) { + sortedList.add(sortListItems((List) item)); + } else { + sortedList.add(item); + } + } + return sortedList; } /** * Correct for known issue with SSA */ private void sanitizeState(R actual, R desired, Map actualMap) { - if (actual instanceof StatefulSet) { - var actualSpec = (((StatefulSet) actual)).getSpec(); - var desiredSpec = (((StatefulSet) desired)).getSpec(); + if (actual instanceof StatefulSet actualStatefulSet + && desired instanceof StatefulSet desiredStatefulSet) { + var actualSpec = actualStatefulSet.getSpec(); + var desiredSpec = desiredStatefulSet.getSpec(); int claims = desiredSpec.getVolumeClaimTemplates().size(); if (claims == actualSpec.getVolumeClaimTemplates().size()) { for (int i = 0; i < claims; i++) { @@ -135,18 +191,21 @@ private void sanitizeState(R actual, R desired, Map actualMap) { } } sanitizeResourceRequirements(actualMap, actualSpec.getTemplate(), desiredSpec.getTemplate()); - } else if (actual instanceof Deployment) { + } else if (actual instanceof Deployment actualDeployment + && desired instanceof Deployment desiredDeployment) { sanitizeResourceRequirements(actualMap, - ((Deployment) actual).getSpec().getTemplate(), - ((Deployment) desired).getSpec().getTemplate()); - } else if (actual instanceof ReplicaSet) { + actualDeployment.getSpec().getTemplate(), + desiredDeployment.getSpec().getTemplate()); + } else if (actual instanceof ReplicaSet actualReplicaSet + && desired instanceof ReplicaSet desiredReplicaSet) { sanitizeResourceRequirements(actualMap, - ((ReplicaSet) actual).getSpec().getTemplate(), - ((ReplicaSet) desired).getSpec().getTemplate()); - } else if (actual instanceof DaemonSet) { + actualReplicaSet.getSpec().getTemplate(), + desiredReplicaSet.getSpec().getTemplate()); + } else if (actual instanceof DaemonSet actualDaemonSet + && desired instanceof DaemonSet desiredDaemonSet) { sanitizeResourceRequirements(actualMap, - ((DaemonSet) actual).getSpec().getTemplate(), - ((DaemonSet) desired).getSpec().getTemplate()); + actualDaemonSet.getSpec().getTemplate(), + desiredDaemonSet.getSpec().getTemplate()); } } @@ -331,13 +390,13 @@ private static Map.Entry> selectListEntryBasedOnKey } } if (possibleTargets.isEmpty()) { - throw new IllegalStateException("Cannot find list element for key: " + key + ", in map: " - + values.stream().map(Map::keySet).collect(Collectors.toList())); + throw new IllegalStateException("Cannot find list element for key: " + key + " in map: " + + values.stream().map(Map::keySet).toList()); } if (possibleTargets.size() > 1) { throw new IllegalStateException( "More targets found in list element for key: " + key + " in map: " - + values.stream().map(Map::keySet).collect(Collectors.toList())); + + values.stream().map(Map::keySet).toList()); } return new AbstractMap.SimpleEntry<>(lastIndex, possibleTargets.get(0)); } @@ -349,7 +408,7 @@ private Optional checkIfFieldManagerExists(R actual, String // field manager name. .filter( f -> f.getManager().equals(fieldManager) && f.getOperation().equals(APPLY_OPERATION)) - .collect(Collectors.toList()); + .toList(); if (targetManagedFields.isEmpty()) { log.debug("No field manager exists for resource: {} with name: {} and operation {}", actual.getKind(), diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/AbstractWorkflowExecutor.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/AbstractWorkflowExecutor.java index 56e5e17d07..eb0f3f7e83 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/AbstractWorkflowExecutor.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/AbstractWorkflowExecutor.java @@ -1,12 +1,12 @@ package io.javaoperatorsdk.operator.processing.dependent.workflow; +import java.util.HashMap; import java.util.Map; -import java.util.Map.Entry; import java.util.Optional; -import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; +import java.util.function.Function; import java.util.stream.Collectors; import org.slf4j.Logger; @@ -18,27 +18,26 @@ import io.javaoperatorsdk.operator.processing.event.ResourceID; @SuppressWarnings("rawtypes") -public abstract class AbstractWorkflowExecutor

{ +abstract class AbstractWorkflowExecutor

{ - protected final Workflow

workflow; + protected final DefaultWorkflow

workflow; protected final P primary; protected final ResourceID primaryID; protected final Context

context; + protected final Map, WorkflowResult.DetailBuilder> results; /** * Covers both deleted and reconciled */ - private final Set alreadyVisited = ConcurrentHashMap.newKeySet(); private final Map> actualExecutions = new ConcurrentHashMap<>(); - private final Map exceptionsDuringExecution = - new ConcurrentHashMap<>(); private final ExecutorService executorService; - public AbstractWorkflowExecutor(Workflow

workflow, P primary, Context

context) { + protected AbstractWorkflowExecutor(DefaultWorkflow

workflow, P primary, Context

context) { this.workflow = workflow; this.primary = primary; this.context = context; this.primaryID = ResourceID.fromResource(primary); executorService = context.getWorkflowExecutorService(); + results = new HashMap<>(workflow.getDependentResourcesByName().size()); } protected abstract Logger logger(); @@ -75,11 +74,31 @@ protected boolean noMoreExecutionsScheduled() { } protected boolean alreadyVisited(DependentResourceNode dependentResourceNode) { - return alreadyVisited.contains(dependentResourceNode); + return getResultFlagFor(dependentResourceNode, WorkflowResult.DetailBuilder::isVisited); } - protected void markAsVisited(DependentResourceNode dependentResourceNode) { - alreadyVisited.add(dependentResourceNode); + protected boolean postDeleteConditionNotMet(DependentResourceNode drn) { + return getResultFlagFor(drn, WorkflowResult.DetailBuilder::hasPostDeleteConditionNotMet); + } + + protected boolean isMarkedForDelete(DependentResourceNode drn) { + return getResultFlagFor(drn, WorkflowResult.DetailBuilder::isMarkedForDelete); + } + + protected synchronized WorkflowResult.DetailBuilder createOrGetResultFor( + DependentResourceNode dependentResourceNode) { + return results.computeIfAbsent(dependentResourceNode, + unused -> new WorkflowResult.DetailBuilder()); + } + + protected synchronized Optional> getResultFor( + DependentResourceNode dependentResourceNode) { + return Optional.ofNullable(results.get(dependentResourceNode)); + } + + protected boolean getResultFlagFor(DependentResourceNode dependentResourceNode, + Function, Boolean> flag) { + return getResultFor(dependentResourceNode).map(flag).orElse(false); } protected boolean isExecutingNow(DependentResourceNode dependentResourceNode) { @@ -94,17 +113,15 @@ protected void markAsExecuting(DependentResourceNode dependentResourceNode protected synchronized void handleExceptionInExecutor( DependentResourceNode dependentResourceNode, RuntimeException e) { - exceptionsDuringExecution.put(dependentResourceNode, e); + createOrGetResultFor(dependentResourceNode).withError(e); } - protected boolean isInError(DependentResourceNode dependentResourceNode) { - return exceptionsDuringExecution.containsKey(dependentResourceNode); + protected boolean isReady(DependentResourceNode dependentResourceNode) { + return getResultFlagFor(dependentResourceNode, WorkflowResult.DetailBuilder::isReady); } - protected Map getErroredDependents() { - return exceptionsDuringExecution.entrySet().stream() - .collect( - Collectors.toMap(e -> e.getKey().getDependentResource(), Entry::getValue)); + protected boolean isInError(DependentResourceNode dependentResourceNode) { + return getResultFlagFor(dependentResourceNode, WorkflowResult.DetailBuilder::hasError); } protected synchronized void handleNodeExecutionFinish( @@ -116,9 +133,19 @@ protected synchronized void handleNodeExecutionFinish( } } - protected boolean isConditionMet(Optional> condition, - DependentResource dependentResource) { - return condition.map(c -> c.isMet(dependentResource, primary, context)).orElse(true); + @SuppressWarnings({"unchecked", "OptionalUsedAsFieldOrParameterType"}) + protected boolean isConditionMet( + Optional> condition, + DependentResourceNode dependentResource) { + final var dr = dependentResource.getDependentResource(); + return condition.map(c -> { + final DetailedCondition.Result r = c.detailedIsMet(dr, primary, context); + synchronized (this) { + results.computeIfAbsent(dependentResource, unused -> new WorkflowResult.DetailBuilder()) + .withResultForCondition(c, r); + } + return r; + }).orElse(DetailedCondition.Result.metWithoutResult).isSuccess(); } protected void submit(DependentResourceNode dependentResourceNode, @@ -133,18 +160,22 @@ protected void registerOrDeregisterEventSourceBasedOnActivation( boolean activationConditionMet, DependentResourceNode dependentResourceNode) { if (dependentResourceNode.getActivationCondition().isPresent()) { + final var dr = dependentResourceNode.getDependentResource(); + final var eventSourceRetriever = context.eventSourceRetriever(); + var eventSource = + dr.eventSource(eventSourceRetriever.eventSourceContextForDynamicRegistration()); if (activationConditionMet) { - var eventSource = - dependentResourceNode.getDependentResource().eventSource(context.eventSourceRetriever() - .eventSourceContextForDynamicRegistration()); var es = eventSource.orElseThrow(); - context.eventSourceRetriever() - .dynamicallyRegisterEventSource(dependentResourceNode.getName(), es); - + eventSourceRetriever.dynamicallyRegisterEventSource(es); } else { - context.eventSourceRetriever() - .dynamicallyDeRegisterEventSource(dependentResourceNode.getName()); + eventSourceRetriever.dynamicallyDeRegisterEventSource(eventSource.orElseThrow().name()); } } } + + protected synchronized Map> asDetails() { + return results.entrySet().stream() + .collect( + Collectors.toMap(e -> e.getKey().getDependentResource(), e -> e.getValue().build())); + } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/CRDPresentActivationCondition.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/CRDPresentActivationCondition.java new file mode 100644 index 0000000000..5a60b63d41 --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/CRDPresentActivationCondition.java @@ -0,0 +1,132 @@ +package io.javaoperatorsdk.operator.processing.dependent.workflow; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinition; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; + +/** + * A generic CRD checking activation condition. Makes sure that the CRD is not checked unnecessarily + * even used in multiple condition. By default, it checks CRD at most 10 times with a delay at least + * 10 seconds. To fully customize CRD check trigger behavior you can extend this class and override + * the {@link CRDPresentActivationCondition#shouldCheckStateNow(CRDCheckState)} method. + * + * @param the resource type associated with the CRD to check for presence + * @param

the primary resource type associated with the reconciler processing dependents + * associated with this condition + */ +public class CRDPresentActivationCondition + implements Condition { + + public static final int DEFAULT_CRD_CHECK_LIMIT = 10; + public static final Duration DEFAULT_CRD_CHECK_INTERVAL = Duration.ofSeconds(10); + + private static final Map crdPresenceCache = new ConcurrentHashMap<>(); + + private final CRDPresentChecker crdPresentChecker; + private final int checkLimit; + private final Duration crdCheckInterval; + + public CRDPresentActivationCondition() { + this(DEFAULT_CRD_CHECK_LIMIT, DEFAULT_CRD_CHECK_INTERVAL); + } + + public CRDPresentActivationCondition(int checkLimit, Duration crdCheckInterval) { + this(new CRDPresentChecker(), checkLimit, crdCheckInterval); + } + + // for testing purposes only + CRDPresentActivationCondition(CRDPresentChecker crdPresentChecker, int checkLimit, + Duration crdCheckInterval) { + this.crdPresentChecker = crdPresentChecker; + this.checkLimit = checkLimit; + this.crdCheckInterval = crdCheckInterval; + } + + @Override + public boolean isMet(DependentResource dependentResource, + P primary, Context

context) { + + var resourceClass = dependentResource.resourceType(); + final var crdName = HasMetadata.getFullResourceName(resourceClass); + + var crdCheckState = crdPresenceCache.computeIfAbsent(crdName, + g -> new CRDCheckState()); + + synchronized (crdCheckState) { + if (shouldCheckStateNow(crdCheckState)) { + boolean isPresent = crdPresentChecker + .checkIfCRDPresent(crdName, context.getClient()); + crdCheckState.checkedNow(isPresent); + } + } + + if (crdCheckState.isCrdPresent() == null) { + throw new IllegalStateException("State should be already checked at this point."); + } + return crdCheckState.isCrdPresent(); + } + + /** + * Override this method to fine tune when the crd state should be refreshed; + */ + protected boolean shouldCheckStateNow(CRDCheckState crdCheckState) { + if (crdCheckState.isCrdPresent() == null) { + return true; + } + // assumption is that if CRD is present, it is not deleted anymore + if (crdCheckState.isCrdPresent()) { + return false; + } + if (crdCheckState.getCheckCount() >= checkLimit) { + return false; + } + if (crdCheckState.getLastChecked() == null) { + return true; + } + return LocalDateTime.now().isAfter(crdCheckState.getLastChecked().plus(crdCheckInterval)); + } + + public static class CRDCheckState { + private Boolean crdPresent; + private LocalDateTime lastChecked; + private int checkCount = 0; + + public void checkedNow(boolean crdPresent) { + this.crdPresent = crdPresent; + lastChecked = LocalDateTime.now(); + checkCount++; + } + + public Boolean isCrdPresent() { + return crdPresent; + } + + public LocalDateTime getLastChecked() { + return lastChecked; + } + + public int getCheckCount() { + return checkCount; + } + } + + public static class CRDPresentChecker { + boolean checkIfCRDPresent(String crdName, KubernetesClient client) { + return client.resources(CustomResourceDefinition.class) + .withName(crdName).get() != null; + } + } + + /** For testing purposes only */ + public static void clearState() { + crdPresenceCache.clear(); + } + +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/Condition.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/Condition.java index 87690ed69b..de96c99ca5 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/Condition.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/Condition.java @@ -6,6 +6,10 @@ public interface Condition { + enum Type { + ACTIVATION, DELETE, READY, RECONCILE + } + /** * Checks whether a condition holds true for a given * {@link io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource} based on the diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ConditionWithType.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ConditionWithType.java new file mode 100644 index 0000000000..de95830a92 --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ConditionWithType.java @@ -0,0 +1,31 @@ +package io.javaoperatorsdk.operator.processing.dependent.workflow; + +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; + +class ConditionWithType implements DetailedCondition { + private final Condition condition; + private final Type type; + + ConditionWithType(Condition condition, Type type) { + this.condition = condition; + this.type = type; + } + + public Type type() { + return type; + } + + @SuppressWarnings("unchecked") + @Override + public Result detailedIsMet(DependentResource dependentResource, P primary, + Context

context) { + if (condition instanceof DetailedCondition detailedCondition) { + return detailedCondition.detailedIsMet(dependentResource, primary, context); + } else { + return Result + .withoutResult(condition.isMet(dependentResource, primary, context)); + } + } +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/DefaultManagedWorkflow.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/DefaultManagedWorkflow.java index 27400230df..64f936c70d 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/DefaultManagedWorkflow.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/DefaultManagedWorkflow.java @@ -12,9 +12,9 @@ import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceSpec; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; import io.javaoperatorsdk.operator.api.reconciler.dependent.EventSourceReferencer; -import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.KubernetesClientAware; +import io.javaoperatorsdk.operator.api.reconciler.dependent.NameSetter; -import static io.javaoperatorsdk.operator.processing.dependent.workflow.Workflow.THROW_EXCEPTION_AUTOMATICALLY_DEFAULT; +import static io.javaoperatorsdk.operator.api.reconciler.Constants.NO_VALUE_SET; @SuppressWarnings("rawtypes") public class DefaultManagedWorkflow

implements ManagedWorkflow

{ @@ -31,7 +31,7 @@ protected DefaultManagedWorkflow(List orderedSpecs, boole .map(DependentResourceSpec::getName) .collect(Collectors.toSet()); this.orderedSpecs = orderedSpecs; - for (DependentResourceSpec spec : orderedSpecs) { + for (DependentResourceSpec spec : orderedSpecs) { // add cycle detection? if (spec.getDependsOn().isEmpty()) { topLevelResources.add(spec.getName()); @@ -77,13 +77,14 @@ public Workflow

resolve(KubernetesClient client, ControllerConfiguration

configuration) { final var alreadyResolved = new HashMap(orderedSpecs.size()); for (DependentResourceSpec spec : orderedSpecs) { - final var node = new DependentResourceNode(spec.getName(), + final var dependentResource = resolve(spec, client, configuration); + final var node = new DependentResourceNode( spec.getReconcileCondition(), spec.getDeletePostCondition(), spec.getReadyCondition(), spec.getActivationCondition(), - resolve(spec, client, configuration)); - alreadyResolved.put(node.getName(), node); + dependentResource); + alreadyResolved.put(dependentResource.name(), node); spec.getDependsOn() .forEach(depend -> node.addDependsOnRelation(alreadyResolved.get(depend))); } @@ -93,19 +94,21 @@ public Workflow

resolve(KubernetesClient client, final var top = topLevelResources.stream().map(alreadyResolved::get).collect(Collectors.toSet()); return new DefaultWorkflow<>(alreadyResolved, bottom, top, - THROW_EXCEPTION_AUTOMATICALLY_DEFAULT, hasCleaner); + configuration.getWorkflowSpec().map(w -> !w.handleExceptionsInReconciler()).orElseThrow(), + hasCleaner); } @SuppressWarnings({"rawtypes", "unchecked"}) - private DependentResource resolve(DependentResourceSpec spec, + private DependentResource resolve(DependentResourceSpec spec, KubernetesClient client, ControllerConfiguration

configuration) { final DependentResource dependentResource = configuration.getConfigurationService().dependentResourceFactory() .createFrom(spec, configuration); - if (dependentResource instanceof KubernetesClientAware) { - ((KubernetesClientAware) dependentResource).setKubernetesClient(client); + final var name = spec.getName(); + if (name != null && !NO_VALUE_SET.equals(name) && dependentResource instanceof NameSetter) { + ((NameSetter) dependentResource).setName(name); } spec.getUseEventSourceWithName() diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/DefaultResult.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/DefaultResult.java new file mode 100644 index 0000000000..cc63f637cf --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/DefaultResult.java @@ -0,0 +1,26 @@ +package io.javaoperatorsdk.operator.processing.dependent.workflow; + +public class DefaultResult implements DetailedCondition.Result { + private final T result; + private final boolean success; + + public DefaultResult(boolean success, T result) { + this.result = result; + this.success = success; + } + + @Override + public T getDetail() { + return result; + } + + @Override + public boolean isSuccess() { + return success; + } + + @Override + public String toString() { + return asString(); + } +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/DefaultWorkflow.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/DefaultWorkflow.java index 056b5906a0..3b928ad78a 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/DefaultWorkflow.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/DefaultWorkflow.java @@ -12,16 +12,18 @@ import io.javaoperatorsdk.operator.api.reconciler.dependent.Deleter; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; import io.javaoperatorsdk.operator.api.reconciler.dependent.GarbageCollected; -import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.DefaultManagedDependentResourceContext; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; +import static io.javaoperatorsdk.operator.api.reconciler.dependent.managed.DefaultManagedWorkflowAndDependentResourceContext.CLEANUP_RESULT_KEY; +import static io.javaoperatorsdk.operator.api.reconciler.dependent.managed.DefaultManagedWorkflowAndDependentResourceContext.RECONCILE_RESULT_KEY; + /** * Dependents definition: so if B depends on A, the B is dependent of A. * * @param

primary resource */ @SuppressWarnings("rawtypes") -public class DefaultWorkflow

implements Workflow

{ +class DefaultWorkflow

implements Workflow

{ private final Map dependentResourceNodes; private final Set topLevelResources; @@ -78,7 +80,7 @@ private Map toMap(Set node bottomLevelResource.remove(dependsOn); } } - map.put(node.getName(), node); + map.put(node.getDependentResource().name(), node); } if (topLevelResources.isEmpty()) { throw new IllegalStateException( @@ -92,8 +94,7 @@ public WorkflowReconcileResult reconcile(P primary, Context

context) { WorkflowReconcileExecutor

workflowReconcileExecutor = new WorkflowReconcileExecutor<>(this, primary, context); var result = workflowReconcileExecutor.reconcile(); - context.managedDependentResourceContext() - .put(DefaultManagedDependentResourceContext.RECONCILE_RESULT_KEY, result); + context.managedWorkflowAndDependentResourceContext().put(RECONCILE_RESULT_KEY, result); if (throwExceptionAutomatically) { result.throwAggregateExceptionIfErrorsPresent(); } @@ -105,21 +106,18 @@ public WorkflowCleanupResult cleanup(P primary, Context

context) { WorkflowCleanupExecutor

workflowCleanupExecutor = new WorkflowCleanupExecutor<>(this, primary, context); var result = workflowCleanupExecutor.cleanup(); - context.managedDependentResourceContext() - .put(DefaultManagedDependentResourceContext.CLEANUP_RESULT_KEY, result); + context.managedWorkflowAndDependentResourceContext().put(CLEANUP_RESULT_KEY, result); if (throwExceptionAutomatically) { result.throwAggregateExceptionIfErrorsPresent(); } return result; } - @Override public Set getTopLevelDependentResources() { return topLevelResources; } - @Override - public Set getBottomLevelResource() { + public Set getBottomLevelDependentResources() { return bottomLevelResource; } @@ -145,6 +143,11 @@ public boolean isEmpty() { return dependentResourceNodes.isEmpty(); } + @Override + public int size() { + return dependentResourceNodes.size(); + } + @Override public Map getDependentResourcesByName() { final var resources = new HashMap(dependentResourceNodes.size()); @@ -153,14 +156,10 @@ public Map getDependentResourcesByName() { return resources; } - public Map getDependentResourcesByNameWithoutActivationCondition() { - final var resources = new HashMap(dependentResourceNodes.size()); - dependentResourceNodes - .forEach((name, node) -> { - if (node.getActivationCondition().isEmpty()) { - resources.put(name, node.getDependentResource()); - } - }); - return resources; + public List getDependentResourcesWithoutActivationCondition() { + return dependentResourceNodes.values().stream() + .filter(n -> n.getActivationCondition().isEmpty()) + .map(DependentResourceNode::getDependentResource) + .toList(); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/DependentResourceNode.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/DependentResourceNode.java index 4c82ee19f3..aa8bb31c66 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/DependentResourceNode.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/DependentResourceNode.java @@ -8,33 +8,28 @@ import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; @SuppressWarnings("rawtypes") -public class DependentResourceNode { +class DependentResourceNode { private final List dependsOn = new LinkedList<>(); private final List parents = new LinkedList<>(); - private final String name; - private Condition reconcilePrecondition; - private Condition deletePostcondition; - private Condition readyPostcondition; - private Condition activationCondition; - private final DependentResource dependentResource; - DependentResourceNode(String name, DependentResource dependentResource) { - this(name, null, null, null, null, dependentResource); - } + private ConditionWithType reconcilePrecondition; + private ConditionWithType deletePostcondition; + private ConditionWithType readyPostcondition; + private ConditionWithType activationCondition; + private final DependentResource dependentResource; DependentResourceNode(DependentResource dependentResource) { - this(getNameFor(dependentResource), null, null, null, null, dependentResource); + this(null, null, null, null, dependentResource); } - public DependentResourceNode(String name, Condition reconcilePrecondition, + public DependentResourceNode(Condition reconcilePrecondition, Condition deletePostcondition, Condition readyPostcondition, Condition activationCondition, DependentResource dependentResource) { - this.name = name; - this.reconcilePrecondition = reconcilePrecondition; - this.deletePostcondition = deletePostcondition; - this.readyPostcondition = readyPostcondition; - this.activationCondition = activationCondition; + setReconcilePrecondition(reconcilePrecondition); + setDeletePostcondition(deletePostcondition); + setReadyPostcondition(readyPostcondition); + setActivationCondition(activationCondition); this.dependentResource = dependentResource; } @@ -55,42 +50,40 @@ public List getParents() { return parents; } - public String getName() { - return name; - } - - - public Optional> getReconcilePrecondition() { + public Optional> getReconcilePrecondition() { return Optional.ofNullable(reconcilePrecondition); } - - public Optional> getDeletePostcondition() { + public Optional> getDeletePostcondition() { return Optional.ofNullable(deletePostcondition); } - public Optional> getActivationCondition() { + public Optional> getActivationCondition() { return Optional.ofNullable(activationCondition); } - void setReconcilePrecondition(Condition reconcilePrecondition) { - this.reconcilePrecondition = reconcilePrecondition; + public Optional> getReadyPostcondition() { + return Optional.ofNullable(readyPostcondition); } - void setDeletePostcondition(Condition cleanupCondition) { - this.deletePostcondition = cleanupCondition; + void setReconcilePrecondition(Condition reconcilePrecondition) { + this.reconcilePrecondition = reconcilePrecondition == null ? null + : new ConditionWithType<>(reconcilePrecondition, Condition.Type.RECONCILE); } - void setActivationCondition(Condition activationCondition) { - this.activationCondition = activationCondition; + void setDeletePostcondition(Condition deletePostcondition) { + this.deletePostcondition = deletePostcondition == null ? null + : new ConditionWithType<>(deletePostcondition, Condition.Type.DELETE); } - public Optional> getReadyPostcondition() { - return Optional.ofNullable(readyPostcondition); + void setActivationCondition(Condition activationCondition) { + this.activationCondition = activationCondition == null ? null + : new ConditionWithType<>(activationCondition, Condition.Type.ACTIVATION); } void setReadyPostcondition(Condition readyPostcondition) { - this.readyPostcondition = readyPostcondition; + this.readyPostcondition = readyPostcondition == null ? null + : new ConditionWithType<>(readyPostcondition, Condition.Type.READY); } public DependentResource getDependentResource() { @@ -106,18 +99,12 @@ public boolean equals(Object o) { return false; } DependentResourceNode that = (DependentResourceNode) o; - return name.equals(that.name); + return this.getDependentResource().name().equals(that.getDependentResource().name()); } @Override public int hashCode() { - return name.hashCode(); - } - - @SuppressWarnings("rawtypes") - static String getNameFor(DependentResource dependentResource) { - return DependentResource.defaultNameFor(dependentResource.getClass()) + "#" - + dependentResource.hashCode(); + return this.getDependentResource().name().hashCode(); } @Override diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/DetailedCondition.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/DetailedCondition.java new file mode 100644 index 0000000000..200743cc0e --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/DetailedCondition.java @@ -0,0 +1,94 @@ +package io.javaoperatorsdk.operator.processing.dependent.workflow; + +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; + +/** + * A condition that can return extra information in addition of whether it is met or not. + * + * @param the resource type this condition applies to + * @param

the primary resource type associated with the dependent workflow this condition is + * part of + * @param the type of the extra information returned by the condition + */ +public interface DetailedCondition extends Condition { + + /** + * Checks whether a condition holds true for the specified {@link DependentResource}, returning + * additional information as needed. + * + * @param dependentResource the {@link DependentResource} for which we want to check the condition + * @param primary the primary resource being considered + * @param context the current reconciliation {@link Context} + * @return a {@link Result} instance containing the result of the evaluation of the condition as + * well as additional detail + * @see Condition#isMet(DependentResource, HasMetadata, Context) + */ + Result detailedIsMet(DependentResource dependentResource, P primary, Context

context); + + @Override + default boolean isMet(DependentResource dependentResource, P primary, Context

context) { + return detailedIsMet(dependentResource, primary, context).isSuccess(); + } + + /** + * Holds a more detailed {@link Condition} result. + * + * @param the type of the extra information provided in condition evaluation + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + interface Result { + /** + * A result expressing a condition has been met without extra information + */ + Result metWithoutResult = new DefaultResult(true, null); + + /** + * A result expressing a condition has not been met without extra information + */ + Result unmetWithoutResult = new DefaultResult(false, null); + + /** + * Creates a {@link Result} without extra information + * + * @param success whether or not the condition has been met + * @return a {@link Result} without extra information + */ + static Result withoutResult(boolean success) { + return success ? metWithoutResult : unmetWithoutResult; + } + + /** + * Creates a {@link Result} with the specified condition evaluation result and extra information + * + * @param success whether or not the condition has been met + * @param detail the extra information that the condition provided during its evaluation + * @return a {@link Result} with the specified condition evaluation result and extra information + * @param the type of the extra information provided by the condition + */ + static Result withResult(boolean success, T detail) { + return new DefaultResult<>(success, detail); + } + + default String asString() { + return "Detail: " + getDetail() + " met: " + isSuccess(); + } + + /** + * The extra information provided by the associated {@link DetailedCondition} during its + * evaluation + * + * @return extra information provided by the associated {@link DetailedCondition} during its + * evaluation or {@code null} if none was provided + */ + T getDetail(); + + /** + * Whether the associated condition held true + * + * @return {@code true} if the associated condition was met, {@code false} otherwise + */ + boolean isSuccess(); + } +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ManagedWorkflowFactory.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ManagedWorkflowFactory.java index eb01dcd3f4..ef839896f4 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ManagedWorkflowFactory.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ManagedWorkflowFactory.java @@ -1,20 +1,22 @@ package io.javaoperatorsdk.operator.processing.dependent.workflow; +import java.util.Optional; + import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.config.workflow.WorkflowSpec; public interface ManagedWorkflowFactory> { @SuppressWarnings({"rawtypes", "unchecked"}) ManagedWorkflowFactory DEFAULT = (configuration) -> { - final var dependentResourceSpecs = configuration.getDependentResources(); - if (dependentResourceSpecs == null || dependentResourceSpecs.isEmpty()) { + final Optional workflowSpec = configuration.getWorkflowSpec(); + if (workflowSpec.isEmpty()) { return (ManagedWorkflow) (client, configuration1) -> new DefaultWorkflow(null); } ManagedWorkflowSupport support = new ManagedWorkflowSupport(); - return support.createWorkflow(dependentResourceSpecs); + return support.createWorkflow(workflowSpec.orElseThrow()); }; @SuppressWarnings("rawtypes") ManagedWorkflow workflowFor(C configuration); } - diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ManagedWorkflowSupport.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ManagedWorkflowSupport.java index b5a6fd26b2..d6404aa392 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ManagedWorkflowSupport.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ManagedWorkflowSupport.java @@ -12,9 +12,10 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.OperatorException; import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceSpec; +import io.javaoperatorsdk.operator.api.config.workflow.WorkflowSpec; @SuppressWarnings({"rawtypes", "unchecked"}) -class ManagedWorkflowSupport { +public class ManagedWorkflowSupport { public void checkForNameDuplication(List dependentResourceSpecs) { if (dependentResourceSpecs == null) { @@ -38,10 +39,8 @@ public void checkForNameDuplication(List dependentResourc } } - - public

ManagedWorkflow

createWorkflow( - List dependentResourceSpecs) { - return createAsDefault(dependentResourceSpecs); + public

ManagedWorkflow

createWorkflow(WorkflowSpec workflowSpec) { + return createAsDefault(workflowSpec.getDependentResourceSpecs()); }

DefaultManagedWorkflow

createAsDefault( diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/NodeExecutor.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/NodeExecutor.java index 0067c55321..2006486dc1 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/NodeExecutor.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/NodeExecutor.java @@ -1,7 +1,6 @@ package io.javaoperatorsdk.operator.processing.dependent.workflow; import io.fabric8.kubernetes.api.model.HasMetadata; -import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; abstract class NodeExecutor implements Runnable { @@ -17,9 +16,7 @@ protected NodeExecutor(DependentResourceNode dependentResourceNode, @Override public void run() { try { - var dependentResource = dependentResourceNode.getDependentResource(); - - doRun(dependentResourceNode, dependentResource); + doRun(dependentResourceNode); } catch (RuntimeException e) { workflowExecutor.handleExceptionInExecutor(dependentResourceNode, e); @@ -28,6 +25,5 @@ public void run() { } } - protected abstract void doRun(DependentResourceNode dependentResourceNode, - DependentResource dependentResource); + protected abstract void doRun(DependentResourceNode dependentResourceNode); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/Workflow.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/Workflow.java index 839844256e..02f7d9c89f 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/Workflow.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/Workflow.java @@ -1,8 +1,8 @@ package io.javaoperatorsdk.operator.processing.dependent.workflow; import java.util.Collections; +import java.util.List; import java.util.Map; -import java.util.Set; import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.api.reconciler.Context; @@ -20,22 +20,16 @@ default WorkflowCleanupResult cleanup(P primary, Context

context) { throw new UnsupportedOperationException("Implement this"); } - @SuppressWarnings("rawtypes") - default Set getTopLevelDependentResources() { - return Collections.emptySet(); - } - - @SuppressWarnings("rawtypes") - default Set getBottomLevelResource() { - return Collections.emptySet(); - } - default boolean hasCleaner() { return false; } default boolean isEmpty() { - return true; + return size() == 0; + } + + default int size() { + return getDependentResourcesByName().size(); } @SuppressWarnings("rawtypes") @@ -44,7 +38,7 @@ default Map getDependentResourcesByName() { } @SuppressWarnings("rawtypes") - default Map getDependentResourcesByNameWithoutActivationCondition() { - return Collections.emptyMap(); + default List getDependentResourcesWithoutActivationCondition() { + return Collections.emptyList(); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowBuilder.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowBuilder.java index e416de0260..7493058723 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowBuilder.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowBuilder.java @@ -16,61 +16,30 @@ public class WorkflowBuilder

{ private final Map> dependentResourceNodes = new HashMap<>(); private boolean throwExceptionAutomatically = THROW_EXCEPTION_AUTOMATICALLY_DEFAULT; - private DependentResourceNode currentNode; private boolean isCleaner = false; - public WorkflowBuilder

addDependentResource(DependentResource dependentResource) { - return addDependentResource(dependentResource, null); - } - - public WorkflowBuilder

addDependentResource(DependentResource dependentResource, String name) { - currentNode = name == null ? new DependentResourceNode<>(dependentResource) - : new DependentResourceNode<>(name, dependentResource); - isCleaner = isCleaner || dependentResource.isDeletable(); - final var actualName = currentNode.getName(); - dependentResourceNodes.put(actualName, currentNode); - return this; - } - - public WorkflowBuilder

dependsOn(Set dependentResources) { - for (var dependentResource : dependentResources) { - var dependsOn = getNodeByDependentResource(dependentResource); - currentNode.addDependsOnRelation(dependsOn); - } - return this; - } - - public WorkflowBuilder

dependsOn(DependentResource... dependentResources) { - if (dependentResources != null) { - return dependsOn(new HashSet<>(Arrays.asList(dependentResources))); - } - return this; - } - - public WorkflowBuilder

withReconcilePrecondition(Condition reconcilePrecondition) { - currentNode.setReconcilePrecondition(reconcilePrecondition); - return this; - } - - public WorkflowBuilder

withReadyPostcondition(Condition readyPostcondition) { - currentNode.setReadyPostcondition(readyPostcondition); - return this; + public WorkflowNodeConfigurationBuilder addDependentResourceAndConfigure( + DependentResource dependentResource) { + final var currentNode = doAddDependentResource(dependentResource); + return new WorkflowNodeConfigurationBuilder(currentNode); } - public WorkflowBuilder

withDeletePostcondition(Condition deletePostcondition) { - currentNode.setDeletePostcondition(deletePostcondition); + public WorkflowBuilder

addDependentResource(DependentResource dependentResource) { + doAddDependentResource(dependentResource); return this; } - public WorkflowBuilder

withActivationCondition(Condition activationCondition) { - currentNode.setActivationCondition(activationCondition); - return this; + private DependentResourceNode doAddDependentResource(DependentResource dependentResource) { + final var currentNode = new DependentResourceNode<>(dependentResource); + isCleaner = isCleaner || dependentResource.isDeletable(); + final var actualName = dependentResource.name(); + dependentResourceNodes.put(actualName, currentNode); + return currentNode; } DependentResourceNode getNodeByDependentResource(DependentResource dependentResource) { // first check by name - final var node = - dependentResourceNodes.get(DependentResourceNode.getNameFor(dependentResource)); + final var node = dependentResourceNodes.get(dependentResource.name()); if (node != null) { return node; } else { @@ -87,7 +56,77 @@ public WorkflowBuilder

withThrowExceptionFurther(boolean throwExceptionFurthe } public Workflow

build() { + return buildAsDefaultWorkflow(); + } + + DefaultWorkflow

buildAsDefaultWorkflow() { return new DefaultWorkflow(new HashSet<>(dependentResourceNodes.values()), throwExceptionAutomatically, isCleaner); } + + public class WorkflowNodeConfigurationBuilder { + private final DependentResourceNode currentNode; + + private WorkflowNodeConfigurationBuilder(DependentResourceNode currentNode) { + this.currentNode = currentNode; + } + + public WorkflowBuilder

addDependentResource(DependentResource dependentResource) { + return WorkflowBuilder.this.addDependentResource(dependentResource); + } + + public WorkflowNodeConfigurationBuilder addDependentResourceAndConfigure( + DependentResource dependentResource) { + final var currentNode = WorkflowBuilder.this.doAddDependentResource(dependentResource); + return new WorkflowNodeConfigurationBuilder(currentNode); + } + + public Workflow

build() { + return WorkflowBuilder.this.build(); + } + + DefaultWorkflow

buildAsDefaultWorkflow() { + return WorkflowBuilder.this.buildAsDefaultWorkflow(); + } + + public WorkflowBuilder

withThrowExceptionFurther(boolean throwExceptionFurther) { + return WorkflowBuilder.this.withThrowExceptionFurther(throwExceptionFurther); + } + + public WorkflowNodeConfigurationBuilder dependsOn(Set dependentResources) { + for (var dependentResource : dependentResources) { + var dependsOn = getNodeByDependentResource(dependentResource); + currentNode.addDependsOnRelation(dependsOn); + } + return this; + } + + public WorkflowNodeConfigurationBuilder dependsOn(DependentResource... dependentResources) { + if (dependentResources != null) { + return dependsOn(new HashSet<>(Arrays.asList(dependentResources))); + } + return this; + } + + public WorkflowNodeConfigurationBuilder withReconcilePrecondition( + Condition reconcilePrecondition) { + currentNode.setReconcilePrecondition(reconcilePrecondition); + return this; + } + + public WorkflowNodeConfigurationBuilder withReadyPostcondition(Condition readyPostcondition) { + currentNode.setReadyPostcondition(readyPostcondition); + return this; + } + + public WorkflowNodeConfigurationBuilder withDeletePostcondition(Condition deletePostcondition) { + currentNode.setDeletePostcondition(deletePostcondition); + return this; + } + + public WorkflowNodeConfigurationBuilder withActivationCondition(Condition activationCondition) { + currentNode.setActivationCondition(activationCondition); + return this; + } + } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowCleanupExecutor.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowCleanupExecutor.java index dda4db6729..73633adb82 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowCleanupExecutor.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowCleanupExecutor.java @@ -1,9 +1,7 @@ package io.javaoperatorsdk.operator.processing.dependent.workflow; +import java.util.ArrayList; import java.util.List; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -11,24 +9,20 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.dependent.Deleter; -import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; @SuppressWarnings("rawtypes") -public class WorkflowCleanupExecutor

extends AbstractWorkflowExecutor

{ +class WorkflowCleanupExecutor

extends AbstractWorkflowExecutor

{ private static final Logger log = LoggerFactory.getLogger(WorkflowCleanupExecutor.class); private static final String CLEANUP = "cleanup"; - private final Set postDeleteConditionNotMet = - ConcurrentHashMap.newKeySet(); - private final Set deleteCalled = ConcurrentHashMap.newKeySet(); - - public WorkflowCleanupExecutor(Workflow

workflow, P primary, Context

context) { + WorkflowCleanupExecutor(DefaultWorkflow

workflow, P primary, Context

context) { super(workflow, primary, context); } public synchronized WorkflowCleanupResult cleanup() { - for (DependentResourceNode dependentResourceNode : workflow.getBottomLevelResource()) { + for (DependentResourceNode dependentResourceNode : workflow + .getBottomLevelDependentResources()) { handleCleanup(dependentResourceNode); } waitForScheduledExecutionsToRun(); @@ -42,13 +36,30 @@ protected Logger logger() { @SuppressWarnings({"rawtypes", "unchecked"}) private synchronized void handleCleanup(DependentResourceNode dependentResourceNode) { - log.debug("Submitting for cleanup: {} primaryID: {}", dependentResourceNode, primaryID); - - if (alreadyVisited(dependentResourceNode) - || isExecutingNow(dependentResourceNode) - || !allDependentsCleaned(dependentResourceNode) - || hasErroredDependent(dependentResourceNode)) { - log.debug("Skipping submit of: {} primaryID: {}", dependentResourceNode, primaryID); + log.debug("Considering for cleanup: {} primaryID: {}", dependentResourceNode, primaryID); + + final var alreadyVisited = alreadyVisited(dependentResourceNode); + final var executingNow = isExecutingNow(dependentResourceNode); + final var waitingOnDependents = !allDependentsCleaned(dependentResourceNode); + final var hasErroredDependent = hasErroredDependent(dependentResourceNode); + if (waitingOnDependents || alreadyVisited || executingNow || hasErroredDependent) { + if (log.isDebugEnabled()) { + final var causes = new ArrayList(); + if (alreadyVisited) { + causes.add("already visited"); + } + if (executingNow) { + causes.add("executing now"); + } + if (waitingOnDependents) { + causes.add("waiting on dependents"); + } + if (hasErroredDependent) { + causes.add("errored dependent"); + } + log.debug("Skipping: {} primaryID: {} causes: {}", dependentResourceNode, + primaryID, String.join(", ", causes)); + } return; } @@ -64,33 +75,27 @@ private CleanupExecutor(DependentResourceNode drn) { @Override @SuppressWarnings("unchecked") - protected void doRun(DependentResourceNode dependentResourceNode, - DependentResource dependentResource) { - var deletePostCondition = dependentResourceNode.getDeletePostcondition(); - - var active = - isConditionMet(dependentResourceNode.getActivationCondition(), dependentResource); + protected void doRun(DependentResourceNode dependentResourceNode) { + final var active = + isConditionMet(dependentResourceNode.getActivationCondition(), dependentResourceNode); registerOrDeregisterEventSourceBasedOnActivation(active, dependentResourceNode); - if (dependentResource.isDeletable() && active) { - ((Deleter

) dependentResource).delete(primary, context); - deleteCalled.add(dependentResourceNode); - } - - boolean deletePostConditionMet; + boolean deletePostConditionMet = true; if (active) { - deletePostConditionMet = isConditionMet(deletePostCondition, dependentResource); - } else { - deletePostConditionMet = true; + final var dependentResource = dependentResourceNode.getDependentResource(); + if (dependentResource.isDeletable()) { + ((Deleter

) dependentResource).delete(primary, context); + createOrGetResultFor(dependentResourceNode).markAsDeleted(); + } + + deletePostConditionMet = + isConditionMet(dependentResourceNode.getDeletePostcondition(), dependentResourceNode); } + + createOrGetResultFor(dependentResourceNode).markAsVisited(); + if (deletePostConditionMet) { - markAsVisited(dependentResourceNode); handleDependentCleaned(dependentResourceNode); - } else { - // updating alreadyVisited needs to be the last operation otherwise could lead to a race - // condition in handleCleanup condition checks - postDeleteConditionNotMet.add(dependentResourceNode); - markAsVisited(dependentResourceNode); } } } @@ -112,7 +117,7 @@ private boolean allDependentsCleaned(DependentResourceNode dependentResourceNode List parents = dependentResourceNode.getParents(); return parents.isEmpty() || parents.stream() - .allMatch(d -> alreadyVisited(d) && !postDeleteConditionNotMet.contains(d)); + .allMatch(d -> alreadyVisited(d) && !postDeleteConditionNotMet(d)); } @SuppressWarnings("unchecked") @@ -122,13 +127,6 @@ private boolean hasErroredDependent(DependentResourceNode dependentResourceNode) } private WorkflowCleanupResult createCleanupResult() { - final var erroredDependents = getErroredDependents(); - final var postConditionNotMet = postDeleteConditionNotMet.stream() - .map(DependentResourceNode::getDependentResource) - .collect(Collectors.toList()); - final var deleteCalled = this.deleteCalled.stream() - .map(DependentResourceNode::getDependentResource) - .collect(Collectors.toList()); - return new WorkflowCleanupResult(erroredDependents, postConditionNotMet, deleteCalled); + return new WorkflowCleanupResult(asDetails()); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowCleanupResult.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowCleanupResult.java index 860a553c39..b93741ef56 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowCleanupResult.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowCleanupResult.java @@ -7,26 +7,24 @@ @SuppressWarnings("rawtypes") public class WorkflowCleanupResult extends WorkflowResult { + private Boolean allPostConditionsMet; - private final List deleteCalledOnDependents; - private final List postConditionNotMetDependents; - - WorkflowCleanupResult(Map erroredDependents, - List postConditionNotMet, List deleteCalled) { - super(erroredDependents); - this.deleteCalledOnDependents = deleteCalled; - this.postConditionNotMetDependents = postConditionNotMet; + WorkflowCleanupResult(Map> results) { + super(results); } public List getDeleteCalledOnDependents() { - return deleteCalledOnDependents; + return listFilteredBy(Detail::deleted); } public List getPostConditionNotMetDependents() { - return postConditionNotMetDependents; + return listFilteredBy(detail -> !detail.isConditionWithTypeMet(Condition.Type.DELETE)); } public boolean allPostConditionsMet() { - return postConditionNotMetDependents.isEmpty(); + if (allPostConditionsMet == null) { + allPostConditionsMet = getPostConditionNotMetDependents().isEmpty(); + } + return allPostConditionsMet; } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowReconcileExecutor.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowReconcileExecutor.java index 2da0bd7525..962d01c8e5 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowReconcileExecutor.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowReconcileExecutor.java @@ -1,10 +1,8 @@ package io.javaoperatorsdk.operator.processing.dependent.workflow; +import java.util.ArrayList; import java.util.HashSet; -import java.util.Map; import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -12,28 +10,16 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.dependent.Deleter; -import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; import io.javaoperatorsdk.operator.api.reconciler.dependent.ReconcileResult; @SuppressWarnings({"rawtypes", "unchecked"}) -public class WorkflowReconcileExecutor

extends AbstractWorkflowExecutor

{ +class WorkflowReconcileExecutor

extends AbstractWorkflowExecutor

{ private static final Logger log = LoggerFactory.getLogger(WorkflowReconcileExecutor.class); private static final String RECONCILE = "reconcile"; private static final String DELETE = "delete"; - - private final Set notReady = ConcurrentHashMap.newKeySet(); - - private final Set markedForDelete = ConcurrentHashMap.newKeySet(); - private final Set deletePostConditionNotMet = - ConcurrentHashMap.newKeySet(); - // used to remember reconciled (not deleted or errored) dependents - private final Set reconciled = ConcurrentHashMap.newKeySet(); - private final Map reconcileResults = - new ConcurrentHashMap<>(); - - public WorkflowReconcileExecutor(Workflow

workflow, P primary, Context

context) { + public WorkflowReconcileExecutor(DefaultWorkflow

workflow, P primary, Context

context) { super(workflow, primary, context); } @@ -51,25 +37,46 @@ protected Logger logger() { } private synchronized void handleReconcile(DependentResourceNode dependentResourceNode) { - log.debug("Submitting for reconcile: {} primaryID: {}", dependentResourceNode, primaryID); - - if (alreadyVisited(dependentResourceNode) - || isExecutingNow(dependentResourceNode) - || !allParentsReconciledAndReady(dependentResourceNode) - || markedForDelete.contains(dependentResourceNode) - || hasErroredParent(dependentResourceNode)) { - log.debug("Skipping submit of: {}, primaryID: {}", dependentResourceNode, primaryID); + log.debug("Considering for reconcile: {} primaryID: {}", dependentResourceNode, primaryID); + + final var alreadyVisited = alreadyVisited(dependentResourceNode); + final var executingNow = isExecutingNow(dependentResourceNode); + final var isWaitingOnParents = !allParentsReconciledAndReady(dependentResourceNode); + final var isMarkedForDelete = isMarkedForDelete(dependentResourceNode); + final var hasErroredParent = hasErroredParent(dependentResourceNode); + if (isWaitingOnParents || alreadyVisited || executingNow || isMarkedForDelete + || hasErroredParent) { + if (log.isDebugEnabled()) { + final var causes = new ArrayList(); + if (alreadyVisited) { + causes.add("already visited"); + } + if (executingNow) { + causes.add("executing now"); + } + if (isMarkedForDelete) { + causes.add("marked for delete"); + } + if (isWaitingOnParents) { + causes.add("waiting on parents"); + } + if (hasErroredParent) { + causes.add("errored parent"); + } + log.debug("Skipping: {} primaryID: {} causes: {}", dependentResourceNode, + primaryID, String.join(", ", causes)); + } return; } boolean activationConditionMet = isConditionMet(dependentResourceNode.getActivationCondition(), - dependentResourceNode.getDependentResource()); + dependentResourceNode); registerOrDeregisterEventSourceBasedOnActivation(activationConditionMet, dependentResourceNode); boolean reconcileConditionMet = true; if (activationConditionMet) { reconcileConditionMet = isConditionMet(dependentResourceNode.getReconcilePrecondition(), - dependentResourceNode.getDependentResource()); + dependentResourceNode); } if (!reconcileConditionMet || !activationConditionMet) { handleReconcileOrActivationConditionNotMet(dependentResourceNode, activationConditionMet); @@ -81,12 +88,29 @@ private synchronized void handleReconcile(DependentResourceNode depend private synchronized void handleDelete(DependentResourceNode dependentResourceNode) { log.debug("Submitting for delete: {}", dependentResourceNode); - if (alreadyVisited(dependentResourceNode) - || isExecutingNow(dependentResourceNode) - || !markedForDelete.contains(dependentResourceNode) - || !allDependentsDeletedAlready(dependentResourceNode)) { - log.debug("Skipping submit for delete of: {} primaryID: {} ", dependentResourceNode, - primaryID); + final var alreadyVisited = alreadyVisited(dependentResourceNode); + final var executingNow = isExecutingNow(dependentResourceNode); + final var isNotMarkedForDelete = !isMarkedForDelete(dependentResourceNode); + final var isWaitingOnDependents = !allDependentsDeletedAlready(dependentResourceNode); + if (isNotMarkedForDelete || alreadyVisited || executingNow || isWaitingOnDependents) { + if (log.isDebugEnabled()) { + final var causes = new ArrayList(); + if (alreadyVisited) { + causes.add("already visited"); + } + if (executingNow) { + causes.add("executing now"); + } + if (isNotMarkedForDelete) { + causes.add("not marked for delete"); + } + if (isWaitingOnDependents) { + causes.add("waiting on dependents"); + } + log.debug("Skipping submit for delete of: {} primaryID: {} causes: {}", + dependentResourceNode, + primaryID, String.join(", ", causes)); + } return; } @@ -96,16 +120,8 @@ private synchronized void handleDelete(DependentResourceNode dependentResourceNo private boolean allDependentsDeletedAlready(DependentResourceNode dependentResourceNode) { var dependents = dependentResourceNode.getParents(); - return dependents.stream().allMatch(d -> alreadyVisited(d) && !notReady.contains(d) - && !isInError(d) && !deletePostConditionNotMet.contains(d)); - } - - // needs to be in one step - private synchronized void setAlreadyReconciledButNotReady( - DependentResourceNode dependentResourceNode) { - log.debug("Setting already reconciled but not ready for: {}", dependentResourceNode); - markAsVisited(dependentResourceNode); - notReady.add(dependentResourceNode); + return dependents.stream().allMatch(d -> alreadyVisited(d) && isReady(d) + && !isInError(d) && !postDeleteConditionNotMet(d)); } private class NodeReconcileExecutor extends NodeExecutor { @@ -115,24 +131,20 @@ private NodeReconcileExecutor(DependentResourceNode dependentResourceNode) } @Override - protected void doRun(DependentResourceNode dependentResourceNode, - DependentResource dependentResource) { - + protected void doRun(DependentResourceNode dependentResourceNode) { + final var dependentResource = dependentResourceNode.getDependentResource(); log.debug( "Reconciling for primary: {} node: {} ", primaryID, dependentResourceNode); ReconcileResult reconcileResult = dependentResource.reconcile(primary, context); - reconcileResults.put(dependentResource, reconcileResult); - reconciled.add(dependentResourceNode); + final var detailBuilder = createOrGetResultFor(dependentResourceNode); + detailBuilder.withReconcileResult(reconcileResult).markAsVisited(); - boolean ready = isConditionMet(dependentResourceNode.getReadyPostcondition(), - dependentResource); - if (ready) { + if (isConditionMet(dependentResourceNode.getReadyPostcondition(), dependentResourceNode)) { log.debug("Setting already reconciled for: {} primaryID: {}", dependentResourceNode, primaryID); - markAsVisited(dependentResourceNode); handleDependentsReconcile(dependentResourceNode); } else { - setAlreadyReconciledButNotReady(dependentResourceNode); + log.debug("Setting already reconciled but not ready for: {}", dependentResourceNode); } } } @@ -145,29 +157,23 @@ private NodeDeleteExecutor(DependentResourceNode dependentResourceNode) { @Override @SuppressWarnings("unchecked") - protected void doRun(DependentResourceNode dependentResourceNode, - DependentResource dependentResource) { - var deletePostCondition = dependentResourceNode.getDeletePostcondition(); - + protected void doRun(DependentResourceNode dependentResourceNode) { boolean deletePostConditionMet = true; - if (isConditionMet(dependentResourceNode.getActivationCondition(), dependentResource)) { + if (isConditionMet(dependentResourceNode.getActivationCondition(), dependentResourceNode)) { // GarbageCollected status is irrelevant here, as this method is only called when a // precondition does not hold, // a deleter should be deleted even if it is otherwise garbage collected + final var dependentResource = dependentResourceNode.getDependentResource(); if (dependentResource instanceof Deleter) { ((Deleter

) dependentResource).delete(primary, context); } - deletePostConditionMet = isConditionMet(deletePostCondition, dependentResource); + deletePostConditionMet = + isConditionMet(dependentResourceNode.getDeletePostcondition(), dependentResourceNode); } + createOrGetResultFor(dependentResourceNode).markAsVisited(); if (deletePostConditionMet) { - markAsVisited(dependentResourceNode); handleDependentDeleted(dependentResourceNode); - } else { - // updating alreadyVisited needs to be the last operation otherwise could lead to a race - // condition in handleDelete condition checks - deletePostConditionNotMet.add(dependentResourceNode); - markAsVisited(dependentResourceNode); } } } @@ -191,7 +197,6 @@ private synchronized void handleDependentsReconcile( }); } - private void handleReconcileOrActivationConditionNotMet( DependentResourceNode dependentResourceNode, boolean activationConditionMet) { @@ -206,7 +211,7 @@ private void markDependentsForDelete(DependentResourceNode dependentResour // so if the activation condition was false, this node is not meant to be deleted. var dependents = dependentResourceNode.getParents(); if (activationConditionMet) { - markedForDelete.add(dependentResourceNode); + createOrGetResultFor(dependentResourceNode).markForDelete(); if (dependents.isEmpty()) { bottomNodes.add(dependentResourceNode); } else { @@ -214,7 +219,7 @@ private void markDependentsForDelete(DependentResourceNode dependentResour } } else { // this is for an edge case when there is only one resource but that is not active - markAsVisited(dependentResourceNode); + createOrGetResultFor(dependentResourceNode).markAsVisited(); if (dependents.isEmpty()) { handleNodeExecutionFinish(dependentResourceNode); } else { @@ -226,7 +231,7 @@ private void markDependentsForDelete(DependentResourceNode dependentResour private boolean allParentsReconciledAndReady(DependentResourceNode dependentResourceNode) { return dependentResourceNode.getDependsOn().isEmpty() || dependentResourceNode.getDependsOn().stream() - .allMatch(d -> alreadyVisited(d) && !notReady.contains(d)); + .allMatch(d -> alreadyVisited(d) && isReady(d)); } private boolean hasErroredParent(DependentResourceNode dependentResourceNode) { @@ -236,15 +241,6 @@ private boolean hasErroredParent(DependentResourceNode dependentResourceNo } private WorkflowReconcileResult createReconcileResult() { - return new WorkflowReconcileResult( - reconciled.stream() - .map(DependentResourceNode::getDependentResource) - .collect(Collectors.toList()), - notReady.stream() - .map(DependentResourceNode::getDependentResource) - .collect(Collectors.toList()), - getErroredDependents(), - reconcileResults); + return new WorkflowReconcileResult(asDetails()); } - } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowReconcileResult.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowReconcileResult.java index 6fbd06486c..055fca3bfe 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowReconcileResult.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowReconcileResult.java @@ -2,41 +2,31 @@ import java.util.List; import java.util.Map; +import java.util.Optional; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; -import io.javaoperatorsdk.operator.api.reconciler.dependent.ReconcileResult; @SuppressWarnings("rawtypes") public class WorkflowReconcileResult extends WorkflowResult { - private final List reconciledDependents; - private final List notReadyDependents; - private final Map reconcileResults; - - public WorkflowReconcileResult(List reconciledDependents, - List notReadyDependents, - Map erroredDependents, - Map reconcileResults) { - super(erroredDependents); - this.reconciledDependents = reconciledDependents; - this.notReadyDependents = notReadyDependents; - this.reconcileResults = reconcileResults; + WorkflowReconcileResult(Map> results) { + super(results); } public List getReconciledDependents() { - return reconciledDependents; + return listFilteredBy(detail -> detail.reconcileResult() != null); } public List getNotReadyDependents() { - return notReadyDependents; + return listFilteredBy(detail -> !detail.isConditionWithTypeMet(Condition.Type.READY)); } - @SuppressWarnings("unused") - public Map getReconcileResults() { - return reconcileResults; + public Optional getNotReadyDependentResult(DependentResource dependentResource, + Class expectedResultType) { + return getDependentConditionResult(dependentResource, Condition.Type.READY, expectedResultType); } public boolean allDependentResourcesReady() { - return notReadyDependents.isEmpty(); + return getNotReadyDependents().isEmpty(); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowResult.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowResult.java index 77fc2dcbfe..1b278fed77 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowResult.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowResult.java @@ -1,58 +1,227 @@ package io.javaoperatorsdk.operator.processing.dependent.workflow; -import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Optional; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; import io.javaoperatorsdk.operator.AggregatedOperatorException; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; +import io.javaoperatorsdk.operator.api.reconciler.dependent.ReconcileResult; @SuppressWarnings("rawtypes") class WorkflowResult { + private final Map> results; + private Boolean hasErroredDependents; - private static final String NUMBER_DELIMITER = "_"; - private final Map erroredDependents; - - WorkflowResult(Map erroredDependents) { - this.erroredDependents = erroredDependents; + WorkflowResult(Map> results) { + this.results = results; } public Map getErroredDependents() { - return erroredDependents; + return getErroredDependentsStream() + .collect(Collectors.toMap(Entry::getKey, entry -> entry.getValue().error)); + } + + private Stream>> getErroredDependentsStream() { + return results.entrySet().stream().filter(entry -> entry.getValue().error != null); + } + + protected Map> results() { + return results; + } + + /** + * Retrieves the {@link DependentResource} associated with the specified name if it exists, + * {@link Optional#empty()} otherwise. + * + * @param name the name of the {@link DependentResource} to retrieve + * @return the {@link DependentResource} associated with the specified name if it exists, + * {@link Optional#empty()} otherwise + */ + public Optional getDependentResourceByName(String name) { + if (name == null || name.isEmpty()) { + return Optional.empty(); + } + return results.keySet().stream().filter(dr -> dr.name().equals(name)).findFirst(); } /** - * @deprecated Use {@link #erroredDependentsExist()} instead - * @return if any dependents are in error state + * Retrieves the optional result of the condition with the specified type for the specified + * dependent resource. + * + * @param the expected result type of the condition + * @param dependentResourceName the dependent resource for which we want to retrieve a condition + * result + * @param conditionType the condition type which result we're interested in + * @param expectedResultType the expected result type of the condition + * @return the dependent condition result if it exists or {@link Optional#empty()} otherwise + * @throws IllegalArgumentException if a result exists but is not of the expected type */ - @Deprecated(forRemoval = true) - public boolean erroredDependentsExists() { - return !erroredDependents.isEmpty(); + public Optional getDependentConditionResult(String dependentResourceName, + Condition.Type conditionType, Class expectedResultType) { + return getDependentConditionResult( + getDependentResourceByName(dependentResourceName).orElse(null), conditionType, + expectedResultType); + } + + /** + * Retrieves the optional result of the condition with the specified type for the specified + * dependent resource. + * + * @param the expected result type of the condition + * @param dependentResource the dependent resource for which we want to retrieve a condition + * result + * @param conditionType the condition type which result we're interested in + * @param expectedResultType the expected result type of the condition + * @return the dependent condition result if it exists or {@link Optional#empty()} otherwise + * @throws IllegalArgumentException if a result exists but is not of the expected type + */ + public Optional getDependentConditionResult(DependentResource dependentResource, + Condition.Type conditionType, Class expectedResultType) { + if (dependentResource == null) { + return Optional.empty(); + } + + final var result = new Object[1]; + try { + return Optional.ofNullable(results().get(dependentResource)) + .flatMap(detail -> detail.getResultForConditionWithType(conditionType)) + .map(r -> result[0] = r.getDetail()) + .map(expectedResultType::cast); + } catch (Exception e) { + throw new IllegalArgumentException("Condition " + + "result " + result[0] + + " for Dependent " + dependentResource.name() + " doesn't match expected type " + + expectedResultType.getSimpleName(), e); + } + } + + protected List listFilteredBy( + Function filter) { + return results.entrySet().stream() + .filter(e -> filter.apply(e.getValue())) + .map(Map.Entry::getKey) + .toList(); } - @SuppressWarnings("unused") public boolean erroredDependentsExist() { - return !erroredDependents.isEmpty(); + if (hasErroredDependents == null) { + hasErroredDependents = !getErroredDependents().isEmpty(); + } + return hasErroredDependents; } public void throwAggregateExceptionIfErrorsPresent() { if (erroredDependentsExist()) { - Map exceptionMap = new HashMap<>(); - Map numberOfClasses = new HashMap<>(); - - for (Entry entry : erroredDependents.entrySet()) { - String name = entry.getKey().getClass().getName(); - var num = numberOfClasses.getOrDefault(name, 0); - if (num > 0) { - exceptionMap.put(name + NUMBER_DELIMITER + num, entry.getValue()); - } else { - exceptionMap.put(name, entry.getValue()); - } - numberOfClasses.put(name, num + 1); + throw new AggregatedOperatorException("Exception(s) during workflow execution.", + getErroredDependentsStream() + .collect(Collectors.toMap(e -> e.getKey().name(), e -> e.getValue().error))); + } + } + + @SuppressWarnings("UnusedReturnValue") + static class DetailBuilder { + private Exception error; + private ReconcileResult reconcileResult; + private DetailedCondition.Result activationConditionResult; + private DetailedCondition.Result deletePostconditionResult; + private DetailedCondition.Result readyPostconditionResult; + private DetailedCondition.Result reconcilePostconditionResult; + private boolean deleted; + private boolean visited; + private boolean markedForDelete; + + Detail build() { + return new Detail<>(error, reconcileResult, activationConditionResult, + deletePostconditionResult, readyPostconditionResult, reconcilePostconditionResult, + deleted, visited, markedForDelete); + } + + DetailBuilder withResultForCondition( + ConditionWithType conditionWithType, + DetailedCondition.Result conditionResult) { + switch (conditionWithType.type()) { + case ACTIVATION -> activationConditionResult = conditionResult; + case DELETE -> deletePostconditionResult = conditionResult; + case READY -> readyPostconditionResult = conditionResult; + case RECONCILE -> reconcilePostconditionResult = conditionResult; + default -> + throw new IllegalStateException("Unexpected condition type: " + conditionWithType); } + return this; + } - throw new AggregatedOperatorException("Exception(s) during workflow execution.", - exceptionMap); + DetailBuilder withError(Exception error) { + this.error = error; + return this; + } + + DetailBuilder withReconcileResult(ReconcileResult reconcileResult) { + this.reconcileResult = reconcileResult; + return this; + } + + DetailBuilder markAsDeleted() { + this.deleted = true; + return this; + } + + public boolean hasError() { + return error != null; + } + + public boolean hasPostDeleteConditionNotMet() { + return deletePostconditionResult != null && !deletePostconditionResult.isSuccess(); + } + + public boolean isReady() { + return readyPostconditionResult == null || readyPostconditionResult.isSuccess(); + } + + DetailBuilder markAsVisited() { + visited = true; + return this; + } + + public boolean isVisited() { + return visited; + } + + public boolean isMarkedForDelete() { + return markedForDelete; + } + + DetailBuilder markForDelete() { + markedForDelete = true; + return this; + } + } + + + record Detail(Exception error, ReconcileResult reconcileResult, + DetailedCondition.Result activationConditionResult, + DetailedCondition.Result deletePostconditionResult, + DetailedCondition.Result readyPostconditionResult, + DetailedCondition.Result reconcilePostconditionResult, + boolean deleted, boolean visited, boolean markedForDelete) { + + boolean isConditionWithTypeMet(Condition.Type conditionType) { + return getResultForConditionWithType(conditionType).map(DetailedCondition.Result::isSuccess) + .orElse(true); + } + + Optional> getResultForConditionWithType( + Condition.Type conditionType) { + return switch (conditionType) { + case ACTIVATION -> Optional.ofNullable(activationConditionResult); + case DELETE -> Optional.ofNullable(deletePostconditionResult); + case READY -> Optional.ofNullable(readyPostconditionResult); + case RECONCILE -> Optional.ofNullable(reconcilePostconditionResult); + }; } } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventProcessor.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventProcessor.java index 2809efde8a..e05ea4830f 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventProcessor.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventProcessor.java @@ -52,7 +52,7 @@ public EventProcessor(EventSourceManager

eventSourceManager, this( eventSourceManager.getController().getConfiguration(), new ReconciliationDispatcher<>(eventSourceManager.getController()), eventSourceManager, - configurationService.getMetrics(), eventSourceManager.getControllerResourceEventSource()); + configurationService.getMetrics(), eventSourceManager.getControllerEventSource()); } @SuppressWarnings("rawtypes") @@ -64,7 +64,7 @@ public EventProcessor(EventSourceManager

eventSourceManager, this( controllerConfiguration, reconciliationDispatcher, eventSourceManager, metrics, - eventSourceManager.getControllerResourceEventSource()); + eventSourceManager.getControllerEventSource()); } @SuppressWarnings({"rawtypes", "unchecked"}) @@ -166,8 +166,7 @@ private void submitReconciliationExecution(ResourceState state) { private void handleEventMarking(Event event, ResourceState state) { final var relatedCustomResourceID = event.getRelatedCustomResourceID(); - if (event instanceof ResourceEvent) { - var resourceEvent = (ResourceEvent) event; + if (event instanceof ResourceEvent resourceEvent) { if (resourceEvent.getAction() == ResourceAction.DELETED) { log.debug("Marking delete event received for: {}", relatedCustomResourceID); state.markDeleteEventReceived(); @@ -245,17 +244,6 @@ synchronized void eventProcessingFinished( state.markProcessedMarkForDeletion(); metrics.cleanupDoneFor(resourceID, metricsMetadata); } else { - postExecutionControl - .getUpdatedCustomResource() - .ifPresent( - p -> { - if (!postExecutionControl.updateIsStatusPatch()) { - eventSourceManager - .getControllerResourceEventSource() - .handleRecentResourceUpdate( - ResourceID.fromResource(p), p, executionScope.getResource()); - } - }); if (state.eventPresent()) { submitReconciliationExecution(state); } else { @@ -342,8 +330,8 @@ private void handleRetryOnException( private void retryAwareErrorLogging(RetryExecution retry, boolean eventPresent, Exception exception, ExecutionScope

executionScope) { - if (!eventPresent && !retry.isLastAttempt() && exception instanceof KubernetesClientException) { - KubernetesClientException ex = (KubernetesClientException) exception; + if (!eventPresent && !retry.isLastAttempt() + && exception instanceof KubernetesClientException ex) { if (ex.getCode() == HttpURLConnection.HTTP_CONFLICT) { log.debug("Full client conflict error during event processing {}", executionScope, exception); @@ -409,6 +397,10 @@ public synchronized void start() throws OperatorException { handleAlreadyMarkedEvents(); } + public boolean isNextReconciliationImminent(ResourceID resourceID) { + return resourceStateManager.getOrCreate(resourceID).eventPresent(); + } + private void handleAlreadyMarkedEvents() { for (var state : resourceStateManager.resourcesWithEventPresent()) { log.debug("Handling already marked event on start. State: {}", state); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSourceManager.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSourceManager.java index bd299b464a..174ffa0978 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSourceManager.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSourceManager.java @@ -1,6 +1,10 @@ package io.javaoperatorsdk.operator.processing.event; -import java.util.*; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -14,14 +18,12 @@ import io.javaoperatorsdk.operator.api.config.ExecutorServiceManager; import io.javaoperatorsdk.operator.api.config.NamespaceChangeable; import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; -import io.javaoperatorsdk.operator.api.reconciler.EventSourceInitializer; import io.javaoperatorsdk.operator.processing.Controller; import io.javaoperatorsdk.operator.processing.LifecycleAware; import io.javaoperatorsdk.operator.processing.event.source.EventSource; import io.javaoperatorsdk.operator.processing.event.source.EventSourceStartPriority; import io.javaoperatorsdk.operator.processing.event.source.ResourceEventAware; -import io.javaoperatorsdk.operator.processing.event.source.ResourceEventSource; -import io.javaoperatorsdk.operator.processing.event.source.controller.ControllerResourceEventSource; +import io.javaoperatorsdk.operator.processing.event.source.controller.ControllerEventSource; import io.javaoperatorsdk.operator.processing.event.source.controller.ResourceAction; import io.javaoperatorsdk.operator.processing.event.source.informer.ManagedInformerEventSource; import io.javaoperatorsdk.operator.processing.event.source.timer.TimerEventSource; @@ -49,7 +51,7 @@ public EventSourceManager(Controller

controller) { } public void postProcessDefaultEventSourcesAfterProcessorInitializer() { - eventSources.controllerResourceEventSource().setEventHandler(controller.getEventProcessor()); + eventSources.controllerEventSource().setEventHandler(controller.getEventProcessor()); eventSources.retryEventSource().setEventHandler(controller.getEventProcessor()); } @@ -61,31 +63,28 @@ public void postProcessDefaultEventSourcesAfterProcessorInitializer() { * {@link io.javaoperatorsdk.operator.processing.event.source.polling.PerResourcePollingEventSource}). *

* Now the event sources are also started sequentially, mainly because others might depend on - * {@link ControllerResourceEventSource} , which is started first. + * {@link ControllerEventSource} , which is started first. */ @Override public synchronized void start() { - startEventSource(eventSources.namedControllerResourceEventSource()); + startEventSource(eventSources.controllerEventSource()); executorServiceManager.boundedExecuteAndWaitForAllToComplete( - eventSources.additionalNamedEventSources() + eventSources.additionalEventSources() .filter(es -> es.priority().equals(EventSourceStartPriority.RESOURCE_STATE_LOADER)), this::startEventSource, getThreadNamer("start")); executorServiceManager.boundedExecuteAndWaitForAllToComplete( - eventSources.additionalNamedEventSources() + eventSources.additionalEventSources() .filter(es -> es.priority().equals(EventSourceStartPriority.DEFAULT)), this::startEventSource, getThreadNamer("start")); } - private static Function getThreadNamer(String stage) { - return es -> { - final var name = es.name(); - return es.priority() + " " + stage + " -> " - + (es.isNameSet() ? name + " " + es.original().getClass() : es.original()); - }; + @SuppressWarnings("rawtypes") + private static Function getThreadNamer(String stage) { + return es -> es.priority() + " " + stage + " -> " + es.name(); } private static Function getEventSourceThreadNamer(String stage) { @@ -94,29 +93,22 @@ private static Function getEventSourceThreadNamer(S @Override public synchronized void stop() { - stopEventSource(eventSources.namedControllerResourceEventSource()); + stopEventSource(eventSources.controllerEventSource()); executorServiceManager.boundedExecuteAndWaitForAllToComplete( - eventSources.additionalNamedEventSources(), + eventSources.additionalEventSources(), this::stopEventSource, getThreadNamer("stop")); } @SuppressWarnings("rawtypes") - private void logEventSourceEvent(NamedEventSource eventSource, String event) { + private void logEventSourceEvent(EventSource eventSource, String event) { if (log.isDebugEnabled()) { - if (eventSource.original() instanceof ResourceEventSource) { - ResourceEventSource source = (ResourceEventSource) eventSource.original(); - log.debug("{} event source {} for {}", event, - eventSource.isNameSet() ? eventSource.name() : eventSource, - source.resourceType()); - } else { - log.debug("{} event source {}", event, - eventSource.isNameSet() ? eventSource.name() : eventSource); - } + log.debug("{} event source {} for {}", event, eventSource.name(), + eventSource.resourceType()); } } - private Void startEventSource(NamedEventSource eventSource) { + private Void startEventSource(EventSource eventSource) { try { logEventSourceEvent(eventSource, "Starting"); eventSource.start(); @@ -129,7 +121,7 @@ private Void startEventSource(NamedEventSource eventSource) { return null; } - private Void stopEventSource(NamedEventSource eventSource) { + private Void stopEventSource(EventSource eventSource) { try { logEventSourceEvent(eventSource, "Stopping"); eventSource.stop(); @@ -140,38 +132,28 @@ private Void stopEventSource(NamedEventSource eventSource) { return null; } - public final void registerEventSource(EventSource eventSource) throws OperatorException { - registerEventSource(null, eventSource); - } - @SuppressWarnings("rawtypes") - public final synchronized void registerEventSource(String name, EventSource eventSource) + public final synchronized void registerEventSource(EventSource eventSource) throws OperatorException { Objects.requireNonNull(eventSource, "EventSource must not be null"); try { - if (name == null || name.isBlank()) { - name = EventSourceInitializer.generateNameFor(eventSource); - } - if (eventSource instanceof ManagedInformerEventSource) { - var managedInformerEventSource = ((ManagedInformerEventSource) eventSource); - managedInformerEventSource.setConfigurationService( - controller.getConfiguration().getConfigurationService()); + if (eventSource instanceof ManagedInformerEventSource managedInformerEventSource) { + managedInformerEventSource.setControllerConfiguration( + controller.getConfiguration()); } - final var named = new NamedEventSource(eventSource, name); - eventSources.add(named); - named.setEventHandler(controller.getEventProcessor()); + eventSources.add(eventSource); + eventSource.setEventHandler(controller.getEventProcessor()); } catch (IllegalStateException | MissingCRDException e) { throw e; // leave untouched } catch (Exception e) { - throw new OperatorException("Couldn't register event source: " + name + " for " + throw new OperatorException("Couldn't register event source: " + eventSource.name() + " for " + controller.getConfiguration().getName() + " controller", e); } } @SuppressWarnings("unchecked") public void broadcastOnResourceEvent(ResourceAction action, P resource, P oldResource) { - eventSources.additionalNamedEventSources() - .map(NamedEventSource::original) + eventSources.additionalEventSources() .forEach(source -> { if (source instanceof ResourceEventAware) { var lifecycleAwareES = ((ResourceEventAware

) source); @@ -191,52 +173,51 @@ public void broadcastOnResourceEvent(ResourceAction action, P resource, P oldRes } public void changeNamespaces(Set namespaces) { - eventSources.controllerResourceEventSource() - .changeNamespaces(namespaces); - executorServiceManager.boundedExecuteAndWaitForAllToComplete(eventSources + eventSources.controllerEventSource().changeNamespaces(namespaces); + final var namespaceChangeables = eventSources .additionalEventSources() .filter(NamespaceChangeable.class::isInstance) .map(NamespaceChangeable.class::cast) - .filter(NamespaceChangeable::allowsNamespaceChanges), e -> { - e.changeNamespaces(namespaces); - return null; - }, + .filter(NamespaceChangeable::allowsNamespaceChanges); + executorServiceManager.boundedExecuteAndWaitForAllToComplete(namespaceChangeables, e -> { + e.changeNamespaces(namespaces); + return null; + }, getEventSourceThreadNamer("changeNamespace")); } - public Set getRegisteredEventSources() { + public Set> getRegisteredEventSources() { return eventSources.flatMappedSources() - .map(NamedEventSource::original) .collect(Collectors.toCollection(LinkedHashSet::new)); } - public Map allEventSources() { - return eventSources.allNamedEventSources().collect(Collectors.toMap(NamedEventSource::name, - NamedEventSource::original)); + @SuppressWarnings("rawtypes") + public List allEventSources() { + return eventSources.allEventSources().toList(); } + @SuppressWarnings("unused") - public Stream getNamedEventSourcesStream() { + public Stream> getEventSourcesStream() { return eventSources.flatMappedSources(); } - public ControllerResourceEventSource

getControllerResourceEventSource() { - return eventSources.controllerResourceEventSource(); + public ControllerEventSource

getControllerEventSource() { + return eventSources.controllerEventSource(); } - public List> getResourceEventSourcesFor(Class dependentType) { + public List> getEventSourcesFor(Class dependentType) { return eventSources.getEventSources(dependentType); } @Override - public EventSource dynamicallyRegisterEventSource(String name, - EventSource eventSource) { + public EventSource dynamicallyRegisterEventSource(EventSource eventSource) { synchronized (this) { - var actual = eventSources.existing(name, eventSource); + var actual = eventSources.existingEventSourceByName(eventSource.name()); if (actual != null) { - eventSource = actual.eventSource(); + eventSource = actual; } else { - registerEventSource(name, eventSource); + registerEventSource(eventSource); } } // The start itself is blocking thus blocking only the threads which are attempt to start the @@ -246,8 +227,10 @@ public EventSource dynamicallyRegisterEventSource(String name, } @Override - public synchronized Optional dynamicallyDeRegisterEventSource(String name) { - EventSource es = eventSources.remove(name); + public synchronized Optional> dynamicallyDeRegisterEventSource( + String name) { + @SuppressWarnings("unchecked") + EventSource es = eventSources.remove(name); if (es != null) { es.stop(); } @@ -259,23 +242,11 @@ public EventSourceContext

eventSourceContextForDynamicRegistration() { return controller.eventSourceContext(); } - /** - * @deprecated Use {@link #getResourceEventSourceFor(Class)} instead - * - * @param target resource type - * @param dependentType target resource class - * @return list of related event sources - */ - @Deprecated - public List> getEventSourcesFor(Class dependentType) { - return getResourceEventSourcesFor(dependentType); - } - @Override - public ResourceEventSource getResourceEventSourceFor( - Class dependentType, String qualifier) { + public EventSource getEventSourceFor( + Class dependentType, String name) { Objects.requireNonNull(dependentType, "dependentType is Mandatory"); - return eventSources.get(dependentType, qualifier); + return eventSources.get(dependentType, name); } TimerEventSource

retryEventSource() { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSourceMetadata.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSourceMetadata.java deleted file mode 100644 index 2fd913d481..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSourceMetadata.java +++ /dev/null @@ -1,13 +0,0 @@ -package io.javaoperatorsdk.operator.processing.event; - -import java.util.Optional; - -public interface EventSourceMetadata { - String name(); - - Class type(); - - Optional> resourceType(); - - Optional configuration(); -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSourceRetriever.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSourceRetriever.java index 7ed2777998..16b03303a4 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSourceRetriever.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSourceRetriever.java @@ -6,23 +6,23 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; import io.javaoperatorsdk.operator.processing.event.source.EventSource; -import io.javaoperatorsdk.operator.processing.event.source.ResourceEventSource; public interface EventSourceRetriever

{ - default ResourceEventSource getResourceEventSourceFor(Class dependentType) { - return getResourceEventSourceFor(dependentType, null); + default EventSource getEventSourceFor(Class dependentType) { + return getEventSourceFor(dependentType, null); } - ResourceEventSource getResourceEventSourceFor(Class dependentType, String name); + EventSource getEventSourceFor(Class dependentType, String name); - List> getResourceEventSourcesFor(Class dependentType); + List> getEventSourcesFor(Class dependentType); /** + *

* Registers (and starts) the specified {@link EventSource} dynamically during the reconciliation. * If an EventSource is already registered with the specified name, the registration will be - * ignored. It is the user's responsibility to handle the naming correctly, thus to not try to - * register different event source with same name that is already registered. + * ignored. It is the user's responsibility to handle the naming correctly. + *

*

* This is only needed when your operator needs to adapt dynamically based on optional resources * that may or may not be present on the target cluster. Even in this situation, it should be @@ -31,20 +31,25 @@ default ResourceEventSource getResourceEventSourceFor(Class depende * activation conditions of dependents, for example. *

*

- * This method will block until the event source is synced, if needed (as is the case for + * This method will block until the event source is synced (if needed, as it is the case for * {@link io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource}). *

*

- * Should multiple reconciliations happen concurrently, only one EventSource with the specified - * name will ever be registered. + * IMPORTANT: Should multiple reconciliations happen concurrently, only one + * EventSource with the specified name will ever be registered. It is therefore important to + * explicitly name the event sources that you want to reuse because the name will be used to + * identify which event sources need to be created or not. If you let JOSDK implicitly name event + * sources, then you might end up with duplicated event sources because concurrent registration of + * event sources will lead to 2 (or more) event sources for the same resource type to be attempted + * to be registered under different, automatically generated names. If you clearly identify your + * event sources with names, then, if the concurrent process determines that an event source with + * the specified name, it won't register it again. *

* - * @param name of the event source * @param eventSource to register * @return the actual event source registered. Might not be the same as the parameter. */ - EventSource dynamicallyRegisterEventSource(String name, EventSource eventSource); - + EventSource dynamicallyRegisterEventSource(EventSource eventSource); /** * De-registers (and stops) the {@link EventSource} associated with the specified name. If no such @@ -62,7 +67,7 @@ default ResourceEventSource getResourceEventSourceFor(Class depende * @param name of the event source * @return the actual event source deregistered if there is one. */ - Optional dynamicallyDeRegisterEventSource(String name); + Optional> dynamicallyDeRegisterEventSource(String name); EventSourceContext

eventSourceContextForDynamicRegistration(); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSources.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSources.java index f827b04a6d..c21509f41c 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSources.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSources.java @@ -1,115 +1,93 @@ package io.javaoperatorsdk.operator.processing.event; + import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentNavigableMap; import java.util.concurrent.ConcurrentSkipListMap; -import java.util.stream.Collectors; import java.util.stream.Stream; import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.processing.Controller; import io.javaoperatorsdk.operator.processing.event.source.EventSource; -import io.javaoperatorsdk.operator.processing.event.source.ResourceEventSource; -import io.javaoperatorsdk.operator.processing.event.source.controller.ControllerResourceEventSource; +import io.javaoperatorsdk.operator.processing.event.source.controller.ControllerEventSource; import io.javaoperatorsdk.operator.processing.event.source.timer.TimerEventSource; -class EventSources { - - public static final String CONTROLLER_RESOURCE_EVENT_SOURCE_NAME = - "ControllerResourceEventSource"; - public static final String RETRY_RESCHEDULE_TIMER_EVENT_SOURCE_NAME = - "RetryAndRescheduleTimerEventSource"; +class EventSources

{ - private final ConcurrentNavigableMap> sources = + private final ConcurrentNavigableMap>> sources = new ConcurrentSkipListMap<>(); - private final TimerEventSource retryAndRescheduleTimerEventSource = new TimerEventSource<>(); - private ControllerResourceEventSource controllerResourceEventSource; - + private final Map sourceByName = new HashMap<>(); - void createControllerEventSource(Controller controller) { - controllerResourceEventSource = new ControllerResourceEventSource<>(controller); - } + private final TimerEventSource

retryAndRescheduleTimerEventSource = + new TimerEventSource<>("RetryAndRescheduleTimerEventSource"); + private ControllerEventSource

controllerEventSource; - ControllerResourceEventSource controllerResourceEventSource() { - return controllerResourceEventSource; + public void add(EventSource eventSource) { + final var name = eventSource.name(); + var existing = sourceByName.get(name); + if (existing != null) { + throw new IllegalArgumentException("Event source " + existing + + " is already registered with name: " + name); + } + sourceByName.put(name, eventSource); + sources.computeIfAbsent(keyFor(eventSource), k -> new ConcurrentHashMap<>()).put(name, + eventSource); } - TimerEventSource retryEventSource() { - return retryAndRescheduleTimerEventSource; + public EventSource remove(String name) { + var optionalMap = sources.values().stream().filter(m -> m.containsKey(name)).findFirst(); + sourceByName.remove(name); + return optionalMap.map(m -> m.remove(name)).orElse(null); } - public Stream additionalNamedEventSources() { - return Stream.concat(Stream.of( - new NamedEventSource(retryAndRescheduleTimerEventSource, - RETRY_RESCHEDULE_TIMER_EVENT_SOURCE_NAME)), - flatMappedSources()); + public void clear() { + sources.clear(); + sourceByName.clear(); } - public Stream allNamedEventSources() { - return Stream.concat(Stream.of(namedControllerResourceEventSource(), - new NamedEventSource(retryAndRescheduleTimerEventSource, - RETRY_RESCHEDULE_TIMER_EVENT_SOURCE_NAME)), - flatMappedSources()); + public EventSource existingEventSourceByName(String name) { + return sourceByName.get(name); } - Stream additionalEventSources() { - return Stream.concat( - Stream.of(retryEventSource()).filter(Objects::nonNull), - flatMappedSources().map(NamedEventSource::original)); + void createControllerEventSource(Controller

controller) { + controllerEventSource = new ControllerEventSource<>(controller); } - NamedEventSource namedControllerResourceEventSource() { - return new NamedEventSource(controllerResourceEventSource, - CONTROLLER_RESOURCE_EVENT_SOURCE_NAME); + public ControllerEventSource

controllerEventSource() { + return controllerEventSource; } - Stream flatMappedSources() { - return sources.values().stream().flatMap(c -> c.values().stream()); + TimerEventSource

retryEventSource() { + return retryAndRescheduleTimerEventSource; } - public void clear() { - sources.clear(); + @SuppressWarnings("rawtypes") + public Stream allEventSources() { + return Stream.concat( + Stream.of(controllerEventSource(), retryAndRescheduleTimerEventSource), + flatMappedSources()); } - public NamedEventSource existing(String name, EventSource source) { - final var eventSources = sources.get(keyFor(source)); - if (eventSources == null || eventSources.isEmpty()) { - return null; - } - return eventSources.get(name); + @SuppressWarnings("rawtypes") + Stream additionalEventSources() { + return Stream.concat( + Stream.of(retryEventSource()).filter(Objects::nonNull), + flatMappedSources()); } - public void add(NamedEventSource eventSource) { - final var name = eventSource.name(); - final var original = eventSource.original(); - final var existing = existing(name, original); - if (existing != null && !eventSource.equals(existing)) { - throw new IllegalArgumentException("Event source " + existing.original() - + " is already registered for the " - + keyAsString(getResourceType(original), name) - + " class/name combination"); - } - sources.computeIfAbsent(keyFor(original), k -> new ConcurrentHashMap<>()).put(name, - eventSource); + Stream> flatMappedSources() { + return sources.values().stream().flatMap(c -> c.values().stream()); } - @SuppressWarnings("rawtypes") - private Class getResourceType(EventSource source) { - return source instanceof ResourceEventSource - ? ((ResourceEventSource) source).resourceType() - : source.getClass(); - } - private String keyFor(EventSource source) { - if (source instanceof NamedEventSource) { - source = ((NamedEventSource) source).original(); - } - return keyFor(getResourceType(source)); + private String keyFor(EventSource source) { + return keyFor(source.resourceType()); } private String keyFor(Class dependentType) { @@ -117,21 +95,20 @@ private String keyFor(Class dependentType) { } @SuppressWarnings("unchecked") - public ResourceEventSource get(Class dependentType, String name) { + public EventSource get(Class dependentType, String name) { if (dependentType == null) { throw new IllegalArgumentException("Must pass a dependent type to retrieve event sources"); } final var sourcesForType = sources.get(keyFor(dependentType)); if (sourcesForType == null || sourcesForType.isEmpty()) { - throw new IllegalArgumentException( - "There is no event source found for class:" + dependentType.getName()); + throw new NoEventSourceForClassException(dependentType); } final var size = sourcesForType.size(); - NamedEventSource source; + EventSource source; if (size == 1 && name == null) { - source = sourcesForType.values().stream().findFirst().orElseThrow(); + source = (EventSource) sourcesForType.values().stream().findFirst().orElseThrow(); } else { if (name == null || name.isBlank()) { throw new IllegalArgumentException("There are multiple EventSources registered for type " @@ -139,7 +116,7 @@ public ResourceEventSource get(Class dependentType, String name) { + ", you need to provide a name to specify which EventSource you want to query. Known names: " + String.join(",", sourcesForType.keySet())); } - source = sourcesForType.get(name); + source = (EventSource) sourcesForType.get(name); if (source == null) { throw new IllegalArgumentException("There is no event source found for class:" + @@ -147,21 +124,14 @@ public ResourceEventSource get(Class dependentType, String name) { } } - EventSource original = source.original(); - if (!(original instanceof ResourceEventSource)) { - throw new IllegalArgumentException(source + " associated with " - + keyAsString(dependentType, name) + " is not a " - + ResourceEventSource.class.getSimpleName()); - } - final var res = (ResourceEventSource) original; - final var resourceClass = res.resourceType(); + final var resourceClass = source.resourceType(); if (!resourceClass.isAssignableFrom(dependentType)) { - throw new IllegalArgumentException(original + " associated with " + throw new IllegalArgumentException(source + " associated with " + keyAsString(dependentType, name) + " is handling " + resourceClass.getName() + " resources but asked for " + dependentType.getName()); } - return res; + return source; } @SuppressWarnings("rawtypes") @@ -172,21 +142,12 @@ private String keyAsString(Class dependentType, String name) { } @SuppressWarnings("unchecked") - public List> getEventSources(Class dependentType) { + public List> getEventSources(Class dependentType) { final var sourcesForType = sources.get(keyFor(dependentType)); if (sourcesForType == null) { return Collections.emptyList(); } - return sourcesForType.values().stream() - .map(NamedEventSource::original) - .filter(ResourceEventSource.class::isInstance) - .map(es -> (ResourceEventSource) es) - .collect(Collectors.toList()); - } - - public EventSource remove(String name) { - var optionalMap = sources.values().stream().filter(m -> m.containsKey(name)).findFirst(); - return optionalMap.map(m -> m.remove(name)).orElse(null); + .map(es -> (EventSource) es).toList(); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/NamedEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/NamedEventSource.java index a1d1a601e4..e69de29bb2 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/NamedEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/NamedEventSource.java @@ -1,105 +0,0 @@ -package io.javaoperatorsdk.operator.processing.event; - -import java.util.Objects; -import java.util.Optional; - -import io.javaoperatorsdk.operator.OperatorException; -import io.javaoperatorsdk.operator.api.reconciler.EventSourceInitializer; -import io.javaoperatorsdk.operator.processing.event.source.Configurable; -import io.javaoperatorsdk.operator.processing.event.source.EventSource; -import io.javaoperatorsdk.operator.processing.event.source.EventSourceStartPriority; -import io.javaoperatorsdk.operator.processing.event.source.ResourceEventSource; - -class NamedEventSource implements EventSource, EventSourceMetadata { - - private final EventSource original; - private final String name; - private final boolean nameSet; - - NamedEventSource(EventSource original, String name) { - this.original = original; - this.name = name; - nameSet = !name.equals(EventSourceInitializer.generateNameFor(original)); - } - - @Override - public void start() throws OperatorException { - original.start(); - } - - @Override - public void stop() throws OperatorException { - original.stop(); - } - - @Override - public void setEventHandler(EventHandler handler) { - original.setEventHandler(handler); - } - - public String name() { - return name; - } - - @Override - public Class type() { - return original.getClass(); - } - - @Override - @SuppressWarnings({"rawtypes", "unchecked"}) - public Optional> resourceType() { - if (original instanceof ResourceEventSource) { - ResourceEventSource resourceEventSource = (ResourceEventSource) original; - return Optional.of(resourceEventSource.resourceType()); - } - return Optional.empty(); - } - - @Override - @SuppressWarnings("rawtypes") - public Optional configuration() { - if (original instanceof Configurable) { - Configurable configurable = (Configurable) original; - return Optional.ofNullable(configurable.configuration()); - } - return Optional.empty(); - } - - public EventSource eventSource() { - return original; - } - - @Override - public String toString() { - return original + " named: " + name; - } - - public EventSource original() { - return original; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - NamedEventSource that = (NamedEventSource) o; - return Objects.equals(original, that.original) && Objects.equals(name, that.name); - } - - @Override - public int hashCode() { - return Objects.hash(original, name); - } - - @Override - public EventSourceStartPriority priority() { - return original.priority(); - } - - public boolean isNameSet() { - return nameSet; - } -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/NoEventSourceForClassException.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/NoEventSourceForClassException.java new file mode 100644 index 0000000000..74c3449f87 --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/NoEventSourceForClassException.java @@ -0,0 +1,16 @@ +package io.javaoperatorsdk.operator.processing.event; + +import io.javaoperatorsdk.operator.OperatorException; + +public class NoEventSourceForClassException extends OperatorException { + + private Class clazz; + + public NoEventSourceForClassException(Class clazz) { + this.clazz = clazz; + } + + public Class getClazz() { + return clazz; + } +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/PostExecutionControl.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/PostExecutionControl.java index 6fddd5ad93..3343cff80a 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/PostExecutionControl.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/PostExecutionControl.java @@ -37,7 +37,7 @@ public static PostExecutionControl customResourceStat return new PostExecutionControl<>(false, updatedCustomResource, true, null); } - public static PostExecutionControl customResourceUpdated( + public static PostExecutionControl customResourcePatched( R updatedCustomResource) { return new PostExecutionControl<>(false, updatedCustomResource, false, null); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/ReconciliationDispatcher.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/ReconciliationDispatcher.java index 9189cc6822..1ad3b65910 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/ReconciliationDispatcher.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/ReconciliationDispatcher.java @@ -1,5 +1,6 @@ package io.javaoperatorsdk.operator.processing.event; +import java.lang.reflect.InvocationTargetException; import java.util.function.Function; import org.slf4j.Logger; @@ -8,26 +9,24 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.KubernetesResourceList; import io.fabric8.kubernetes.api.model.Namespaced; -import io.fabric8.kubernetes.client.CustomResource; +import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; +import io.fabric8.kubernetes.client.dsl.base.PatchContext; +import io.fabric8.kubernetes.client.dsl.base.PatchType; import io.javaoperatorsdk.operator.OperatorException; -import io.javaoperatorsdk.operator.api.ObservedGenerationAware; import io.javaoperatorsdk.operator.api.config.Cloner; import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.reconciler.BaseControl; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.DefaultContext; import io.javaoperatorsdk.operator.api.reconciler.DeleteControl; -import io.javaoperatorsdk.operator.api.reconciler.ErrorStatusHandler; import io.javaoperatorsdk.operator.api.reconciler.RetryInfo; import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.javaoperatorsdk.operator.processing.Controller; -import static io.javaoperatorsdk.operator.processing.KubernetesResourceUtils.getName; -import static io.javaoperatorsdk.operator.processing.KubernetesResourceUtils.getUID; -import static io.javaoperatorsdk.operator.processing.KubernetesResourceUtils.getVersion; +import static io.javaoperatorsdk.operator.processing.KubernetesResourceUtils.*; /** * Handles calls and results of a Reconciler and finalizer related logic @@ -44,19 +43,22 @@ class ReconciliationDispatcher

{ // Usually for testing purposes. private final boolean retryConfigurationHasZeroAttempts; private final Cloner cloner; + private final boolean useSSA; - ReconciliationDispatcher(Controller

controller, - CustomResourceFacade

customResourceFacade) { + ReconciliationDispatcher(Controller

controller, CustomResourceFacade

customResourceFacade) { this.controller = controller; this.customResourceFacade = customResourceFacade; - this.cloner = controller.getConfiguration().getConfigurationService().getResourceCloner(); + final var configuration = controller.getConfiguration(); + this.cloner = configuration.getConfigurationService().getResourceCloner(); - var retry = controller.getConfiguration().getRetry(); + var retry = configuration.getRetry(); retryConfigurationHasZeroAttempts = retry == null || retry.initExecution().isLastAttempt(); + useSSA = configuration.getConfigurationService().useSSAToPatchPrimaryResource(); } public ReconciliationDispatcher(Controller

controller) { - this(controller, new CustomResourceFacade<>(controller.getCRClient())); + this(controller, + new CustomResourceFacade<>(controller.getCRClient(), controller.getConfiguration())); } public PostExecutionControl

handleExecution(ExecutionScope

executionScope) { @@ -86,7 +88,7 @@ private PostExecutionControl

handleDispatch(ExecutionScope

executionScope) Context

context = new DefaultContext<>(executionScope.getRetryInfo(), controller, originalResource); if (markedForDeletion) { - return handleCleanup(resourceForExecution, context); + return handleCleanup(resourceForExecution, originalResource, context); } else { return handleReconcile(executionScope, resourceForExecution, originalResource, context); } @@ -109,8 +111,13 @@ private PostExecutionControl

handleReconcile( * finalizer add. This will make sure that the resources are not created before there is a * finalizer. */ - var updatedResource = - updateCustomResourceWithFinalizer(resourceForExecution, originalResource); + P updatedResource; + if (useSSA) { + updatedResource = addFinalizerWithSSA(originalResource); + } else { + updatedResource = + updateCustomResourceWithFinalizer(resourceForExecution, originalResource); + } return PostExecutionControl.onlyFinalizerAdded(updatedResource); } else { try { @@ -134,34 +141,30 @@ private PostExecutionControl

reconcileExecution(ExecutionScope

executionSc executionScope); UpdateControl

updateControl = controller.reconcile(resourceForExecution, context); + + final P toUpdate; P updatedCustomResource = null; - if (updateControl.isUpdateResourceAndStatus()) { - updatedCustomResource = - updateCustomResource(updateControl.getResource()); - updateControl - .getResource() - .getMetadata() - .setResourceVersion(updatedCustomResource.getMetadata().getResourceVersion()); - updatedCustomResource = - updateStatusGenerationAware(updateControl.getResource(), originalResource, - updateControl.isPatchStatus()); - } else if (updateControl.isUpdateStatus()) { - updatedCustomResource = - updateStatusGenerationAware(updateControl.getResource(), originalResource, - updateControl.isPatchStatus()); - } else if (updateControl.isUpdateResource()) { - updatedCustomResource = - updateCustomResource(updateControl.getResource()); - if (shouldUpdateObservedGenerationAutomatically(updatedCustomResource)) { - updatedCustomResource = - updateStatusGenerationAware(updateControl.getResource(), originalResource, - updateControl.isPatchStatus()); + if (useSSA) { + if (updateControl.isNoUpdate()) { + return createPostExecutionControl(null, updateControl); + } else { + toUpdate = updateControl.getResource().orElseThrow(); } - } else if (updateControl.isNoUpdate() - && shouldUpdateObservedGenerationAutomatically(resourceForExecution)) { - updatedCustomResource = - updateStatusGenerationAware(originalResource, originalResource, - updateControl.isPatchStatus()); + } else { + toUpdate = + updateControl.isNoUpdate() ? originalResource : updateControl.getResource().orElseThrow(); + } + + if (updateControl.isPatchResource()) { + updatedCustomResource = patchResource(toUpdate, originalResource); + if (!useSSA) { + toUpdate.getMetadata() + .setResourceVersion(updatedCustomResource.getMetadata().getResourceVersion()); + } + } + + if (updateControl.isPatchStatus()) { + customResourceFacade.patchStatus(toUpdate, originalResource); } return createPostExecutionControl(updatedCustomResource, updateControl); } @@ -170,103 +173,54 @@ && shouldUpdateObservedGenerationAutomatically(resourceForExecution)) { private PostExecutionControl

handleErrorStatusHandler(P resource, P originalResource, Context

context, Exception e) throws Exception { - if (isErrorStatusHandlerPresent()) { - try { - RetryInfo retryInfo = context.getRetryInfo().orElseGet(() -> new RetryInfo() { - @Override - public int getAttemptCount() { - return 0; - } - @Override - public boolean isLastAttempt() { - // check also if the retry is limited to 0 - return retryConfigurationHasZeroAttempts || - controller.getConfiguration().getRetry() == null; - } - }); - ((DefaultContext

) context).setRetryInfo(retryInfo); - var errorStatusUpdateControl = ((ErrorStatusHandler

) controller.getReconciler()) - .updateErrorStatus(resource, context, e); - - P updatedResource = null; - if (errorStatusUpdateControl.getResource().isPresent()) { - updatedResource = errorStatusUpdateControl.isPatch() ? customResourceFacade - .patchStatus(errorStatusUpdateControl.getResource().orElseThrow(), originalResource) - : customResourceFacade - .updateStatus(errorStatusUpdateControl.getResource().orElseThrow()); - } - if (errorStatusUpdateControl.isNoRetry()) { - PostExecutionControl

postExecutionControl; - if (updatedResource != null) { - postExecutionControl = errorStatusUpdateControl.isPatch() - ? PostExecutionControl.customResourceStatusPatched(updatedResource) - : PostExecutionControl.customResourceUpdated(updatedResource); - } else { - postExecutionControl = PostExecutionControl.defaultDispatch(); - } - errorStatusUpdateControl.getScheduleDelay() - .ifPresent(postExecutionControl::withReSchedule); - return postExecutionControl; - } - } catch (RuntimeException ex) { - log.error("Error during error status handling.", ex); + RetryInfo retryInfo = context.getRetryInfo().orElseGet(() -> new RetryInfo() { + @Override + public int getAttemptCount() { + return 0; } - } - throw e; - } - private boolean isErrorStatusHandlerPresent() { - return controller.getReconciler() instanceof ErrorStatusHandler; - } + @Override + public boolean isLastAttempt() { + // check also if the retry is limited to 0 + return retryConfigurationHasZeroAttempts || + controller.getConfiguration().getRetry() == null; + } + }); + ((DefaultContext

) context).setRetryInfo(retryInfo); + var errorStatusUpdateControl = controller.getReconciler() + .updateErrorStatus(resource, context, e); - private P updateStatusGenerationAware(P resource, P originalResource, boolean patch) { - updateStatusObservedGenerationIfRequired(resource); - if (patch) { - return customResourceFacade.patchStatus(resource, originalResource); - } else { - return customResourceFacade.updateStatus(resource); + if (errorStatusUpdateControl.isDefaultErrorProcessing()) { + throw e; } - } - @SuppressWarnings("rawtypes") - private boolean shouldUpdateObservedGenerationAutomatically(P resource) { - if (configuration().isGenerationAware() && resource instanceof CustomResource) { - var customResource = (CustomResource) resource; - var status = customResource.getStatus(); - // Note that if status is null we won't update the observed generation. - if (status instanceof ObservedGenerationAware) { - var observedGen = ((ObservedGenerationAware) status).getObservedGeneration(); - var currentGen = resource.getMetadata().getGeneration(); - return !currentGen.equals(observedGen); - } + P updatedResource = null; + if (errorStatusUpdateControl.getResource().isPresent()) { + updatedResource = customResourceFacade + .patchStatus(errorStatusUpdateControl.getResource().orElseThrow(), originalResource); } - return false; - } - - @SuppressWarnings("rawtypes") - private void updateStatusObservedGenerationIfRequired(P resource) { - if (configuration().isGenerationAware() && resource instanceof CustomResource) { - var customResource = (CustomResource) resource; - var status = customResource.getStatus(); - // Note that if status is null we won't update the observed generation. - if (status instanceof ObservedGenerationAware) { - ((ObservedGenerationAware) status) - .setObservedGeneration(resource.getMetadata().getGeneration()); + if (errorStatusUpdateControl.isNoRetry()) { + PostExecutionControl

postExecutionControl; + if (updatedResource != null) { + postExecutionControl = + PostExecutionControl.customResourceStatusPatched(updatedResource); + } else { + postExecutionControl = PostExecutionControl.defaultDispatch(); } + errorStatusUpdateControl.getScheduleDelay() + .ifPresent(postExecutionControl::withReSchedule); + return postExecutionControl; } + throw e; } private PostExecutionControl

createPostExecutionControl(P updatedCustomResource, UpdateControl

updateControl) { PostExecutionControl

postExecutionControl; if (updatedCustomResource != null) { - if (updateControl.isUpdateStatus() && updateControl.isPatchStatus()) { - postExecutionControl = - PostExecutionControl.customResourceStatusPatched(updatedCustomResource); - } else { - postExecutionControl = PostExecutionControl.customResourceUpdated(updatedCustomResource); - } + postExecutionControl = + PostExecutionControl.customResourceStatusPatched(updatedCustomResource); } else { postExecutionControl = PostExecutionControl.defaultDispatch(); } @@ -281,7 +235,7 @@ private void updatePostExecutionControlWithReschedule( } private PostExecutionControl

handleCleanup(P resource, - Context

context) { + P originalResource, Context

context) { if (log.isDebugEnabled()) { log.debug( "Executing delete for resource: {} with version: {}", @@ -295,7 +249,7 @@ private PostExecutionControl

handleCleanup(P resource, // cleanup is finished, nothing left to done final var finalizerName = configuration().getFinalizerName(); if (deleteControl.isRemoveFinalizer() && resource.hasFinalizer(finalizerName)) { - P customResource = conflictRetryingUpdate(resource, r -> { + P customResource = conflictRetryingPatch(resource, originalResource, r -> { // the operator might not be allowed to retrieve the resource on a retry, e.g. when its // permissions are removed by deleting the namespace concurrently if (r == null) { @@ -306,7 +260,7 @@ private PostExecutionControl

handleCleanup(P resource, return false; } return r.removeFinalizer(finalizerName); - }); + }, true); return PostExecutionControl.customResourceFinalizerRemoved(customResource); } } @@ -321,27 +275,55 @@ private PostExecutionControl

handleCleanup(P resource, return postExecutionControl; } + @SuppressWarnings("unchecked") + private P addFinalizerWithSSA(P originalResource) { + log.debug( + "Adding finalizer (using SSA) for resource: {} version: {}", + getUID(originalResource), getVersion(originalResource)); + try { + P resource = (P) originalResource.getClass().getConstructor().newInstance(); + ObjectMeta objectMeta = new ObjectMeta(); + objectMeta.setName(originalResource.getMetadata().getName()); + objectMeta.setNamespace(originalResource.getMetadata().getNamespace()); + resource.setMetadata(objectMeta); + resource.addFinalizer(configuration().getFinalizerName()); + return customResourceFacade.patchResourceWithSSA(resource); + } catch (InstantiationException | IllegalAccessException | InvocationTargetException + | NoSuchMethodException e) { + throw new RuntimeException("Issue with creating custom resource instance with reflection." + + " Custom Resources must provide a no-arg constructor. Class: " + + originalResource.getClass().getName(), + e); + } + } + private P updateCustomResourceWithFinalizer(P resourceForExecution, P originalResource) { log.debug( "Adding finalizer for resource: {} version: {}", getUID(originalResource), getVersion(originalResource)); - return conflictRetryingUpdate(resourceForExecution, - r -> r.addFinalizer(configuration().getFinalizerName())); + return conflictRetryingPatch(resourceForExecution, originalResource, + r -> r.addFinalizer(configuration().getFinalizerName()), false); } - private P updateCustomResource(P resource) { + private P patchResource(P resource, P originalResource) { log.debug("Updating resource: {} with version: {}", getUID(resource), getVersion(resource)); log.trace("Resource before update: {}", resource); - return customResourceFacade.updateResource(resource); + final var finalizerName = configuration().getFinalizerName(); + if (useSSA && controller.useFinalizer()) { + // addFinalizer already prevents adding an already present finalizer so no need to check + resource.addFinalizer(finalizerName); + } + return customResourceFacade.patchResource(resource, originalResource); } ControllerConfiguration

configuration() { return controller.getConfiguration(); } - public P conflictRetryingUpdate(P resource, Function modificationFunction) { + public P conflictRetryingPatch(P resource, P originalResource, + Function modificationFunction, boolean forceNotUseSSA) { if (log.isDebugEnabled()) { log.debug("Conflict retrying update for: {}", ResourceID.fromResource(resource)); } @@ -352,7 +334,11 @@ public P conflictRetryingUpdate(P resource, Function modificationFun if (Boolean.FALSE.equals(modified)) { return resource; } - return customResourceFacade.updateResource(resource); + if (forceNotUseSSA) { + return customResourceFacade.patchResourceWithoutSSA(resource, originalResource); + } else { + return customResourceFacade.patchResource(resource, originalResource); + } } catch (KubernetesClientException e) { log.trace("Exception during patch for resource: {}", resource); retryIndex++; @@ -376,10 +362,16 @@ public P conflictRetryingUpdate(P resource, Function modificationFun static class CustomResourceFacade { private final MixedOperation, Resource> resourceOperation; + private final boolean useSSA; + private final String fieldManager; public CustomResourceFacade( - MixedOperation, Resource> resourceOperation) { + MixedOperation, Resource> resourceOperation, + ControllerConfiguration configuration) { this.resourceOperation = resourceOperation; + this.useSSA = + configuration.getConfigurationService().useSSAToPatchPrimaryResource(); + this.fieldManager = configuration.fieldManager(); } public R getResource(String namespace, String name) { @@ -390,33 +382,47 @@ public R getResource(String namespace, String name) { } } - public R updateResource(R resource) { + public R patchResourceWithoutSSA(R resource, R originalResource) { + return resource(originalResource).edit(r -> resource); + } + + public R patchResource(R resource, R originalResource) { if (log.isDebugEnabled()) { log.debug( "Trying to replace resource {}, version: {}", ResourceID.fromResource(resource), resource.getMetadata().getResourceVersion()); } - return resource(resource).lockResourceVersion(resource.getMetadata().getResourceVersion()) - .update(); - } - - public R updateStatus(R resource) { - log.trace("Updating status for resource: {}", resource); - return resource(resource) - .lockResourceVersion() - .updateStatus(); + if (useSSA) { + return patchResourceWithSSA(resource); + } else { + return resource(originalResource).edit(r -> resource); + } } public R patchStatus(R resource, R originalResource) { - log.trace("Updating status for resource: {}", resource); + log.trace("Patching status for resource: {} with ssa: {}", resource, useSSA); String resourceVersion = resource.getMetadata().getResourceVersion(); - // don't do optimistic locking on patch originalResource.getMetadata().setResourceVersion(null); resource.getMetadata().setResourceVersion(null); try { - return resource(originalResource) - .editStatus(r -> resource); + if (useSSA) { + var managedFields = resource.getMetadata().getManagedFields(); + try { + resource.getMetadata().setManagedFields(null); + var res = resource(resource); + return res.subresource("status").patch(new PatchContext.Builder() + .withFieldManager(fieldManager) + .withForce(true) + .withPatchType(PatchType.SERVER_SIDE_APPLY) + .build()); + } finally { + resource.getMetadata().setManagedFields(managedFields); + } + } else { + var res = resource(originalResource); + return res.editStatus(r -> resource); + } } finally { // restore initial resource version originalResource.getMetadata().setResourceVersion(resourceVersion); @@ -424,6 +430,14 @@ public R patchStatus(R resource, R originalResource) { } } + public R patchResourceWithSSA(R resource) { + return resource(resource).patch(new PatchContext.Builder() + .withFieldManager(fieldManager) + .withForce(true) + .withPatchType(PatchType.SERVER_SIDE_APPLY) + .build()); + } + private Resource resource(R resource) { return resource instanceof Namespaced ? resourceOperation .inNamespace(resource.getMetadata().getNamespace()) diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/ResourceID.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/ResourceID.java index 39374cb433..071dd49f29 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/ResourceID.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/ResourceID.java @@ -14,20 +14,6 @@ public static ResourceID fromResource(HasMetadata resource) { resource.getMetadata().getNamespace()); } - public static Optional fromFirstOwnerReference(HasMetadata resource) { - return fromFirstOwnerReference(resource, false); - } - - public static Optional fromFirstOwnerReference(HasMetadata resource, - boolean clusterScoped) { - var ownerReferences = resource.getMetadata().getOwnerReferences(); - if (!ownerReferences.isEmpty()) { - return Optional.of(fromOwnerReference(resource, ownerReferences.get(0), clusterScoped)); - } else { - return Optional.empty(); - } - } - public static ResourceID fromOwnerReference(HasMetadata resource, OwnerReference ownerReference, boolean clusterScoped) { return new ResourceID(ownerReference.getName(), diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiter.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiter.java index 02a919f547..2692b60bd0 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiter.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiter.java @@ -36,11 +36,10 @@ public LinearRateLimiter(Duration refreshPeriod, int limitForPeriod) { @Override public Optional isLimited(RateLimitState rateLimitState) { - if (!isActivated() || !(rateLimitState instanceof RateState)) { + if (!isActivated() || !(rateLimitState instanceof RateState actualState)) { return Optional.empty(); } - var actualState = (RateState) rateLimitState; if (actualState.getCount() < limitForPeriod) { actualState.increaseCount(); return Optional.empty(); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/AbstractEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/AbstractEventSource.java index 4eaee91add..a2306378d4 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/AbstractEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/AbstractEventSource.java @@ -1,12 +1,41 @@ package io.javaoperatorsdk.operator.processing.event.source; + +import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.OperatorException; import io.javaoperatorsdk.operator.processing.event.EventHandler; +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; + +public abstract class AbstractEventSource implements EventSource { + + private final Class resourceClass; + + protected OnAddFilter onAddFilter; + protected OnUpdateFilter onUpdateFilter; + protected OnDeleteFilter onDeleteFilter; + protected GenericFilter genericFilter; -public abstract class AbstractEventSource implements EventSource { private EventHandler handler; private volatile boolean running = false; private EventSourceStartPriority eventSourceStartPriority = EventSourceStartPriority.DEFAULT; + private final String name; + + protected AbstractEventSource(Class resourceClass) { + this(resourceClass, null); + } + + protected AbstractEventSource(Class resourceClass, String name) { + this.name = name == null ? EventSource.super.name() : name; + this.resourceClass = resourceClass; + } + + @Override + public String name() { + return name; + } protected EventHandler getEventHandler() { return handler; @@ -41,4 +70,28 @@ public AbstractEventSource setEventSourcePriority( this.eventSourceStartPriority = eventSourceStartPriority; return this; } + + @Override + public Class resourceType() { + return resourceClass; + } + + public void setOnAddFilter(OnAddFilter onAddFilter) { + this.onAddFilter = onAddFilter; + } + + public void setOnUpdateFilter( + OnUpdateFilter onUpdateFilter) { + this.onUpdateFilter = onUpdateFilter; + } + + public void setOnDeleteFilter( + OnDeleteFilter onDeleteFilter) { + this.onDeleteFilter = onDeleteFilter; + } + + public void setGenericFilter(GenericFilter genericFilter) { + this.genericFilter = genericFilter; + } + } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/AbstractResourceEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/AbstractResourceEventSource.java deleted file mode 100644 index 65294c1625..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/AbstractResourceEventSource.java +++ /dev/null @@ -1,45 +0,0 @@ -package io.javaoperatorsdk.operator.processing.event.source; - -import io.fabric8.kubernetes.api.model.HasMetadata; -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; - -public abstract class AbstractResourceEventSource - extends AbstractEventSource - implements ResourceEventSource { - private final Class resourceClass; - - protected OnAddFilter onAddFilter; - protected OnUpdateFilter onUpdateFilter; - protected OnDeleteFilter onDeleteFilter; - protected GenericFilter genericFilter; - - protected AbstractResourceEventSource(Class resourceClass) { - this.resourceClass = resourceClass; - } - - @Override - public Class resourceType() { - return resourceClass; - } - - public void setOnAddFilter(OnAddFilter onAddFilter) { - this.onAddFilter = onAddFilter; - } - - public void setOnUpdateFilter( - OnUpdateFilter onUpdateFilter) { - this.onUpdateFilter = onUpdateFilter; - } - - public void setOnDeleteFilter( - OnDeleteFilter onDeleteFilter) { - this.onDeleteFilter = onDeleteFilter; - } - - public void setGenericFilter(GenericFilter genericFilter) { - this.genericFilter = genericFilter; - } -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/EventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/EventSource.java index ec2783f797..850a9deb35 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/EventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/EventSource.java @@ -1,18 +1,33 @@ package io.javaoperatorsdk.operator.processing.event.source; +import java.util.Optional; +import java.util.Set; + +import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.health.EventSourceHealthIndicator; import io.javaoperatorsdk.operator.health.Status; import io.javaoperatorsdk.operator.processing.LifecycleAware; import io.javaoperatorsdk.operator.processing.event.EventHandler; +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; /** * Creates an event source to trigger your reconciler whenever something happens to a secondary or - * external resource that would not normally trigger your reconciler (as the primary resources are - * not changed). To register EventSources with so that your reconciler is triggered, please make - * your reconciler implement - * {@link io.javaoperatorsdk.operator.api.reconciler.EventSourceInitializer}. + * external resource that should cause a reconciliation of the primary resource. EventSource + * generalizes the concept of Informers and extends it to external (i.e. non Kubernetes) resources. + * + * @param the resource type that this EventSource is associated with + * @param

the primary resource type which reconciler needs to be triggered when events occur on + * resources of type R */ -public interface EventSource extends LifecycleAware, EventSourceHealthIndicator { +public interface EventSource + extends LifecycleAware, EventSourceHealthIndicator { + + static String generateName(EventSource eventSource) { + return eventSource.getClass().getName() + "@" + Integer.toHexString(eventSource.hashCode()); + } /** * Sets the {@link EventHandler} that is linked to your reconciler when this EventSource is @@ -22,10 +37,69 @@ public interface EventSource extends LifecycleAware, EventSourceHealthIndicator */ void setEventHandler(EventHandler handler); + /** + * Retrieves the EventSource's name so that it can be referred to + * + * @return the EventSource's name + */ + default String name() { + return generateName(this); + } + + /** + * Retrieves the EventSource's starting priority + * + * @return the EventSource's starting priority + * @see EventSourceStartPriority + */ default EventSourceStartPriority priority() { return EventSourceStartPriority.DEFAULT; } + /** + * Retrieves the resource type associated with this ResourceEventSource + * + * @return the resource type associated with this ResourceEventSource + */ + Class resourceType(); + + /** + * Retrieves the optional unique secondary resource associated with the specified primary + * resource. Note that this operation will fail if multiple resources are associated with the + * specified primary resource. + * + * @param primary the primary resource for which the secondary resource is requested + * @return the secondary resource associated with the specified primary resource + * @throws IllegalStateException if multiple resources are associated with the primary one + */ + default Optional getSecondaryResource(P primary) { + var resources = getSecondaryResources(primary); + if (resources.isEmpty()) { + return Optional.empty(); + } else if (resources.size() == 1) { + return Optional.of(resources.iterator().next()); + } else { + throw new IllegalStateException("More than 1 secondary resource related to primary"); + } + } + + /** + * Retrieves a potential empty set of resources tracked by this EventSource associated with the + * specified primary resource + * + * @param primary the primary resource for which the secondary resource is requested + * @return the set of secondary resources associated with the specified primary + */ + Set getSecondaryResources(P primary); + + void setOnAddFilter(OnAddFilter onAddFilter); + + void setOnUpdateFilter(OnUpdateFilter onUpdateFilter); + + void setOnDeleteFilter(OnDeleteFilter onDeleteFilter); + + void setGenericFilter(GenericFilter genericFilter); + @Override default Status getStatus() { return Status.UNKNOWN; diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/EventSourceStartPriority.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/EventSourceStartPriority.java index d1d758bdb4..8284d611f2 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/EventSourceStartPriority.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/EventSourceStartPriority.java @@ -1,17 +1,27 @@ package io.javaoperatorsdk.operator.processing.event.source; +/** + * Defines priority levels for {@link EventSource} implementation to ensure that some sources are + * started before others + */ public enum EventSourceStartPriority { /** * Event Sources with this priority are started and synced before the event source with DEFAULT - * priority. The use case to use this, if the event source holds an information regarding the - * state of a resource. For example a ConfigMap would store an ID of an external resource, in this - * case an event source that tracks the external resource might need this ID (event before the - * reconciliation) to check the state of the external resource. The only way to ensure that the ID - * is already cached is to start/sync related event source before the event source of the external - * resource. + * priority. This is needed if the event source holds information about another resource's state. + * In this situation, it is needed to initialize this event source before the one associated with + * resources which state is being tracked since that state information might be required to + * properly retrieve the other resources. + * + *

+ * For example a {@code ConfigMap} could store the identifier of a fictional external resource + * {@code A}. In this case, the event source tracking {@code A} resources might need the + * identifier from the {@code ConfigMap} to identify and check the state of {@code A} resources. + * This is usually needed before any reconciliation occurs and the only way to ensure the proper + * behavior in this case is to make sure that the event source tracking the {@code ConfigMaps} (in + * this example) is started/cache-synced before the event source for {@code A} resources gets + * started. + *

*/ RESOURCE_STATE_LOADER, DEFAULT - - } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/ExternalResourceCachingEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/ExternalResourceCachingEventSource.java index 58778edbdf..130e3db179 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/ExternalResourceCachingEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/ExternalResourceCachingEventSource.java @@ -1,6 +1,13 @@ package io.javaoperatorsdk.operator.processing.event.source; -import java.util.*; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -33,7 +40,7 @@ * @param

primary resource */ public abstract class ExternalResourceCachingEventSource - extends AbstractResourceEventSource implements RecentOperationCacheFiller { + extends AbstractEventSource implements RecentOperationCacheFiller { private static final Logger log = LoggerFactory.getLogger(ExternalResourceCachingEventSource.class); @@ -44,7 +51,12 @@ public abstract class ExternalResourceCachingEventSource resourceClass, CacheKeyMapper cacheKeyMapper) { - super(resourceClass); + this(null, resourceClass, cacheKeyMapper); + } + + protected ExternalResourceCachingEventSource(String name, Class resourceClass, + CacheKeyMapper cacheKeyMapper) { + super(resourceClass, name); this.cacheKeyMapper = cacheKeyMapper; } @@ -90,8 +102,7 @@ protected synchronized void handleResources(ResourceID primaryID, Set newReso } protected synchronized void handleResources(Map> allNewResources) { - var toDelete = cache.keySet().stream().filter(k -> !allNewResources.containsKey(k)) - .collect(Collectors.toList()); + var toDelete = cache.keySet().stream().filter(k -> !allNewResources.containsKey(k)).toList(); toDelete.forEach(this::handleDelete); allNewResources.forEach(this::handleResources); } @@ -153,21 +164,15 @@ private boolean acceptedByFiler(Map cachedResourceMap, .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); if (onUpdateFilter != null || genericFilter != null) { - var anyUpdated = possibleUpdatedResources.entrySet().stream() + return possibleUpdatedResources.entrySet().stream() .anyMatch( entry -> { var newResource = newResourcesMap.get(entry.getKey()); return acceptedByGenericFiler(newResource) && onUpdateFilter.accept(newResource, entry.getValue()); }); - if (anyUpdated) { - return true; - } - } else if (!possibleUpdatedResources.isEmpty()) { - return true; - } - - return false; + } else + return !possibleUpdatedResources.isEmpty(); } private boolean acceptedByGenericFiler(R resource) { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/PrimaryToSecondaryMapper.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/PrimaryToSecondaryMapper.java index 9a5bfbac5d..2ff61f81e8 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/PrimaryToSecondaryMapper.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/PrimaryToSecondaryMapper.java @@ -3,6 +3,7 @@ import java.util.Set; import io.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; import io.javaoperatorsdk.operator.processing.event.ResourceID; /** @@ -12,13 +13,12 @@ * primary resources *without* a standard way (e.g. owner reference or annotations) to materialize * that relations. When owner references are present, a {@code PrimaryToSecondaryMapper} instance * should not be needed. In other words, associating such a mapper with your - * {@link io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration} is usually needed - * when your secondary resources are referenced in some way by your primary resource but that this - * link does not exist in the secondary resource information. The mapper implementation instructs - * the SDK on how to find all the secondary resources associated with a given primary resource so - * that this primary resource can properly be reconciled when changes impact the associated - * secondary resources, even though these don't contain any information allowing to make such an - * inference. + * {@link InformerEventSourceConfiguration} is usually needed when your secondary resources are + * referenced in some way by your primary resource but that this link does not exist in the + * secondary resource information. The mapper implementation instructs the SDK on how to find all + * the secondary resources associated with a given primary resource so that this primary resource + * can properly be reconciled when changes impact the associated secondary resources, even though + * these don't contain any information allowing to make such an inference. *

*

* This helps particularly in cases where several secondary resources, listed in some way in the diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/ResourceEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/ResourceEventSource.java deleted file mode 100644 index 722e260878..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/ResourceEventSource.java +++ /dev/null @@ -1,42 +0,0 @@ -package io.javaoperatorsdk.operator.processing.event.source; - -import java.util.Optional; -import java.util.Set; - -import io.fabric8.kubernetes.api.model.HasMetadata; -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; - -public interface ResourceEventSource extends EventSource { - - /** - * Retrieves the resource type associated with this ResourceEventSource - * - * @return the resource type associated with this ResourceEventSource - */ - Class resourceType(); - - default Optional getSecondaryResource(P primary) { - var resources = getSecondaryResources(primary); - if (resources.isEmpty()) { - return Optional.empty(); - } else if (resources.size() == 1) { - return Optional.of(resources.iterator().next()); - } else { - throw new IllegalStateException("More than 1 secondary resource related to primary"); - } - - } - - Set getSecondaryResources(P primary); - - void setOnAddFilter(OnAddFilter onAddFilter); - - void setOnUpdateFilter(OnUpdateFilter onUpdateFilter); - - void setOnDeleteFilter(OnDeleteFilter onDeleteFilter); - - void setGenericFilter(GenericFilter genericFilter); -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/controller/ControllerResourceEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/controller/ControllerEventSource.java similarity index 85% rename from operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/controller/ControllerResourceEventSource.java rename to operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/controller/ControllerEventSource.java index c1ac2d3352..07e5bd3fa2 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/controller/ControllerResourceEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/controller/ControllerEventSource.java @@ -18,21 +18,21 @@ import io.javaoperatorsdk.operator.processing.event.source.informer.ManagedInformerEventSource; import static io.javaoperatorsdk.operator.ReconcilerUtils.handleKubernetesClientException; -import static io.javaoperatorsdk.operator.processing.KubernetesResourceUtils.*; +import static io.javaoperatorsdk.operator.processing.KubernetesResourceUtils.getVersion; import static io.javaoperatorsdk.operator.processing.event.source.controller.InternalEventFilters.*; -public class ControllerResourceEventSource +public class ControllerEventSource extends ManagedInformerEventSource> implements ResourceEventHandler { - private static final Logger log = LoggerFactory.getLogger(ControllerResourceEventSource.class); + private static final Logger log = LoggerFactory.getLogger(ControllerEventSource.class); + public static final String NAME = "ControllerResourceEventSource"; private final Controller controller; - private final ResourceEventFilter legacyFilters; @SuppressWarnings({"unchecked", "rawtypes"}) - public ControllerResourceEventSource(Controller controller) { - super(controller.getCRClient(), controller.getConfiguration(), false); + public ControllerEventSource(Controller controller) { + super(NAME, controller.getCRClient(), controller.getConfiguration(), false); this.controller = controller; final var config = controller.getConfiguration(); @@ -42,16 +42,14 @@ public ControllerResourceEventSource(Controller controller) { .or(onUpdateGenerationAware(config.isGenerationAware())) .or(onUpdateMarkedForDeletion()); - legacyFilters = config.getEventFilter(); - // by default the on add should be processed in all cases regarding internal filters - config.onAddFilter().ifPresent(this::setOnAddFilter); - config.onUpdateFilter() + final var informerConfig = config.getInformerConfig(); + Optional.ofNullable(informerConfig.getOnAddFilter()).ifPresent(this::setOnAddFilter); + Optional.ofNullable(informerConfig.getOnUpdateFilter()) .ifPresentOrElse(filter -> setOnUpdateFilter(filter.and(internalOnUpdateFilter)), () -> setOnUpdateFilter(internalOnUpdateFilter)); - config.genericFilter().ifPresent(this::setGenericFilter); - - setConfigurationService(config.getConfigurationService()); + Optional.ofNullable(informerConfig.getGenericFilter()).ifPresent(this::setGenericFilter); + setControllerConfiguration(config); } @Override @@ -74,9 +72,7 @@ public void eventReceived(ResourceAction action, T resource, T oldResource) { } MDCUtils.addResourceInfo(resource); controller.getEventSourceManager().broadcastOnResourceEvent(action, resource, oldResource); - if ((legacyFilters == null || - legacyFilters.acceptChange(controller, oldResource, resource)) - && isAcceptedByFilters(action, resource, oldResource)) { + if (isAcceptedByFilters(action, resource, oldResource)) { getEventHandler().handleEvent( new ResourceEvent(action, ResourceID.fromResource(resource), resource)); } else { @@ -135,4 +131,9 @@ public void setOnDeleteFilter(OnDeleteFilter onDeleteFilter) { throw new IllegalStateException( "onDeleteFilter is not supported for controller resource event source"); } + + @Override + public String name() { + return NAME; + } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/controller/ResourceEventFilter.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/controller/ResourceEventFilter.java deleted file mode 100644 index 08a86c92ae..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/controller/ResourceEventFilter.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.javaoperatorsdk.operator.processing.event.source.controller; - -import io.fabric8.kubernetes.api.model.HasMetadata; -import io.javaoperatorsdk.operator.processing.Controller; - -/** - * A functional interface to determine whether resource events should be processed by the SDK. This - * allows users to more finely tuned which events trigger a reconciliation than was previously - * possible (where the logic was limited to generation-based checking). - * - * @param

the type of custom resources handled by this filter - */ -@Deprecated(forRemoval = true) -@FunctionalInterface -public interface ResourceEventFilter

{ - - /** - * Determines whether the change between the old version of the resource and the new one needs to - * be propagated to the controller or not. - * - * @param controller the target controller - * @param oldResource the old version of the resource, null if no old resource available - * @param newResource the new version of the resource - * @return {@code true} if the change needs to be propagated to the controller, {@code false} - * otherwise - */ - boolean acceptChange(Controller

controller, P oldResource, P newResource); - - /** - * Combines this filter with the provided one with an AND logic, i.e. the resulting filter will - * only accept the change if both this and the other filter accept it, reject it otherwise. - * - * @param other the possibly {@code null} other filter to combine this one with - * @return a composite filter implementing the AND logic between this and the provided filter - */ - default ResourceEventFilter

and(ResourceEventFilter

other) { - return other == null ? this - : (Controller

controller, P oldResource, P newResource) -> { - boolean result = acceptChange(controller, oldResource, newResource); - return result && other.acceptChange(controller, oldResource, newResource); - }; - } - - /** - * Combines this filter with the provided one with an OR logic, i.e. the resulting filter will - * accept the change if any of this or the other filter accept it, rejecting it only if both - * reject it. - * - * @param other the possibly {@code null} other filter to combine this one with - * @return a composite filter implementing the OR logic between this and the provided filter - */ - default ResourceEventFilter

or(ResourceEventFilter

other) { - return other == null ? this - : (Controller

controller, P oldResource, P newResource) -> { - boolean result = acceptChange(controller, oldResource, newResource); - return result || other.acceptChange(controller, oldResource, newResource); - }; - } -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/controller/ResourceEventFilters.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/controller/ResourceEventFilters.java deleted file mode 100644 index 7024388b8b..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/controller/ResourceEventFilters.java +++ /dev/null @@ -1,27 +0,0 @@ -package io.javaoperatorsdk.operator.processing.event.source.controller; - -import io.fabric8.kubernetes.api.model.HasMetadata; - -/** - * Convenience implementations of, and utility methods for, {@link ResourceEventFilter}. - */ -@Deprecated -public final class ResourceEventFilters { - - private static final ResourceEventFilter PASSTHROUGH = - (configuration, oldResource, newResource) -> true; - - private ResourceEventFilters() {} - - /** - * Retrieves a filter that accepts all events. - * - * @param the type of custom resource the filter should handle - * @return a filter that accepts all events - */ - @SuppressWarnings("unchecked") - public static ResourceEventFilter passthrough() { - return (ResourceEventFilter) PASSTHROUGH; - } - -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/inbound/SimpleInboundEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/inbound/SimpleInboundEventSource.java index a441684f0f..7d5f2aa446 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/inbound/SimpleInboundEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/inbound/SimpleInboundEventSource.java @@ -1,16 +1,27 @@ package io.javaoperatorsdk.operator.processing.event.source.inbound; +import java.util.Set; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.processing.event.Event; import io.javaoperatorsdk.operator.processing.event.ResourceID; import io.javaoperatorsdk.operator.processing.event.source.AbstractEventSource; -public class SimpleInboundEventSource extends AbstractEventSource { +public class SimpleInboundEventSource

extends AbstractEventSource { private static final Logger log = LoggerFactory.getLogger(SimpleInboundEventSource.class); + public SimpleInboundEventSource() { + super(Void.class); + } + + public SimpleInboundEventSource(String name) { + super(Void.class, name); + } + public void propagateEvent(ResourceID resourceID) { if (isRunning()) { getEventHandler().handleEvent(new Event(resourceID)); @@ -19,4 +30,8 @@ public void propagateEvent(ResourceID resourceID) { } } + @Override + public Set getSecondaryResources(P primary) { + return Set.of(); + } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSource.java index 81d31f7407..48534a27b3 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSource.java @@ -1,6 +1,8 @@ package io.javaoperatorsdk.operator.processing.event.source.informer; -import java.util.*; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; import java.util.stream.Collectors; import org.slf4j.Logger; @@ -10,7 +12,7 @@ import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.informers.ResourceEventHandler; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; import io.javaoperatorsdk.operator.processing.event.Event; import io.javaoperatorsdk.operator.processing.event.EventHandler; @@ -64,32 +66,33 @@ * @param

type of the primary resource */ public class InformerEventSource - extends ManagedInformerEventSource> + extends ManagedInformerEventSource> implements ResourceEventHandler { - public static String PREVIOUS_ANNOTATION_KEY = "javaoperatorsdk.io/previous"; - private static final Logger log = LoggerFactory.getLogger(InformerEventSource.class); - + public static final String PREVIOUS_ANNOTATION_KEY = "javaoperatorsdk.io/previous"; // we need direct control for the indexer to propagate the just update resource also to the index private final PrimaryToSecondaryIndex primaryToSecondaryIndex; private final PrimaryToSecondaryMapper

primaryToSecondaryMapper; private final String id = UUID.randomUUID().toString(); public InformerEventSource( - InformerConfiguration configuration, EventSourceContext

context) { - this(configuration, context.getClient(), + InformerEventSourceConfiguration configuration, EventSourceContext

context) { + this(configuration, + configuration.getKubernetesClient().orElse(context.getClient()), context.getControllerConfiguration().getConfigurationService() .parseResourceVersionsForEventFilteringAndCaching()); } - public InformerEventSource(InformerConfiguration configuration, KubernetesClient client) { + InformerEventSource(InformerEventSourceConfiguration configuration, KubernetesClient client) { this(configuration, client, false); } - public InformerEventSource(InformerConfiguration configuration, KubernetesClient client, + @SuppressWarnings({"unchecked", "rawtypes"}) + private InformerEventSource(InformerEventSourceConfiguration configuration, + KubernetesClient client, boolean parseResourceVersions) { - super( + super(configuration.name(), configuration.getGroupVersionKind() .map(gvk -> client.genericKubernetesResources(gvk.apiVersion(), gvk.getKind())) .orElseGet(() -> (MixedOperation) client.resources(configuration.getResourceClass())), @@ -104,10 +107,11 @@ public InformerEventSource(InformerConfiguration configuration, KubernetesCli primaryToSecondaryIndex = NOOPPrimaryToSecondaryIndex.getInstance(); } - onAddFilter = configuration.onAddFilter().orElse(null); - onUpdateFilter = configuration.onUpdateFilter().orElse(null); - onDeleteFilter = configuration.onDeleteFilter().orElse(null); - genericFilter = configuration.genericFilter().orElse(null); + final var informerConfig = configuration.getInformerConfig(); + onAddFilter = informerConfig.getOnAddFilter(); + onUpdateFilter = informerConfig.getOnUpdateFilter(); + onDeleteFilter = informerConfig.getOnDeleteFilter(); + genericFilter = informerConfig.getGenericFilter(); } @Override @@ -247,18 +251,6 @@ public Set getSecondaryResources(P primary) { .collect(Collectors.toSet()); } - /** - * Returns the configuration object for the informer. - * - * @return the informer configuration object - * - * @deprecated Use {@link #configuration()} instead - */ - @Deprecated(forRemoval = true) - public InformerConfiguration getConfiguration() { - return configuration(); - } - @Override public synchronized void handleRecentResourceUpdate(ResourceID resourceID, R resource, R previousVersionOfResource) { @@ -296,10 +288,6 @@ private boolean eventAcceptedByFilter(Operation operation, R newObject, R oldObj } } - private enum Operation { - ADD, UPDATE - } - private boolean acceptedByDeleteFilters(R resource, boolean b) { return (onDeleteFilter == null || onDeleteFilter.accept(resource, b)) && (genericFilter == null || genericFilter.accept(resource)); @@ -317,4 +305,7 @@ public R addPreviousAnnotation(String resourceVersion, R target) { return target; } + private enum Operation { + ADD, UPDATE + } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerManager.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerManager.java index e68cd3ab25..57bbf2a8ce 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerManager.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerManager.java @@ -18,8 +18,9 @@ import io.fabric8.kubernetes.client.informers.ResourceEventHandler; import io.javaoperatorsdk.operator.OperatorException; import io.javaoperatorsdk.operator.ReconcilerUtils; -import io.javaoperatorsdk.operator.api.config.ConfigurationService; -import io.javaoperatorsdk.operator.api.config.ResourceConfiguration; +import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.config.Informable; +import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; import io.javaoperatorsdk.operator.health.InformerHealthIndicator; import io.javaoperatorsdk.operator.processing.LifecycleAware; import io.javaoperatorsdk.operator.processing.event.ResourceID; @@ -28,50 +29,52 @@ import static io.javaoperatorsdk.operator.api.reconciler.Constants.WATCH_ALL_NAMESPACES; -public class InformerManager> - implements LifecycleAware, IndexerResourceCache { +class InformerManager> + implements LifecycleAware, IndexerResourceCache { private static final Logger log = LoggerFactory.getLogger(InformerManager.class); - private final Map> sources = new ConcurrentHashMap<>(); + private final Map> sources = new ConcurrentHashMap<>(); private final C configuration; - private final MixedOperation, Resource> client; - private final ResourceEventHandler eventHandler; - private final Map>> indexers = new HashMap<>(); - private ConfigurationService configurationService; + private final MixedOperation, Resource> client; + private final ResourceEventHandler eventHandler; + private final Map>> indexers = new HashMap<>(); + private ControllerConfiguration controllerConfiguration; - InformerManager(MixedOperation, Resource> client, + InformerManager(MixedOperation, Resource> client, C configuration, - ResourceEventHandler eventHandler) { + ResourceEventHandler eventHandler) { this.client = client; this.configuration = configuration; this.eventHandler = eventHandler; } - void setConfigurationService(ConfigurationService configurationService) { - this.configurationService = configurationService; + void setControllerConfiguration(ControllerConfiguration controllerConfiguration) { + this.controllerConfiguration = controllerConfiguration; } @Override public void start() throws OperatorException { initSources(); // make sure informers are all started before proceeding further - configurationService.getExecutorServiceManager().boundedExecuteAndWaitForAllToComplete( - sources.values().stream(), - iw -> { - iw.start(); - return null; - }, - iw -> "InformerStarter-" + iw.getTargetNamespace() + "-" - + configuration.getResourceClass().getSimpleName()); + controllerConfiguration.getConfigurationService().getExecutorServiceManager() + .boundedExecuteAndWaitForAllToComplete( + sources.values().stream(), + iw -> { + iw.start(); + return null; + }, + iw -> "InformerStarter-" + iw.getTargetNamespace() + "-" + + configuration.getResourceClass().getSimpleName()); } private void initSources() { if (!sources.isEmpty()) { throw new IllegalStateException("Some sources already initialized."); } - final var targetNamespaces = configuration.getEffectiveNamespaces(configurationService); - if (ResourceConfiguration.allNamespacesWatched(targetNamespaces)) { + final var targetNamespaces = + configuration.getInformerConfig().getEffectiveNamespaces(controllerConfiguration); + if (InformerConfiguration.allNamespacesWatched(targetNamespaces)) { var source = createEventSourceForNamespace(WATCH_ALL_NAMESPACES); log.debug("Registered {} -> {} for any namespace", this, source); } else { @@ -96,7 +99,7 @@ public void changeNamespaces(Set namespaces) { namespaces.forEach(ns -> { if (!sources.containsKey(ns)) { - final InformerWrapper source = createEventSourceForNamespace(ns); + final InformerWrapper source = createEventSourceForNamespace(ns); source.start(); log.debug("Registered new {} -> {} for namespace: {}", this, source, ns); @@ -105,28 +108,32 @@ public void changeNamespaces(Set namespaces) { } - private InformerWrapper createEventSourceForNamespace(String namespace) { - final InformerWrapper source; + private InformerWrapper createEventSourceForNamespace(String namespace) { + final InformerWrapper source; + final var labelSelector = configuration.getInformerConfig().getLabelSelector(); if (namespace.equals(WATCH_ALL_NAMESPACES)) { final var filteredBySelectorClient = - client.inAnyNamespace().withLabelSelector(configuration.getLabelSelector()); + client.inAnyNamespace().withLabelSelector(labelSelector); source = createEventSource(filteredBySelectorClient, eventHandler, WATCH_ALL_NAMESPACES); } else { source = createEventSource( - client.inNamespace(namespace).withLabelSelector(configuration.getLabelSelector()), + client.inNamespace(namespace).withLabelSelector(labelSelector), eventHandler, namespace); } source.addIndexers(indexers); return source; } - private InformerWrapper createEventSource( - FilterWatchListDeletable, Resource> filteredBySelectorClient, - ResourceEventHandler eventHandler, String namespaceIdentifier) { - var informer = configuration.getInformerListLimit().map(filteredBySelectorClient::withLimit) + private InformerWrapper createEventSource( + FilterWatchListDeletable, Resource> filteredBySelectorClient, + ResourceEventHandler eventHandler, String namespaceIdentifier) { + final var informerConfig = configuration.getInformerConfig(); + var informer = Optional.ofNullable(informerConfig.getInformerListLimit()) + .map(filteredBySelectorClient::withLimit) .orElse(filteredBySelectorClient).runnableInformer(0); - configuration.getItemStore().ifPresent(informer::itemStore); - var source = new InformerWrapper<>(informer, configurationService, namespaceIdentifier); + Optional.ofNullable(informerConfig.getItemStore()).ifPresent(informer::itemStore); + var source = new InformerWrapper<>(informer, controllerConfiguration.getConfigurationService(), + namespaceIdentifier); source.addEventHandler(eventHandler); sources.put(namespaceIdentifier, source); return source; @@ -146,7 +153,7 @@ public void stop() { } @Override - public Stream list(Predicate predicate) { + public Stream list(Predicate predicate) { if (predicate == null) { return sources.values().stream().flatMap(IndexerResourceCache::list); } @@ -154,7 +161,7 @@ public Stream list(Predicate predicate) { } @Override - public Stream list(String namespace, Predicate predicate) { + public Stream list(String namespace, Predicate predicate) { if (isWatchingAllNamespaces()) { return getSource(WATCH_ALL_NAMESPACES) .map(source -> source.list(namespace, predicate)) @@ -167,10 +174,13 @@ public Stream list(String namespace, Predicate predicate) { } @Override - public Optional get(ResourceID resourceID) { + public Optional get(ResourceID resourceID) { return getSource(resourceID.getNamespace().orElse(WATCH_ALL_NAMESPACES)) .flatMap(source -> source.get(resourceID)) - .map(r -> configurationService.getResourceCloner().clone(r)); + .map(r -> controllerConfiguration.getConfigurationService() + .cloneSecondaryResourcesWhenGettingFromCache() + ? controllerConfiguration.getConfigurationService().getResourceCloner().clone(r) + : r); } @Override @@ -182,29 +192,30 @@ private boolean isWatchingAllNamespaces() { return sources.containsKey(WATCH_ALL_NAMESPACES); } - private Optional> getSource(String namespace) { + private Optional> getSource(String namespace) { namespace = isWatchingAllNamespaces() || namespace == null ? WATCH_ALL_NAMESPACES : namespace; return Optional.ofNullable(sources.get(namespace)); } @Override - public void addIndexers(Map>> indexers) { + public void addIndexers(Map>> indexers) { this.indexers.putAll(indexers); } @Override - public List byIndex(String indexName, String indexKey) { + public List byIndex(String indexName, String indexKey) { return sources.values().stream().map(s -> s.byIndex(indexName, indexKey)) .flatMap(List::stream).collect(Collectors.toList()); } @Override public String toString() { - final var selector = configuration.getLabelSelector(); + final var informerConfig = configuration.getInformerConfig(); + final var selector = informerConfig.getLabelSelector(); return "InformerManager [" + ReconcilerUtils.getResourceTypeNameWithVersion(configuration.getResourceClass()) + "] watching: " - + configuration.getEffectiveNamespaces(configurationService) + + informerConfig.getEffectiveNamespaces(controllerConfiguration) + (selector != null ? " selector: " + selector : ""); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSource.java index 7139395e76..f5e899826d 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/ManagedInformerEventSource.java @@ -1,6 +1,10 @@ package io.javaoperatorsdk.operator.processing.event.source.informer; -import java.util.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; @@ -12,21 +16,19 @@ import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.informers.ResourceEventHandler; import io.javaoperatorsdk.operator.OperatorException; -import io.javaoperatorsdk.operator.api.config.ConfigurationService; +import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.config.Informable; import io.javaoperatorsdk.operator.api.config.NamespaceChangeable; -import io.javaoperatorsdk.operator.api.config.ResourceConfiguration; import io.javaoperatorsdk.operator.api.reconciler.dependent.RecentOperationCacheFiller; import io.javaoperatorsdk.operator.health.InformerHealthIndicator; import io.javaoperatorsdk.operator.health.InformerWrappingEventSourceHealthIndicator; import io.javaoperatorsdk.operator.health.Status; import io.javaoperatorsdk.operator.processing.event.ResourceID; -import io.javaoperatorsdk.operator.processing.event.source.AbstractResourceEventSource; -import io.javaoperatorsdk.operator.processing.event.source.Cache; -import io.javaoperatorsdk.operator.processing.event.source.Configurable; -import io.javaoperatorsdk.operator.processing.event.source.IndexerResourceCache; +import io.javaoperatorsdk.operator.processing.event.source.*; -public abstract class ManagedInformerEventSource> - extends AbstractResourceEventSource +@SuppressWarnings("rawtypes") +public abstract class ManagedInformerEventSource> + extends AbstractEventSource implements ResourceEventHandler, Cache, IndexerResourceCache, RecentOperationCacheFiller, NamespaceChangeable, InformerWrappingEventSourceHealthIndicator, Configurable { @@ -34,16 +36,16 @@ public abstract class ManagedInformerEventSource cache; private final boolean parseResourceVersions; - private ConfigurationService configurationService; + private ControllerConfiguration controllerConfiguration; private final C configuration; - private Map>> indexers = new HashMap<>(); + private final Map>> indexers = new HashMap<>(); protected TemporaryResourceCache temporaryResourceCache; protected MixedOperation client; - protected ManagedInformerEventSource( + protected ManagedInformerEventSource(String name, MixedOperation client, C configuration, boolean parseResourceVersions) { - super(configuration.getResourceClass()); + super(configuration.getResourceClass(), name); this.parseResourceVersions = parseResourceVersions; this.client = client; this.configuration = configuration; @@ -75,6 +77,7 @@ public void changeNamespaces(Set namespaces) { } } + @SuppressWarnings("unchecked") @Override public synchronized void start() { if (isRunning()) { @@ -82,7 +85,7 @@ public synchronized void start() { } temporaryResourceCache = new TemporaryResourceCache<>(this, parseResourceVersions); this.cache = new InformerManager<>(client, configuration, this); - cache.setConfigurationService(configurationService); + cache.setControllerConfiguration(controllerConfiguration); cache.addIndexers(indexers); manager().start(); super.start(); @@ -124,6 +127,7 @@ public Optional get(ResourceID resourceID) { } } + @SuppressWarnings("unused") public Optional getCachedValue(ResourceID resourceID) { return get(resourceID); } @@ -170,11 +174,6 @@ public Status getStatus() { return InformerWrappingEventSourceHealthIndicator.super.getStatus(); } - @Override - public ResourceConfiguration getInformerConfiguration() { - return configuration(); - } - @Override public C configuration() { return configuration; @@ -187,7 +186,8 @@ public String toString() { "}"; } - public void setConfigurationService(ConfigurationService configurationService) { - this.configurationService = configurationService; + public void setControllerConfiguration(ControllerConfiguration controllerConfiguration) { + this.controllerConfiguration = controllerConfiguration; } + } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/Mappers.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/Mappers.java index 65f9c86cb8..bc83730592 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/Mappers.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/Mappers.java @@ -5,6 +5,7 @@ import java.util.stream.Collectors; import io.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.processing.GroupVersionKind; import io.javaoperatorsdk.operator.processing.event.ResourceID; import io.javaoperatorsdk.operator.processing.event.source.SecondaryToPrimaryMapper; @@ -13,59 +14,82 @@ public class Mappers { public static final String DEFAULT_ANNOTATION_FOR_NAME = "io.javaoperatorsdk/primary-name"; public static final String DEFAULT_ANNOTATION_FOR_NAMESPACE = "io.javaoperatorsdk/primary-namespace"; + public static final String DEFAULT_ANNOTATION_FOR_PRIMARY_TYPE = + "io.javaoperatorsdk/primary-type"; private Mappers() {} public static SecondaryToPrimaryMapper fromAnnotation( - String nameKey) { - return fromMetadata(nameKey, null, false); + String nameKey, String typeKey, Class primaryResourceType) { + return fromMetadata(nameKey, null, typeKey, primaryResourceType, false); } @SuppressWarnings("unused") public static SecondaryToPrimaryMapper fromAnnotation( - String nameKey, String namespaceKey) { - return fromMetadata(nameKey, namespaceKey, false); + String nameKey, String namespaceKey, String typeKey, + Class primaryResourceType) { + return fromMetadata(nameKey, namespaceKey, typeKey, primaryResourceType, false); } @SuppressWarnings("unused") - public static SecondaryToPrimaryMapper fromLabel(String nameKey) { - return fromMetadata(nameKey, null, true); + public static SecondaryToPrimaryMapper fromLabel(String nameKey, + String typeKey, + Class primaryResourceType) { + return fromMetadata(nameKey, null, typeKey, primaryResourceType, true); } - public static SecondaryToPrimaryMapper fromDefaultAnnotations() { - return fromMetadata(DEFAULT_ANNOTATION_FOR_NAME, DEFAULT_ANNOTATION_FOR_NAMESPACE, false); + public static SecondaryToPrimaryMapper fromDefaultAnnotations( + Class primaryResourceType) { + return fromMetadata(DEFAULT_ANNOTATION_FOR_NAME, DEFAULT_ANNOTATION_FOR_NAMESPACE, + DEFAULT_ANNOTATION_FOR_PRIMARY_TYPE, + primaryResourceType, false); } @SuppressWarnings("unused") public static SecondaryToPrimaryMapper fromLabel( - String nameKey, String namespaceKey) { - return fromMetadata(nameKey, namespaceKey, true); + String nameKey, String namespaceKey, String typeKey, + Class primaryResourceType) { + return fromMetadata(nameKey, namespaceKey, typeKey, primaryResourceType, true); } - public static SecondaryToPrimaryMapper fromOwnerReference() { - return fromOwnerReference(false); + public static SecondaryToPrimaryMapper fromOwnerReferences( + Class primaryResourceType) { + return fromOwnerReferences(primaryResourceType, false); } - /** - * @param clusterScope if the owner is a cluster scoped resource - * @return mapper - * @param type of the secondary resource, where the owner reference is - */ - public static SecondaryToPrimaryMapper fromOwnerReference( - boolean clusterScope) { - return resource -> ResourceID.fromFirstOwnerReference(resource, clusterScope).map(Set::of) - .orElseGet(Collections::emptySet); + public static SecondaryToPrimaryMapper fromOwnerReferences( + Class primaryResourceType, boolean clusterScoped) { + return fromOwnerReferences(HasMetadata.getApiVersion(primaryResourceType), + HasMetadata.getKind(primaryResourceType), + clusterScoped); + } + + public static SecondaryToPrimaryMapper fromOwnerReferences( + HasMetadata primaryResource) { + return fromOwnerReferences(primaryResource, false); + } + + public static SecondaryToPrimaryMapper fromOwnerReferences( + HasMetadata primaryResource, + boolean clusterScoped) { + return fromOwnerReferences(primaryResource.getApiVersion(), primaryResource.getKind(), + clusterScoped); } public static SecondaryToPrimaryMapper fromOwnerReferences( + String apiVersion, String kind, boolean clusterScope) { - return resource -> resource.getMetadata().getOwnerReferences().stream() + return resource -> resource.getMetadata().getOwnerReferences() + .stream() + .filter(r -> r.getKind().equals(kind) + && r.getApiVersion().equals(apiVersion)) .map(or -> ResourceID.fromOwnerReference(resource, or, clusterScope)) .collect(Collectors.toSet()); } private static SecondaryToPrimaryMapper fromMetadata( - String nameKey, String namespaceKey, boolean isLabel) { + String nameKey, String namespaceKey, String typeKey, + Class primaryResourceType, boolean isLabel) { return resource -> { final var metadata = resource.getMetadata(); if (metadata == null) { @@ -81,6 +105,15 @@ private static SecondaryToPrimaryMapper fromMetadata( } var namespace = namespaceKey == null ? resource.getMetadata().getNamespace() : map.get(namespaceKey); + + String gvkSimple = map.get(typeKey); + + if (gvkSimple != null && + !GroupVersionKind.fromString(gvkSimple) + .equals(GroupVersionKind.gvkFor(primaryResourceType))) { + return Set.of(); + } + return Set.of(new ResourceID(name, namespace)); } }; @@ -123,4 +156,21 @@ public static SecondaryToPrim .collect(Collectors.toSet()); }; } + + public static class SecondaryToPrimaryFromDefaultAnnotation + implements SecondaryToPrimaryMapper { + + private Class primaryResourceType; + + public SecondaryToPrimaryFromDefaultAnnotation( + Class primaryResourceType) { + this.primaryResourceType = primaryResourceType; + } + + @Override + public Set toPrimaryResourceIDs(HasMetadata resource) { + return Mappers.fromDefaultAnnotations(primaryResourceType).toPrimaryResourceIDs(resource); + } + } + } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/TemporaryResourceCache.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/TemporaryResourceCache.java index b905629e69..07c9e0a6cc 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/TemporaryResourceCache.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/informer/TemporaryResourceCache.java @@ -9,7 +9,7 @@ import org.slf4j.LoggerFactory; import io.fabric8.kubernetes.api.model.HasMetadata; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; import io.javaoperatorsdk.operator.processing.event.ResourceID; @@ -161,9 +161,9 @@ public synchronized boolean isKnownResourceVersion(T resource) { } /** - * @return true if {@link InformerConfiguration#parseResourceVersions()} is enabled and the - * resourceVersion of newResource is numerically greater than cachedResource, otherwise - * false + * @return true if {@link InformerEventSourceConfiguration#parseResourceVersions()} is enabled and + * the resourceVersion of newResource is numerically greater than cachedResource, + * otherwise false */ private boolean isLaterResourceVersion(ResourceID resourceId, T newResource, T cachedResource) { try { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingConfiguration.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingConfiguration.java new file mode 100644 index 0000000000..52e1fbcd68 --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingConfiguration.java @@ -0,0 +1,33 @@ +package io.javaoperatorsdk.operator.processing.event.source.polling; + +import java.time.Duration; +import java.util.Objects; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.function.Predicate; + +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.processing.event.source.CacheKeyMapper; + +public record PerResourcePollingConfiguration(String name,ScheduledExecutorService executorService, CacheKeyMapper cacheKeyMapper, + PerResourcePollingEventSource.ResourceFetcher resourceFetcher, + Predicate

registerPredicate, Duration defaultPollingPeriod) { + + public static final int DEFAULT_EXECUTOR_THREAD_NUMBER = 1; + + public PerResourcePollingConfiguration( + String name, + ScheduledExecutorService executorService, + CacheKeyMapper cacheKeyMapper, + PerResourcePollingEventSource.ResourceFetcher resourceFetcher, + Predicate

registerPredicate, + Duration defaultPollingPeriod) { + this.name = name; + this.executorService = executorService == null ? new ScheduledThreadPoolExecutor(DEFAULT_EXECUTOR_THREAD_NUMBER) + : executorService; + this.cacheKeyMapper = cacheKeyMapper == null ? CacheKeyMapper.singleResourceCacheKeyMapper() : cacheKeyMapper; + this.resourceFetcher = Objects.requireNonNull(resourceFetcher); + this.registerPredicate = registerPredicate; + this.defaultPollingPeriod = defaultPollingPeriod; + } +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingConfigurationBuilder.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingConfigurationBuilder.java new file mode 100644 index 0000000000..85b1fcf2b0 --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingConfigurationBuilder.java @@ -0,0 +1,55 @@ +package io.javaoperatorsdk.operator.processing.event.source.polling; + +import java.time.Duration; +import java.util.concurrent.ScheduledExecutorService; +import java.util.function.Predicate; + +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.processing.event.source.CacheKeyMapper; + +public final class PerResourcePollingConfigurationBuilder { + + private final Duration defaultPollingPeriod; + private final PerResourcePollingEventSource.ResourceFetcher resourceFetcher; + + private String name; + private Predicate

registerPredicate; + private ScheduledExecutorService executorService; + private CacheKeyMapper cacheKeyMapper; + + public PerResourcePollingConfigurationBuilder( + PerResourcePollingEventSource.ResourceFetcher resourceFetcher, + Duration defaultPollingPeriod) { + this.resourceFetcher = resourceFetcher; + this.defaultPollingPeriod = defaultPollingPeriod; + } + + @SuppressWarnings("unused") + public PerResourcePollingConfigurationBuilder withExecutorService( + ScheduledExecutorService executorService) { + this.executorService = executorService; + return this; + } + + public PerResourcePollingConfigurationBuilder withRegisterPredicate( + Predicate

registerPredicate) { + this.registerPredicate = registerPredicate; + return this; + } + + public PerResourcePollingConfigurationBuilder withCacheKeyMapper( + CacheKeyMapper cacheKeyMapper) { + this.cacheKeyMapper = cacheKeyMapper; + return this; + } + + public PerResourcePollingConfigurationBuilder withName(String name) { + this.name = name; + return this; + } + + public PerResourcePollingConfiguration build() { + return new PerResourcePollingConfiguration<>(name, executorService, cacheKeyMapper, + resourceFetcher, registerPredicate, defaultPollingPeriod); + } +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSource.java index 6da1ec0e58..983679a27a 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSource.java @@ -9,7 +9,6 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; @@ -21,10 +20,10 @@ import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; import io.javaoperatorsdk.operator.processing.event.ResourceID; import io.javaoperatorsdk.operator.processing.event.source.Cache; -import io.javaoperatorsdk.operator.processing.event.source.CacheKeyMapper; import io.javaoperatorsdk.operator.processing.event.source.ExternalResourceCachingEventSource; import io.javaoperatorsdk.operator.processing.event.source.ResourceEventAware; + /** * * Polls the supplier for each controlled resource registered. Resource is registered when created @@ -42,138 +41,26 @@ public class PerResourcePollingEventSource private static final Logger log = LoggerFactory.getLogger(PerResourcePollingEventSource.class); - public static final int DEFAULT_EXECUTOR_THREAD_NUMBER = 1; + private final Map> scheduledFutures = new ConcurrentHashMap<>(); + private final Cache

primaryResourceCache; + private final Set fetchedForPrimaries = ConcurrentHashMap.newKeySet(); private final ScheduledExecutorService executorService; - private final Map> scheduledFutures = new ConcurrentHashMap<>(); private final ResourceFetcher resourceFetcher; - private final Cache

resourceCache; private final Predicate

registerPredicate; - private final long period; - private final Set fetchedForPrimaries = ConcurrentHashMap.newKeySet(); - - public PerResourcePollingEventSource(ResourceFetcher resourceFetcher, - EventSourceContext

context, Duration defaultPollingPeriod, - Class resourceClass) { - this(resourceFetcher, context.getPrimaryCache(), defaultPollingPeriod.toMillis(), - null, resourceClass, - CacheKeyMapper.singleResourceCacheKeyMapper()); - } - - /** - * @deprecated use the variant which uses {@link EventSourceContext} instead of {@link Cache} and - * {@link Duration} for period parameter as it provides a more intuitive API. - * - * @param resourceFetcher fetches resource related to a primary resource - * @param resourceCache cache of the primary resource - * @param period default polling period - * @param resourceClass class of the target resource - */ - @Deprecated(forRemoval = true) - public PerResourcePollingEventSource(ResourceFetcher resourceFetcher, - Cache

resourceCache, long period, Class resourceClass) { - this(resourceFetcher, resourceCache, period, null, resourceClass, - CacheKeyMapper.singleResourceCacheKeyMapper()); - } + private final Duration period; - public PerResourcePollingEventSource(ResourceFetcher resourceFetcher, - EventSourceContext

context, - Duration defaultPollingPeriod, - Class resourceClass, - CacheKeyMapper cacheKeyMapper) { - this(resourceFetcher, context.getPrimaryCache(), defaultPollingPeriod.toMillis(), - null, resourceClass, cacheKeyMapper); - } - /** - * @deprecated use the variant which uses {@link EventSourceContext} instead of {@link Cache} and - * {@link Duration} for period parameter as it provides a more intuitive API. - * - * @param resourceFetcher fetches resource related to a primary resource - * @param resourceCache cache of the primary resource - * @param period default polling period - * @param resourceClass class of the target resource - * @param cacheKeyMapper use to distinguish resource in case more resources are handled for a - * single primary resource - */ - @Deprecated(forRemoval = true) - public PerResourcePollingEventSource(ResourceFetcher resourceFetcher, - Cache

resourceCache, long period, Class resourceClass, - CacheKeyMapper cacheKeyMapper) { - this(resourceFetcher, resourceCache, period, null, resourceClass, cacheKeyMapper); - } - public PerResourcePollingEventSource(ResourceFetcher resourceFetcher, + public PerResourcePollingEventSource(Class resourceClass, EventSourceContext

context, - Duration defaultPollingPeriod, - Predicate

registerPredicate, - Class resourceClass, - CacheKeyMapper cacheKeyMapper) { - this(resourceFetcher, context.getPrimaryCache(), defaultPollingPeriod.toMillis(), - registerPredicate, resourceClass, cacheKeyMapper, - new ScheduledThreadPoolExecutor(DEFAULT_EXECUTOR_THREAD_NUMBER)); - } - - /** - * @deprecated use the variant which uses {@link EventSourceContext} instead of {@link Cache} and - * {@link Duration} for period parameter as it provides a more intuitive API. - * - * @param resourceFetcher fetches resource related to a primary resource - * @param resourceCache cache of the primary resource - * @param period default polling period - * @param resourceClass class of the target resource - * @param cacheKeyMapper use to distinguish resource in case more resources are handled for a - * single primary resource - * @param registerPredicate used to determine if the related resource for a custom resource should - * be polled or not. - */ - @Deprecated(forRemoval = true) - public PerResourcePollingEventSource(ResourceFetcher resourceFetcher, - Cache

resourceCache, long period, - Predicate

registerPredicate, Class resourceClass, - CacheKeyMapper cacheKeyMapper) { - this(resourceFetcher, resourceCache, period, registerPredicate, resourceClass, cacheKeyMapper, - new ScheduledThreadPoolExecutor(DEFAULT_EXECUTOR_THREAD_NUMBER)); - } - - - public PerResourcePollingEventSource( - ResourceFetcher resourceFetcher, - EventSourceContext

context, Duration defaultPollingPeriod, - Predicate

registerPredicate, Class resourceClass, - CacheKeyMapper cacheKeyMapper, ScheduledExecutorService executorService) { - this(resourceFetcher, context.getPrimaryCache(), defaultPollingPeriod.toMillis(), - registerPredicate, - resourceClass, cacheKeyMapper, executorService); - } - - /** - * @deprecated use the variant which uses {@link EventSourceContext} instead of {@link Cache} and - * {@link Duration} for period parameter as it provides a more intuitive API. - * - * @param resourceFetcher fetches resource related to a primary resource - * @param resourceCache cache of the primary resource - * @param period default polling period - * @param resourceClass class of the target resource - * @param cacheKeyMapper use to distinguish resource in case more resources are handled for a - * single primary resource - * @param registerPredicate used to determine if the related resource for a custom resource should - * be polled or not. - * @param executorService custom executor service - */ - - @Deprecated(forRemoval = true) - public PerResourcePollingEventSource( - ResourceFetcher resourceFetcher, - Cache

resourceCache, long period, - Predicate

registerPredicate, Class resourceClass, - CacheKeyMapper cacheKeyMapper, ScheduledExecutorService executorService) { - super(resourceClass, cacheKeyMapper); - this.resourceFetcher = resourceFetcher; - this.resourceCache = resourceCache; - this.period = period; - this.registerPredicate = registerPredicate; - this.executorService = executorService; + PerResourcePollingConfiguration config) { + super(config.name(), resourceClass, config.cacheKeyMapper()); + this.primaryResourceCache = context.getPrimaryCache(); + this.resourceFetcher = config.resourceFetcher(); + this.registerPredicate = config.registerPredicate(); + this.executorService = config.executorService(); + this.period = config.defaultPollingPeriod(); } private Set getAndCacheResource(P primary, boolean fromGetter) { @@ -187,7 +74,7 @@ private Set getAndCacheResource(P primary, boolean fromGetter) { private void scheduleNextExecution(P primary, Set actualResources) { var primaryID = ResourceID.fromResource(primary); var fetchDelay = resourceFetcher.fetchDelay(actualResources, primary); - var fetchDuration = fetchDelay.orElse(Duration.ofMillis(period)); + var fetchDuration = fetchDelay.orElse(period); ScheduledFuture scheduledFuture = (ScheduledFuture) executorService .schedule(new FetchingExecutor(primaryID), fetchDuration.toMillis(), TimeUnit.MILLISECONDS); @@ -246,7 +133,7 @@ public void run() { return; } // always use up-to-date resource from cache - var primary = resourceCache.get(primaryID); + var primary = primaryResourceCache.get(primaryID); if (primary.isEmpty()) { log.warn("No resource in cache for resource ID: {}", primaryID); // no new execution is scheduled in this case, an on delete event should be received shortly diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingConfiguration.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingConfiguration.java new file mode 100644 index 0000000000..c66ef38c8f --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingConfiguration.java @@ -0,0 +1,19 @@ +package io.javaoperatorsdk.operator.processing.event.source.polling; + +import java.time.Duration; +import java.util.Objects; + +import io.javaoperatorsdk.operator.processing.event.source.CacheKeyMapper; + +public record PollingConfiguration(String name,PollingEventSource.GenericResourceFetcher genericResourceFetcher, + Duration period, CacheKeyMapper cacheKeyMapper) { + + public PollingConfiguration(String name,PollingEventSource.GenericResourceFetcher genericResourceFetcher, Duration period, + CacheKeyMapper cacheKeyMapper) { + this.name = name; + this.genericResourceFetcher = Objects.requireNonNull(genericResourceFetcher); + this.period = period; + this.cacheKeyMapper = + cacheKeyMapper == null ? CacheKeyMapper.singleResourceCacheKeyMapper() : cacheKeyMapper; + } +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingConfigurationBuilder.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingConfigurationBuilder.java new file mode 100644 index 0000000000..c6bccefa82 --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingConfigurationBuilder.java @@ -0,0 +1,32 @@ +package io.javaoperatorsdk.operator.processing.event.source.polling; + +import java.time.Duration; + +import io.javaoperatorsdk.operator.processing.event.source.CacheKeyMapper; + +public final class PollingConfigurationBuilder { + private final Duration period; + private final PollingEventSource.GenericResourceFetcher genericResourceFetcher; + private CacheKeyMapper cacheKeyMapper; + private String name; + + public PollingConfigurationBuilder(PollingEventSource.GenericResourceFetcher fetcher, + Duration period) { + this.genericResourceFetcher = fetcher; + this.period = period; + } + + public PollingConfigurationBuilder withCacheKeyMapper(CacheKeyMapper cacheKeyMapper) { + this.cacheKeyMapper = cacheKeyMapper; + return this; + } + + public PollingConfigurationBuilder withName(String name) { + this.name = name; + return this; + } + + public PollingConfiguration build() { + return new PollingConfiguration<>(name, genericResourceFetcher, period, cacheKeyMapper); + } +} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSource.java index 9ef889ecb6..6549030c4b 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSource.java @@ -1,6 +1,10 @@ package io.javaoperatorsdk.operator.processing.event.source.polling; -import java.util.*; +import java.time.Duration; +import java.util.Map; +import java.util.Set; +import java.util.Timer; +import java.util.TimerTask; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; @@ -10,7 +14,6 @@ import io.javaoperatorsdk.operator.OperatorException; import io.javaoperatorsdk.operator.health.Status; import io.javaoperatorsdk.operator.processing.event.ResourceID; -import io.javaoperatorsdk.operator.processing.event.source.CacheKeyMapper; import io.javaoperatorsdk.operator.processing.event.source.ExternalResourceCachingEventSource; /** @@ -46,26 +49,15 @@ public class PollingEventSource private final Timer timer = new Timer(); private final GenericResourceFetcher genericResourceFetcher; - private final long period; + private final Duration period; private final AtomicBoolean healthy = new AtomicBoolean(true); - public PollingEventSource( - GenericResourceFetcher supplier, - long period, - Class resourceClass) { - super(resourceClass, CacheKeyMapper.singleResourceCacheKeyMapper()); - this.genericResourceFetcher = supplier; - this.period = period; - } - public PollingEventSource( - GenericResourceFetcher supplier, - long period, - Class resourceClass, - CacheKeyMapper cacheKeyMapper) { - super(resourceClass, cacheKeyMapper); - this.genericResourceFetcher = supplier; - this.period = period; + + public PollingEventSource(Class resourceClass, PollingConfiguration config) { + super(config.name(), resourceClass, config.cacheKeyMapper()); + this.genericResourceFetcher = config.genericResourceFetcher(); + this.period = config.period(); } @Override @@ -89,8 +81,8 @@ public void run() { } } }, - period, - period); + period.toMillis(), + period.toMillis()); } protected synchronized void getStateAndFillCache() { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/timer/TimerEventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/timer/TimerEventSource.java index fe641e0b0b..b909083a00 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/timer/TimerEventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/source/timer/TimerEventSource.java @@ -1,6 +1,7 @@ package io.javaoperatorsdk.operator.processing.event.source.timer; import java.util.Map; +import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; @@ -15,13 +16,21 @@ import io.javaoperatorsdk.operator.processing.event.source.ResourceEventAware; public class TimerEventSource - extends AbstractEventSource + extends AbstractEventSource implements ResourceEventAware { private static final Logger log = LoggerFactory.getLogger(TimerEventSource.class); private Timer timer; private final Map onceTasks = new ConcurrentHashMap<>(); + public TimerEventSource() { + super(Void.class); + } + + public TimerEventSource(String name) { + super(Void.class, name); + } + @SuppressWarnings("unused") public void scheduleOnce(R resource, long delay) { scheduleOnce(ResourceID.fromResource(resource), delay); @@ -69,6 +78,11 @@ public void stop() { } } + @Override + public Set getSecondaryResources(HasMetadata primary) { + return Set.of(); + } + public class EventProducerTimeTask extends TimerTask { protected final ResourceID customResourceUid; diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/retry/GenericRetry.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/retry/GenericRetry.java index 9d5a83dc51..d1809de566 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/retry/GenericRetry.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/retry/GenericRetry.java @@ -1,7 +1,6 @@ package io.javaoperatorsdk.operator.processing.retry; import io.javaoperatorsdk.operator.api.config.AnnotationConfigurable; -import io.javaoperatorsdk.operator.api.config.RetryConfiguration; public class GenericRetry implements Retry, AnnotationConfigurable { private int maxAttempts = GradualRetry.DEFAULT_MAX_ATTEMPTS; @@ -19,23 +18,6 @@ public static GenericRetry noRetry() { return new GenericRetry().setMaxAttempts(0); } - /** - * @deprecated Use the {@link GradualRetry} annotation instead - * - * @param configuration retry config - * @return Retry instance - */ - @Deprecated(forRemoval = true) - public static Retry fromConfiguration(RetryConfiguration configuration) { - return configuration == null ? defaultLimitedExponentialRetry() - : new GenericRetry() - .setInitialInterval(configuration.getInitialInterval()) - .setMaxAttempts(configuration.getMaxAttempts()) - .setIntervalMultiplier(configuration.getIntervalMultiplier()) - .setMaxInterval(configuration.getMaxInterval()); - } - - public static GenericRetry every10second10TimesRetry() { return new GenericRetry().withLinearRetry().setMaxAttempts(10).setInitialInterval(10000); } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/MockKubernetesClient.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/MockKubernetesClient.java index c9bff4a3d6..31fec8b924 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/MockKubernetesClient.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/MockKubernetesClient.java @@ -1,6 +1,6 @@ package io.javaoperatorsdk.operator; -import java.util.Arrays; +import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executors; @@ -13,7 +13,14 @@ import io.fabric8.kubernetes.api.model.authorization.v1.SubjectRulesReviewStatus; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.V1ApiextensionAPIGroupDSL; -import io.fabric8.kubernetes.client.dsl.*; +import io.fabric8.kubernetes.client.dsl.AnyNamespaceOperation; +import io.fabric8.kubernetes.client.dsl.ApiextensionsAPIGroupDSL; +import io.fabric8.kubernetes.client.dsl.FilterWatchListDeletable; +import io.fabric8.kubernetes.client.dsl.Informable; +import io.fabric8.kubernetes.client.dsl.MixedOperation; +import io.fabric8.kubernetes.client.dsl.NamespaceableResource; +import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation; +import io.fabric8.kubernetes.client.dsl.Resource; import io.fabric8.kubernetes.client.extended.leaderelection.LeaderElectorBuilder; import io.fabric8.kubernetes.client.informers.SharedIndexInformer; import io.fabric8.kubernetes.client.informers.cache.Indexer; @@ -119,10 +126,10 @@ private static Object allowSelfSubjectReview() { SelfSubjectRulesReview review = new SelfSubjectRulesReview(); review.setStatus(new SubjectRulesReviewStatus()); var resourceRule = new ResourceRule(); - resourceRule.setApiGroups(Arrays.asList(COORDINATION_GROUP)); - resourceRule.setResources(Arrays.asList(LEASES_RESOURCE)); - resourceRule.setVerbs(Arrays.asList(UNIVERSAL_VALUE)); - review.getStatus().setResourceRules(Arrays.asList(resourceRule)); + resourceRule.setApiGroups(List.of(COORDINATION_GROUP)); + resourceRule.setResources(List.of(LEASES_RESOURCE)); + resourceRule.setVerbs(List.of(UNIVERSAL_VALUE)); + review.getStatus().setResourceRules(List.of(resourceRule)); return review; } } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverriderTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverriderTest.java index 7a4a5793ba..0e2b8e9cc2 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverriderTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ConfigurationServiceOverriderTest.java @@ -1,5 +1,6 @@ package io.javaoperatorsdk.operator.api.config; +import java.time.Duration; import java.util.Optional; import java.util.concurrent.Executors; @@ -8,7 +9,6 @@ import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.api.monitoring.Metrics; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; class ConfigurationServiceOverriderTest { @@ -60,11 +60,11 @@ public R clone(R object) { } }) .withConcurrentReconciliationThreads(25) - .withTerminationTimeoutSeconds(100) .withMetrics(new Metrics() {}) .withLeaderElectionConfiguration(new LeaderElectionConfiguration("newLease", "newLeaseNS")) .withInformerStoppedHandler((informer, ex) -> { }) + .withReconciliationTerminationTimeout(Duration.ofSeconds(30)) .build(); assertNotEquals(config.closeClientOnStop(), overridden.closeClientOnStop()); @@ -72,8 +72,6 @@ public R clone(R object) { overridden.checkCRDAndValidateLocalModel()); assertNotEquals(config.concurrentReconciliationThreads(), overridden.concurrentReconciliationThreads()); - assertNotEquals(config.getTerminationTimeoutSeconds(), - overridden.getTerminationTimeoutSeconds()); assertNotEquals(config.getExecutorService(), overridden.getExecutorService()); assertNotEquals(config.getWorkflowExecutorService(), overridden.getWorkflowExecutorService()); assertNotEquals(config.getMetrics(), overridden.getMetrics()); @@ -81,26 +79,8 @@ public R clone(R object) { overridden.getLeaderElectionConfiguration()); assertNotEquals(config.getInformerStoppedHandler(), overridden.getLeaderElectionConfiguration()); - } - - @Test - void shouldReplaceInvalidValues() { - final var original = new BaseConfigurationService(); - - final var service = ConfigurationService.newOverriddenConfigurationService(original, - o -> o - .withConcurrentReconciliationThreads(0) - .withMinConcurrentReconciliationThreads(-1) - .withConcurrentWorkflowExecutorThreads(2) - .withMinConcurrentWorkflowExecutorThreads(3)); - - assertEquals(original.minConcurrentReconciliationThreads(), - service.minConcurrentReconciliationThreads()); - assertEquals(original.concurrentReconciliationThreads(), - service.concurrentReconciliationThreads()); - assertEquals(3, service.minConcurrentWorkflowExecutorThreads()); - assertEquals(original.concurrentWorkflowExecutorThreads(), - service.concurrentWorkflowExecutorThreads()); + assertNotEquals(config.reconciliationTerminationTimeout(), + overridden.reconciliationTerminationTimeout()); } } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ControllerConfigurationOverriderTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ControllerConfigurationOverriderTest.java index 1c86886d89..46ef56e1d4 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ControllerConfigurationOverriderTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ControllerConfigurationOverriderTest.java @@ -11,30 +11,38 @@ import io.fabric8.kubernetes.client.informers.cache.BasicItemStore; import io.fabric8.kubernetes.client.informers.cache.Cache; import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceConfigurationResolver; +import io.javaoperatorsdk.operator.api.config.informer.Informer; +import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; import io.javaoperatorsdk.operator.api.reconciler.Constants; 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; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; +import io.javaoperatorsdk.operator.api.reconciler.dependent.GarbageCollected; import io.javaoperatorsdk.operator.api.reconciler.dependent.ReconcileResult; -import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.DependentResourceConfigurator; +import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.ConfiguredDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResourceConfig; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResourceConfigBuilder; import io.javaoperatorsdk.operator.processing.dependent.workflow.Condition; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration.inheritsNamespacesFromController; +import static org.junit.jupiter.api.Assertions.*; class ControllerConfigurationOverriderTest { private final BaseConfigurationService configurationService = new BaseConfigurationService(); + @SuppressWarnings("unchecked") + private static Object extractDependentKubernetesResourceConfig( + io.javaoperatorsdk.operator.api.config.ControllerConfiguration configuration, int index) { + final var spec = + configuration.getWorkflowSpec().orElseThrow().getDependentResourceSpecs().get(index); + return configuration.getConfigurationFor(spec); + } @BeforeEach void clearStaticState() { @@ -46,7 +54,8 @@ void overridingNSShouldPreserveUntouchedDependents() { var configuration = createConfiguration(new NamedDependentReconciler()); // check that we have the proper number of dependent configs - var dependentResources = configuration.getDependentResources(); + var dependentResources = + configuration.getWorkflowSpec().orElseThrow().getDependentResourceSpecs(); assertEquals(2, dependentResources.size()); // override the NS @@ -58,144 +67,80 @@ void overridingNSShouldPreserveUntouchedDependents() { .settingNamespace(namespace) .replacingNamedDependentResourceConfig(externalDRName, stringConfig) .build(); - assertEquals(Set.of(namespace), configuration.getNamespaces()); + assertEquals(Set.of(namespace), configuration.getInformerConfig().getNamespaces()); // check that we still have the proper number of dependent configs - dependentResources = configuration.getDependentResources(); + dependentResources = configuration.getWorkflowSpec().orElseThrow().getDependentResourceSpecs(); assertEquals(2, dependentResources.size()); final var resourceConfig = extractDependentKubernetesResourceConfig( configuration, 1); assertEquals(stringConfig, resourceConfig); } - @ControllerConfiguration(dependents = { - @Dependent(type = NamedDependentReconciler.NamedDependentResource.class), - @Dependent(type = NamedDependentReconciler.ExternalDependentResource.class) - }) - private static class NamedDependentReconciler implements Reconciler { - - @Override - public UpdateControl reconcile(ConfigMap resource, Context context) - throws Exception { - return null; - } - - private static class NamedDependentResource - extends KubernetesDependentResource { - - public NamedDependentResource() { - super(ConfigMap.class); - } - } - - private static class ExternalDependentResource implements DependentResource, - DependentResourceConfigurator { - - private String config = "UNSET"; - - @Override - public ReconcileResult reconcile(ConfigMap primary, Context context) { - return null; - } - - @Override - public Class resourceType() { - return Object.class; - } - - @Override - public void configureWith(String config) { - this.config = config; - } - - @Override - public Optional configuration() { - return Optional.of(config); - } - } - } - - @SuppressWarnings("rawtypes") + @SuppressWarnings({"rawtypes"}) private KubernetesDependentResourceConfig extractFirstDependentKubernetesResourceConfig( io.javaoperatorsdk.operator.api.config.ControllerConfiguration configuration) { return (KubernetesDependentResourceConfig) extractDependentKubernetesResourceConfig( configuration, 0); } - private Object extractDependentKubernetesResourceConfig( - io.javaoperatorsdk.operator.api.config.ControllerConfiguration configuration, int index) { - final var spec = configuration.getDependentResources().get(index); - return DependentResourceConfigurationResolver.configurationFor(spec, configuration); - } - private io.javaoperatorsdk.operator.api.config.ControllerConfiguration createConfiguration( Reconciler reconciler) { return configurationService.configFor(reconciler); } - private static class MyItemStore extends BasicItemStore { - - public MyItemStore() { - super(Cache::metaNamespaceKeyFunc); - } - - } - - @ControllerConfiguration(namespaces = "foo", itemStore = MyItemStore.class) - private static class WatchCurrentReconciler implements Reconciler { - - @Override - public UpdateControl reconcile(ConfigMap resource, Context context) - throws Exception { - return null; - } - } - @Test void overridingNamespacesShouldWork() { var configuration = createConfiguration(new WatchCurrentReconciler()); - assertEquals(Set.of("foo"), configuration.getNamespaces()); - assertFalse(configuration.watchAllNamespaces()); - assertFalse(configuration.watchCurrentNamespace()); + var informerConfig = configuration.getInformerConfig(); + assertEquals(Set.of("foo"), informerConfig.getNamespaces()); + assertFalse(informerConfig.watchAllNamespaces()); + assertFalse(informerConfig.watchCurrentNamespace()); configuration = ControllerConfigurationOverrider.override(configuration) .addingNamespaces("foo", "bar") .build(); - assertEquals(Set.of("foo", "bar"), configuration.getNamespaces()); - assertFalse(configuration.watchAllNamespaces()); - assertFalse(configuration.watchCurrentNamespace()); + informerConfig = configuration.getInformerConfig(); + assertEquals(Set.of("foo", "bar"), informerConfig.getNamespaces()); + assertFalse(informerConfig.watchAllNamespaces()); + assertFalse(informerConfig.watchCurrentNamespace()); configuration = ControllerConfigurationOverrider.override(configuration) .removingNamespaces("bar") .build(); - assertEquals(Set.of("foo"), configuration.getNamespaces()); - assertFalse(configuration.watchAllNamespaces()); - assertFalse(configuration.watchCurrentNamespace()); + informerConfig = configuration.getInformerConfig(); + assertEquals(Set.of("foo"), informerConfig.getNamespaces()); + assertFalse(informerConfig.watchAllNamespaces()); + assertFalse(informerConfig.watchCurrentNamespace()); configuration = ControllerConfigurationOverrider.override(configuration) .removingNamespaces("foo") .build(); - assertTrue(configuration.watchAllNamespaces()); - assertFalse(configuration.watchCurrentNamespace()); + informerConfig = configuration.getInformerConfig(); + assertTrue(informerConfig.watchAllNamespaces()); + assertFalse(informerConfig.watchCurrentNamespace()); configuration = ControllerConfigurationOverrider.override(configuration) .settingNamespace("foo") .build(); - assertFalse(configuration.watchAllNamespaces()); - assertFalse(configuration.watchCurrentNamespace()); - assertEquals(Set.of("foo"), configuration.getNamespaces()); + informerConfig = configuration.getInformerConfig(); + assertFalse(informerConfig.watchAllNamespaces()); + assertFalse(informerConfig.watchCurrentNamespace()); + assertEquals(Set.of("foo"), informerConfig.getNamespaces()); configuration = ControllerConfigurationOverrider.override(configuration) .watchingOnlyCurrentNamespace() .build(); - assertFalse(configuration.watchAllNamespaces()); - assertTrue(configuration.watchCurrentNamespace()); + informerConfig = configuration.getInformerConfig(); + assertFalse(informerConfig.watchAllNamespaces()); + assertTrue(informerConfig.watchCurrentNamespace()); configuration = ControllerConfigurationOverrider.override(configuration) .watchingAllNamespaces() .build(); - assertTrue(configuration.watchAllNamespaces()); - assertFalse(configuration.watchCurrentNamespace()); + informerConfig = configuration.getInformerConfig(); + assertTrue(informerConfig.watchAllNamespaces()); + assertFalse(informerConfig.watchCurrentNamespace()); } @Test @@ -205,23 +150,24 @@ void itemStorePreserved() { configuration = ControllerConfigurationOverrider.override(configuration) .build(); - assertNotNull(configuration.getItemStore().orElse(null)); + assertNotNull(configuration.getInformerConfig().getItemStore()); } @Test void configuredDependentShouldNotChangeOnParentOverrideEvenWhenInitialConfigIsSame() { var configuration = createConfiguration(new OverriddenNSOnDepReconciler()); // retrieve the config for the first (and unique) dependent - var config = extractFirstDependentKubernetesResourceConfig(configuration); + var kubeDependentConfig = extractFirstDependentKubernetesResourceConfig(configuration); // override the parent NS to match the dependent's configuration = ControllerConfigurationOverrider.override(configuration) .settingNamespace(OverriddenNSDependent.DEP_NS).build(); - assertEquals(Set.of(OverriddenNSDependent.DEP_NS), configuration.getNamespaces()); + assertEquals(Set.of(OverriddenNSDependent.DEP_NS), + configuration.getInformerConfig().getNamespaces()); // check that the DependentResource inherits has its own configured NS - assertEquals(1, config.namespaces().size()); - assertEquals(Set.of(OverriddenNSDependent.DEP_NS), config.namespaces()); + assertEquals(Set.of(OverriddenNSDependent.DEP_NS), + kubeDependentConfig.informerConfig().getNamespaces()); // override the parent's NS final var newNS = "bar"; @@ -229,9 +175,9 @@ void configuredDependentShouldNotChangeOnParentOverrideEvenWhenInitialConfigIsSa ControllerConfigurationOverrider.override(configuration).settingNamespace(newNS).build(); // check that dependent config is still using its own NS - config = extractFirstDependentKubernetesResourceConfig(configuration); - assertEquals(1, config.namespaces().size()); - assertEquals(Set.of(OverriddenNSDependent.DEP_NS), config.namespaces()); + kubeDependentConfig = extractFirstDependentKubernetesResourceConfig(configuration); + assertEquals(Set.of(OverriddenNSDependent.DEP_NS), + kubeDependentConfig.informerConfig().getNamespaces()); } @SuppressWarnings("unchecked") @@ -242,17 +188,9 @@ void dependentShouldWatchAllNamespacesIfParentDoesAsWell() { var config = extractFirstDependentKubernetesResourceConfig(configuration); // check that the DependentResource inherits the controller's configuration if applicable - assertTrue(ResourceConfiguration.allNamespacesWatched(config.namespaces())); - - // override the NS - final var newNS = "bar"; - configuration = - ControllerConfigurationOverrider.override(configuration).settingNamespace(newNS).build(); + var informerConfig = config.informerConfig(); + assertTrue(inheritsNamespacesFromController(informerConfig.getNamespaces())); - // check that dependent config is using the overridden namespace - config = extractFirstDependentKubernetesResourceConfig(configuration); - assertEquals(1, config.namespaces().size()); - assertEquals(Set.of(newNS), config.namespaces()); } @SuppressWarnings("unchecked") @@ -263,7 +201,9 @@ void shouldBePossibleToForceDependentToWatchAllNamespaces() { var config = extractFirstDependentKubernetesResourceConfig(configuration); // check that the DependentResource inherits the controller's configuration if applicable - assertTrue(ResourceConfiguration.allNamespacesWatched(config.namespaces())); + assertTrue( + InformerConfiguration + .allNamespacesWatched(config.informerConfig().getNamespaces())); // override the NS final var newNS = "bar"; @@ -272,7 +212,9 @@ void shouldBePossibleToForceDependentToWatchAllNamespaces() { // check that dependent config is still configured to watch all NS config = extractFirstDependentKubernetesResourceConfig(configuration); - assertTrue(ResourceConfiguration.allNamespacesWatched(config.namespaces())); + assertTrue( + InformerConfiguration + .allNamespacesWatched(config.informerConfig().getNamespaces())); } @Test @@ -282,18 +224,7 @@ void overridingNamespacesShouldBePropagatedToDependentsWithDefaultConfig() { var config = extractFirstDependentKubernetesResourceConfig(configuration); // check that the DependentResource inherits the controller's configuration if applicable - assertEquals(1, config.namespaces().size()); - assertEquals(Set.of(OneDepReconciler.CONFIGURED_NS), config.namespaces()); - - // override the NS - final var newNS = "bar"; - configuration = - ControllerConfigurationOverrider.override(configuration).settingNamespace(newNS).build(); - - // check that dependent config is using the overridden namespace - config = extractFirstDependentKubernetesResourceConfig(configuration); - assertEquals(1, config.namespaces().size()); - assertEquals(Set.of(newNS), config.namespaces()); + assertEquals(1, config.informerConfig().getNamespaces().size()); } @Test @@ -303,8 +234,8 @@ void alreadyOverriddenDependentNamespacesShouldNotBePropagated() { var config = extractFirstDependentKubernetesResourceConfig(configuration); // DependentResource has its own NS - assertEquals(1, config.namespaces().size()); - assertEquals(Set.of(OverriddenNSDependent.DEP_NS), config.namespaces()); + assertEquals(Set.of(OverriddenNSDependent.DEP_NS), + config.informerConfig().getNamespaces()); // override the NS final var newNS = "bar"; @@ -313,15 +244,15 @@ void alreadyOverriddenDependentNamespacesShouldNotBePropagated() { // check that dependent config is still using its own NS config = extractFirstDependentKubernetesResourceConfig(configuration); - assertEquals(1, config.namespaces().size()); - assertEquals(Set.of(OverriddenNSDependent.DEP_NS), config.namespaces()); + assertEquals(Set.of(OverriddenNSDependent.DEP_NS), + config.informerConfig().getNamespaces()); } - @SuppressWarnings({"rawtypes", "unchecked"}) @Test + @SuppressWarnings({"rawtypes", "unchecked"}) void replaceNamedDependentResourceConfigShouldWork() { var configuration = createConfiguration(new OneDepReconciler()); - var dependents = configuration.getDependentResources(); + var dependents = configuration.getWorkflowSpec().orElseThrow().getDependentResourceSpecs(); assertFalse(dependents.isEmpty()); assertEquals(1, dependents.size()); @@ -332,41 +263,63 @@ void replaceNamedDependentResourceConfigShouldWork() { .filter(dr -> dr.getName().equals(dependentResourceName)) .findFirst().orElseThrow(); assertEquals(ReadOnlyDependent.class, dependentSpec.getDependentResourceClass()); - var maybeConfig = - DependentResourceConfigurationResolver.configurationFor(dependentSpec, configuration); + var maybeConfig = extractFirstDependentKubernetesResourceConfig(configuration); assertNotNull(maybeConfig); - assertTrue(maybeConfig instanceof KubernetesDependentResourceConfig); + assertInstanceOf(KubernetesDependentResourceConfig.class, maybeConfig); var config = (KubernetesDependentResourceConfig) maybeConfig; // check that the DependentResource inherits the controller's configuration if applicable - assertEquals(1, config.namespaces().size()); - assertNull(config.labelSelector()); - assertEquals(Set.of(OneDepReconciler.CONFIGURED_NS), config.namespaces()); + var informerConfig = config.informerConfig(); + assertEquals(1, informerConfig.getNamespaces().size()); + assertNull(informerConfig.getLabelSelector()); // override the namespaces for the dependent resource final var overriddenNS = "newNS"; final var labelSelector = "foo=bar"; + final var overridingInformerConfig = InformerConfiguration.builder(ConfigMap.class) + .withNamespaces(Set.of(overriddenNS)) + .withLabelSelector(labelSelector) + .buildForInformerEventSource(); final var overridden = ControllerConfigurationOverrider.override(configuration) .replacingNamedDependentResourceConfig( - DependentResource.defaultNameFor(ReadOnlyDependent.class), - new KubernetesDependentResourceConfigBuilder<>() - .withNamespaces(Set.of(overriddenNS)) - .withLabelSelector(labelSelector) + dependentResourceName, + new KubernetesDependentResourceConfigBuilder() + .withKubernetesDependentInformerConfig(overridingInformerConfig) .build()) .build(); - dependents = overridden.getDependentResources(); - dependentSpec = dependents.stream().filter(dr -> dr.getName().equals(dependentResourceName)) - .findFirst().orElseThrow(); - config = (KubernetesDependentResourceConfig) DependentResourceConfigurationResolver - .configurationFor(dependentSpec, overridden); - assertEquals(1, config.namespaces().size()); - assertEquals(labelSelector, config.labelSelector()); - assertEquals(Set.of(overriddenNS), config.namespaces()); + dependents = overridden.getWorkflowSpec().orElseThrow().getDependentResourceSpecs(); + dependentSpec = dependents.stream() + .filter(dr -> dr.getName().equals(dependentResourceName)) + .findFirst() + .orElseThrow(); + config = (KubernetesDependentResourceConfig) overridden.getConfigurationFor(dependentSpec); + informerConfig = config.informerConfig(); + assertEquals(labelSelector, informerConfig.getLabelSelector()); + assertEquals(Set.of(overriddenNS), informerConfig.getNamespaces()); // check that we still have the proper workflow configuration - assertTrue(dependentSpec.getReadyCondition() instanceof TestCondition); + assertInstanceOf(TestCondition.class, dependentSpec.getReadyCondition()); + } + + private static class MyItemStore extends BasicItemStore { + + public MyItemStore() { + super(Cache::metaNamespaceKeyFunc); + } + } - @ControllerConfiguration(dependents = @Dependent(type = ReadOnlyDependent.class)) + @ControllerConfiguration( + informer = @Informer(namespaces = "foo", itemStore = MyItemStore.class)) + private static class WatchCurrentReconciler implements Reconciler { + + @Override + public UpdateControl reconcile(ConfigMap resource, Context context) { + return null; + } + } + + @Workflow(dependents = @Dependent(type = ReadOnlyDependent.class)) + @ControllerConfiguration private static class WatchAllNamespacesReconciler implements Reconciler { @Override @@ -375,7 +328,8 @@ public UpdateControl reconcile(ConfigMap resource, Context } } - @ControllerConfiguration(dependents = @Dependent(type = WatchAllNSDependent.class)) + @Workflow(dependents = @Dependent(type = WatchAllNSDependent.class)) + @ControllerConfiguration private static class DependentWatchesAllNSReconciler implements Reconciler { @Override @@ -394,9 +348,10 @@ public boolean isMet(DependentResource dependentResource, } } - @ControllerConfiguration(namespaces = OneDepReconciler.CONFIGURED_NS, - dependents = @Dependent(type = ReadOnlyDependent.class, - readyPostcondition = TestCondition.class)) + @Workflow(dependents = @Dependent(type = ReadOnlyDependent.class, + readyPostcondition = TestCondition.class)) + @ControllerConfiguration( + informer = @Informer(namespaces = OneDepReconciler.CONFIGURED_NS)) private static class OneDepReconciler implements Reconciler { private static final String CONFIGURED_NS = "foo"; @@ -407,25 +362,29 @@ public UpdateControl reconcile(ConfigMap resource, Context } } - private static class ReadOnlyDependent extends KubernetesDependentResource { + public static class ReadOnlyDependent extends KubernetesDependentResource + implements GarbageCollected { public ReadOnlyDependent() { super(ConfigMap.class); } } - @KubernetesDependent(namespaces = Constants.WATCH_ALL_NAMESPACES) - private static class WatchAllNSDependent - extends KubernetesDependentResource { + @KubernetesDependent( + informer = @Informer(namespaces = Constants.WATCH_ALL_NAMESPACES)) + public static class WatchAllNSDependent + extends KubernetesDependentResource + implements GarbageCollected { public WatchAllNSDependent() { super(ConfigMap.class); } } - @ControllerConfiguration(namespaces = OverriddenNSOnDepReconciler.CONFIGURED_NS, - dependents = @Dependent(type = OverriddenNSDependent.class)) - private static class OverriddenNSOnDepReconciler implements Reconciler { + @Workflow(dependents = @Dependent(type = OverriddenNSDependent.class)) + @ControllerConfiguration( + informer = @Informer(namespaces = OverriddenNSOnDepReconciler.CONFIGURED_NS)) + public static class OverriddenNSOnDepReconciler implements Reconciler { private static final String CONFIGURED_NS = "parentNS"; @@ -435,9 +394,10 @@ public UpdateControl reconcile(ConfigMap resource, Context } } - @KubernetesDependent(namespaces = OverriddenNSDependent.DEP_NS) - private static class OverriddenNSDependent - extends KubernetesDependentResource { + @KubernetesDependent(informer = @Informer(namespaces = OverriddenNSDependent.DEP_NS)) + public static class OverriddenNSDependent + extends KubernetesDependentResource + implements GarbageCollected { private static final String DEP_NS = "dependentNS"; @@ -445,4 +405,55 @@ public OverriddenNSDependent() { super(ConfigMap.class); } } + + @Workflow(dependents = { + @Dependent(type = NamedDependentReconciler.NamedDependentResource.class), + @Dependent(type = NamedDependentReconciler.ExternalDependentResource.class) + }) + @ControllerConfiguration + public static class NamedDependentReconciler implements Reconciler { + + @Override + public UpdateControl reconcile(ConfigMap resource, Context context) { + return null; + } + + private static class NamedDependentResource + extends KubernetesDependentResource + implements GarbageCollected { + + public NamedDependentResource() { + super(ConfigMap.class); + } + } + + private static class ExternalDependentResource implements DependentResource, + ConfiguredDependentResource, GarbageCollected { + + private String config = "UNSET"; + + @Override + public ReconcileResult reconcile(ConfigMap primary, Context context) { + return null; + } + + @Override + public Class resourceType() { + return Object.class; + } + + @Override + public void configureWith(String config) { + this.config = config; + } + + @Override + public Optional configuration() { + return Optional.of(config); + } + + @Override + public void delete(ConfigMap primary, Context context) {} + } + } } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/InformerConfigurationTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/InformerConfigurationTest.java new file mode 100644 index 0000000000..468c67e0d7 --- /dev/null +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/InformerConfigurationTest.java @@ -0,0 +1,83 @@ +package io.javaoperatorsdk.operator.api.config; + +import java.util.Collections; +import java.util.Set; + +import org.junit.jupiter.api.Test; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.Constants; + +import static org.junit.jupiter.api.Assertions.*; + +class InformerConfigurationTest { + + @Test + void allNamespacesWatched() { + assertThrows(IllegalArgumentException.class, + () -> InformerConfiguration.allNamespacesWatched(null)); + assertThrows(IllegalArgumentException.class, () -> InformerConfiguration.allNamespacesWatched( + Set.of(Constants.WATCH_CURRENT_NAMESPACE, Constants.WATCH_ALL_NAMESPACES, "foo"))); + assertThrows(IllegalArgumentException.class, () -> InformerConfiguration.allNamespacesWatched( + Collections.emptySet())); + assertFalse(InformerConfiguration.allNamespacesWatched(Set.of("foo", "bar"))); + assertTrue(InformerConfiguration.allNamespacesWatched(Set.of(Constants.WATCH_ALL_NAMESPACES))); + assertFalse(InformerConfiguration.allNamespacesWatched(Set.of("foo"))); + assertFalse( + InformerConfiguration.allNamespacesWatched(Set.of(Constants.WATCH_CURRENT_NAMESPACE))); + } + + @Test + void currentNamespaceWatched() { + assertThrows(IllegalArgumentException.class, + () -> InformerConfiguration.currentNamespaceWatched(null)); + assertThrows(IllegalArgumentException.class, + () -> InformerConfiguration.currentNamespaceWatched( + Set.of(Constants.WATCH_CURRENT_NAMESPACE, Constants.WATCH_ALL_NAMESPACES, "foo"))); + assertThrows(IllegalArgumentException.class, + () -> InformerConfiguration.currentNamespaceWatched(Collections.emptySet())); + assertFalse(InformerConfiguration.currentNamespaceWatched(Set.of("foo", "bar"))); + assertFalse( + InformerConfiguration.currentNamespaceWatched(Set.of(Constants.WATCH_ALL_NAMESPACES))); + assertFalse(InformerConfiguration.currentNamespaceWatched(Set.of("foo"))); + assertTrue( + InformerConfiguration.currentNamespaceWatched(Set.of(Constants.WATCH_CURRENT_NAMESPACE))); + } + + @Test + void nullLabelSelectorByDefault() { + final var informerConfig = + InformerConfiguration.builder(ConfigMap.class).buildForInformerEventSource(); + assertNull(informerConfig.getLabelSelector()); + } + + @Test + void shouldWatchAllNamespacesByDefaultForControllers() { + final var informerConfig = InformerConfiguration.builder(ConfigMap.class).buildForController(); + assertTrue(informerConfig.watchAllNamespaces()); + } + + @Test + void shouldFollowControllerNamespacesByDefaultForInformerEventSource() { + final var informerConfig = + InformerConfiguration.builder(ConfigMap.class).buildForInformerEventSource(); + assertTrue(informerConfig.isFollowControllerNamespacesOnChange()); + } + + @Test + void failIfNotValid() { + assertThrows(IllegalArgumentException.class, () -> InformerConfiguration.failIfNotValid(null)); + assertThrows(IllegalArgumentException.class, + () -> InformerConfiguration.failIfNotValid(Collections.emptySet())); + assertThrows(IllegalArgumentException.class, () -> InformerConfiguration.failIfNotValid( + Set.of(Constants.WATCH_CURRENT_NAMESPACE, Constants.WATCH_ALL_NAMESPACES, "foo"))); + assertThrows(IllegalArgumentException.class, () -> InformerConfiguration.failIfNotValid( + Set.of(Constants.WATCH_CURRENT_NAMESPACE, "foo"))); + assertThrows(IllegalArgumentException.class, () -> InformerConfiguration.failIfNotValid( + Set.of(Constants.WATCH_ALL_NAMESPACES, "foo"))); + + // should work + InformerConfiguration.failIfNotValid(Set.of("foo", "bar")); + } +} diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/MockControllerConfiguration.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/MockControllerConfiguration.java index 6ae83294bb..afd01d0f90 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/MockControllerConfiguration.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/MockControllerConfiguration.java @@ -1,6 +1,7 @@ package io.javaoperatorsdk.operator.api.config; import io.fabric8.kubernetes.api.model.HasMetadata; +import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; import static io.javaoperatorsdk.operator.api.reconciler.Constants.DEFAULT_NAMESPACES_SET; import static org.mockito.ArgumentMatchers.any; @@ -18,9 +19,11 @@ public static ControllerConfiguration forResource( public static ControllerConfiguration forResource( Class resourceType, ConfigurationService configurationService) { final ControllerConfiguration configuration = mock(ControllerConfiguration.class); + final InformerConfiguration informerConfiguration = mock(InformerConfiguration.class); + when(configuration.getInformerConfig()).thenReturn(informerConfiguration); when(configuration.getResourceClass()).thenReturn(resourceType); - when(configuration.getNamespaces()).thenReturn(DEFAULT_NAMESPACES_SET); - when(configuration.getEffectiveNamespaces(any())).thenCallRealMethod(); + when(informerConfiguration.getNamespaces()).thenReturn(DEFAULT_NAMESPACES_SET); + when(informerConfiguration.getEffectiveNamespaces(any())).thenCallRealMethod(); when(configuration.getName()).thenReturn(resourceType.getSimpleName()); when(configuration.getConfigurationService()).thenReturn(configurationService); return configuration; diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ResourceConfigurationTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ResourceConfigurationTest.java deleted file mode 100644 index 013eec9cc0..0000000000 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/ResourceConfigurationTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package io.javaoperatorsdk.operator.api.config; - -import java.util.Collections; -import java.util.Set; - -import org.junit.jupiter.api.Test; - -import io.javaoperatorsdk.operator.api.reconciler.Constants; - -import static org.junit.jupiter.api.Assertions.*; - -class ResourceConfigurationTest { - - @Test - void allNamespacesWatched() { - assertThrows(IllegalArgumentException.class, - () -> ResourceConfiguration.allNamespacesWatched(null)); - assertThrows(IllegalArgumentException.class, () -> ResourceConfiguration.allNamespacesWatched( - Set.of(Constants.WATCH_CURRENT_NAMESPACE, Constants.WATCH_ALL_NAMESPACES, "foo"))); - assertThrows(IllegalArgumentException.class, () -> ResourceConfiguration.allNamespacesWatched( - Collections.emptySet())); - assertFalse(ResourceConfiguration.allNamespacesWatched(Set.of("foo", "bar"))); - assertTrue(ResourceConfiguration.allNamespacesWatched(Set.of(Constants.WATCH_ALL_NAMESPACES))); - assertFalse(ResourceConfiguration.allNamespacesWatched(Set.of("foo"))); - assertFalse( - ResourceConfiguration.allNamespacesWatched(Set.of(Constants.WATCH_CURRENT_NAMESPACE))); - } - - @Test - void currentNamespaceWatched() { - assertThrows(IllegalArgumentException.class, - () -> ResourceConfiguration.currentNamespaceWatched(null)); - assertThrows(IllegalArgumentException.class, - () -> ResourceConfiguration.currentNamespaceWatched( - Set.of(Constants.WATCH_CURRENT_NAMESPACE, Constants.WATCH_ALL_NAMESPACES, "foo"))); - assertThrows(IllegalArgumentException.class, - () -> ResourceConfiguration.currentNamespaceWatched(Collections.emptySet())); - assertFalse(ResourceConfiguration.currentNamespaceWatched(Set.of("foo", "bar"))); - assertFalse( - ResourceConfiguration.currentNamespaceWatched(Set.of(Constants.WATCH_ALL_NAMESPACES))); - assertFalse(ResourceConfiguration.currentNamespaceWatched(Set.of("foo"))); - assertTrue( - ResourceConfiguration.currentNamespaceWatched(Set.of(Constants.WATCH_CURRENT_NAMESPACE))); - } - - @Test - void nullLabelSelectorByDefault() { - assertNull(new ResourceConfiguration<>() {}.getLabelSelector()); - } - - @Test - void shouldWatchAllNamespacesByDefault() { - assertTrue(new ResourceConfiguration<>() {}.watchAllNamespaces()); - } - - @Test - void failIfNotValid() { - assertThrows(IllegalArgumentException.class, () -> ResourceConfiguration.failIfNotValid(null)); - assertThrows(IllegalArgumentException.class, - () -> ResourceConfiguration.failIfNotValid(Collections.emptySet())); - assertThrows(IllegalArgumentException.class, () -> ResourceConfiguration.failIfNotValid( - Set.of(Constants.WATCH_CURRENT_NAMESPACE, Constants.WATCH_ALL_NAMESPACES, "foo"))); - assertThrows(IllegalArgumentException.class, () -> ResourceConfiguration.failIfNotValid( - Set.of(Constants.WATCH_CURRENT_NAMESPACE, "foo"))); - assertThrows(IllegalArgumentException.class, () -> ResourceConfiguration.failIfNotValid( - Set.of(Constants.WATCH_ALL_NAMESPACES, "foo"))); - - // should work - ResourceConfiguration.failIfNotValid(Set.of("foo", "bar")); - } -} diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/dependent/DependentResourceConfigurationResolverTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/dependent/DependentResourceConfigurationResolverTest.java index 3187b32645..5cc5472798 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/dependent/DependentResourceConfigurationResolverTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/config/dependent/DependentResourceConfigurationResolverTest.java @@ -16,18 +16,17 @@ 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; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; +import io.javaoperatorsdk.operator.api.reconciler.dependent.GarbageCollected; import io.javaoperatorsdk.operator.api.reconciler.dependent.ReconcileResult; -import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.DependentResourceConfigurator; +import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.ConfiguredDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentConverter; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; import static io.javaoperatorsdk.operator.api.config.dependent.DependentResourceConfigurationResolverTest.CustomAnnotationReconciler.DR_NAME; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; class DependentResourceConfigurationResolverTest { @@ -49,43 +48,44 @@ private

io.javaoperatorsdk.operator.api.config.Controlle return configurationService.configFor(reconciler); } + @SuppressWarnings({"rawtypes", "unchecked"}) + private static Object extractDependentKubernetesResourceConfig( + io.javaoperatorsdk.operator.api.config.ControllerConfiguration configuration, + Class target) { + final var spec = + configuration.getWorkflowSpec().orElseThrow().getDependentResourceSpecs().stream() + .filter(s -> target.isAssignableFrom(s.getDependentResourceClass())) + .findFirst().orElseThrow(); + return configuration.getConfigurationFor(spec); + } + @Test void controllerConfigurationProvidedShouldBeReturnedIfAvailable() { final var cfg = configFor(new CustomAnnotationReconciler()); - final var customConfig = DependentResourceConfigurationResolver - .extractConfigurationFromConfigured(CustomAnnotatedDep.class, cfg); - assertTrue(customConfig instanceof CustomConfig); + + final var customConfig = + extractDependentKubernetesResourceConfig(cfg, CustomAnnotatedDep.class); + assertInstanceOf(CustomConfig.class, customConfig); assertEquals(CustomAnnotatedDep.PROVIDED_VALUE, ((CustomConfig) customConfig).getValue()); final var newConfig = new CustomConfig(72); final var overridden = ControllerConfigurationOverrider.override(cfg) .replacingNamedDependentResourceConfig(DR_NAME, newConfig) .build(); - final var spec = cfg.getDependentResources().stream() + final var spec = cfg.getWorkflowSpec().orElseThrow().getDependentResourceSpecs().stream() .filter(s -> DR_NAME.equals(s.getName())) .findFirst() .orElseThrow(); - assertEquals(newConfig, - DependentResourceConfigurationResolver.configurationFor(spec, overridden)); + assertEquals(newConfig, overridden.getConfigurationFor(spec)); } @Test void getConverterShouldWork() { - final var cfg = configFor(new CustomAnnotationReconciler()); - var converter = DependentResourceConfigurationResolver.getConverter(CustomAnnotatedDep.class); - assertNull(converter); - assertNull(DependentResourceConfigurationResolver.getConverter(ChildCustomAnnotatedDep.class)); - // extracting configuration should trigger converter creation - DependentResourceConfigurationResolver.extractConfigurationFromConfigured( - CustomAnnotatedDep.class, cfg); - converter = DependentResourceConfigurationResolver.getConverter(CustomAnnotatedDep.class); + configFor(new CustomAnnotationReconciler()); + var converter = DependentResourceConfigurationResolver.getConverter(CustomAnnotatedDep.class); assertNotNull(converter); assertEquals(CustomConfigConverter.class, converter.getClass()); - converter = DependentResourceConfigurationResolver.getConverter(ChildCustomAnnotatedDep.class); - assertNull(converter); - DependentResourceConfigurationResolver.extractConfigurationFromConfigured( - ChildCustomAnnotatedDep.class, cfg); converter = DependentResourceConfigurationResolver.getConverter(ChildCustomAnnotatedDep.class); assertNotNull(converter); assertEquals(CustomConfigConverter.class, converter.getClass()); @@ -96,41 +96,34 @@ void getConverterShouldWork() { @SuppressWarnings("rawtypes") @Test void registerConverterShouldWork() { - final var cfg = configFor(new CustomAnnotationReconciler()); - var converter = DependentResourceConfigurationResolver.getConverter(ConfigMapDep.class); - assertNull(converter); - DependentResourceConfigurationResolver.extractConfigurationFromConfigured(ConfigMapDep.class, - cfg); - converter = DependentResourceConfigurationResolver.getConverter(ConfigMapDep.class); - assertTrue(converter instanceof KubernetesDependentConverter); final var overriddenConverter = new ConfigurationConverter() { + @Override - public Object configFrom(Annotation configAnnotation, - io.javaoperatorsdk.operator.api.config.ControllerConfiguration parentConfiguration, - Class originatingClass) { + public Object configFrom(Annotation configAnnotation, DependentResourceSpec spec, + io.javaoperatorsdk.operator.api.config.ControllerConfiguration parentConfiguration) { return null; } }; - DependentResourceConfigurationResolver.registerConverter(KubernetesDependentResource.class, + DependentResourceConfigurationResolver.registerConverter(ServiceDep.class, overriddenConverter); + configFor(new CustomAnnotationReconciler()); - // already resolved converters are kept unchanged - converter = DependentResourceConfigurationResolver.getConverter(ConfigMapDep.class); - assertTrue(converter instanceof KubernetesDependentConverter); + // non overridden dependents should use the default converter + var converter = DependentResourceConfigurationResolver.getConverter(ConfigMapDep.class); + assertInstanceOf(KubernetesDependentConverter.class, converter); - // but new converters should use the overridden version - DependentResourceConfigurationResolver.extractConfigurationFromConfigured(ServiceDep.class, - cfg); + // dependent with registered converter should use that one converter = DependentResourceConfigurationResolver.getConverter(ServiceDep.class); assertEquals(overriddenConverter, converter); } - @ControllerConfiguration(dependents = { + @Workflow(dependents = { @Dependent(type = CustomAnnotatedDep.class, name = DR_NAME), @Dependent(type = ChildCustomAnnotatedDep.class), @Dependent(type = ConfigMapDep.class), @Dependent(type = ServiceDep.class) }) + @ControllerConfiguration static class CustomAnnotationReconciler implements Reconciler { public static final String DR_NAME = "first"; @@ -142,14 +135,16 @@ public UpdateControl reconcile(ConfigMap resource, Context } } - private static class ConfigMapDep extends KubernetesDependentResource { + public static class ConfigMapDep extends KubernetesDependentResource + implements GarbageCollected { public ConfigMapDep() { super(ConfigMap.class); } } - private static class ServiceDep extends KubernetesDependentResource { + public static class ServiceDep extends KubernetesDependentResource + implements GarbageCollected { public ServiceDep() { super(Service.class); @@ -160,7 +155,7 @@ public ServiceDep() { @Configured(by = CustomAnnotation.class, with = CustomConfig.class, converter = CustomConfigConverter.class) private static class CustomAnnotatedDep implements DependentResource, - DependentResourceConfigurator { + ConfiguredDependentResource, GarbageCollected { public static final int PROVIDED_VALUE = 42; private CustomConfig config; @@ -184,6 +179,11 @@ public void configureWith(CustomConfig config) { public Optional configuration() { return Optional.ofNullable(config); } + + @Override + public void delete(ConfigMap primary, Context context) { + + } } private static class ChildCustomAnnotatedDep extends CustomAnnotatedDep { @@ -210,14 +210,14 @@ public int getValue() { } private static class CustomConfigConverter - implements ConfigurationConverter { + implements ConfigurationConverter { static final int CONVERTER_PROVIDED_DEFAULT = 7; @Override public CustomConfig configFrom(CustomAnnotation configAnnotation, - io.javaoperatorsdk.operator.api.config.ControllerConfiguration parentConfiguration, - Class originatingClass) { + DependentResourceSpec spec, + io.javaoperatorsdk.operator.api.config.ControllerConfiguration parentConfiguration) { if (configAnnotation == null) { return new CustomConfig(CONVERTER_PROVIDED_DEFAULT); } else { diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/reconciler/DefaultContextTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/reconciler/DefaultContextTest.java new file mode 100644 index 0000000000..3d8fc9563e --- /dev/null +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/reconciler/DefaultContextTest.java @@ -0,0 +1,37 @@ +package io.javaoperatorsdk.operator.api.reconciler; + +import org.junit.jupiter.api.Test; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.Secret; +import io.javaoperatorsdk.operator.processing.Controller; +import io.javaoperatorsdk.operator.processing.event.EventSourceManager; +import io.javaoperatorsdk.operator.processing.event.NoEventSourceForClassException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class DefaultContextTest { + + Secret primary = new Secret(); + Controller mockController = mock(Controller.class); + + DefaultContext context = new DefaultContext<>(null, mockController, primary); + + @Test + void getSecondaryResourceReturnsEmptyOptionalOnNonActivatedDRType() { + var mockManager = mock(EventSourceManager.class); + when(mockController.getEventSourceManager()).thenReturn(mockManager); + when(mockController.workflowContainsDependentForType(ConfigMap.class)).thenReturn(true); + when(mockManager.getEventSourceFor(any(), any())) + .thenThrow(new NoEventSourceForClassException(ConfigMap.class)); + + var res = context.getSecondaryResource(ConfigMap.class); + + assertThat(res).isEmpty(); + } + +} diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/reconciler/EventSourceInitializerTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/reconciler/EventSourceInitializerTest.java deleted file mode 100644 index b89ae730ee..0000000000 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/reconciler/EventSourceInitializerTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package io.javaoperatorsdk.operator.api.reconciler; - -import java.util.HashMap; - -import org.junit.jupiter.api.Test; - -import io.javaoperatorsdk.operator.processing.event.source.polling.PollingEventSource; - -import static org.assertj.core.api.Assertions.assertThat; - -class EventSourceInitializerTest { - - @Test - @SuppressWarnings({"rawtypes", "unchecked"}) - void defaultNameDifferentForOtherInstance() { - var eventSource1 = new PollingEventSource(HashMap::new, 1000, String.class); - var eventSource2 = new PollingEventSource(HashMap::new, 1000, String.class); - var eventSourceName1 = EventSourceInitializer.generateNameFor(eventSource1); - var eventSourceName2 = EventSourceInitializer.generateNameFor(eventSource2); - - assertThat(eventSourceName1).isNotEqualTo(eventSourceName2); - } - -} diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/GroupVersionKindTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/GroupVersionKindTest.java index a20233a6f0..2b73107610 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/GroupVersionKindTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/GroupVersionKindTest.java @@ -7,6 +7,7 @@ import io.javaoperatorsdk.operator.processing.dependent.kubernetes.GroupVersionKindPlural; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; class GroupVersionKindTest { @@ -21,6 +22,24 @@ void testInitFromApiVersion() { assertThat(gvk.getVersion()).isEqualTo("v1"); } + @Test + void parseGVK() { + var gvk = GroupVersionKind.fromString("apps/v1/Deployment"); + assertThat(gvk.getGroup()).isEqualTo("apps"); + assertThat(gvk.getVersion()).isEqualTo("v1"); + assertThat(gvk.getKind()).isEqualTo("Deployment"); + + + gvk = GroupVersionKind.fromString("v1/ConfigMap"); + assertThat(gvk.getGroup()).isNull(); + assertThat(gvk.getVersion()).isEqualTo("v1"); + assertThat(gvk.getKind()).isEqualTo("ConfigMap"); + + assertThrows(IllegalArgumentException.class, () -> GroupVersionKind.fromString("v1#ConfigMap")); + assertThrows(IllegalArgumentException.class, + () -> GroupVersionKind.fromString("api/beta/v1/ConfigMap")); + } + @Test void pluralShouldOnlyBeProvidedIfExplicitlySet() { final var kind = "ConfigMap"; @@ -56,4 +75,13 @@ void pluralShouldOverrideDefaultComputedVersionIfProvided() { "MyPlural"); assertThat(gvk.getPlural()).hasValue("MyPlural"); } + + @Test + void encodesGVKToSimpleString() { + var gvk = GroupVersionKind.fromString("apps/v1/Deployment"); + assertThat(gvk.toSimpleString()).isEqualTo("apps/v1/Deployment"); + + gvk = GroupVersionKind.fromString("v1/ConfigMap"); + assertThat(gvk.toSimpleString()).isEqualTo("v1/ConfigMap"); + } } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/EmptyTestDependentResource.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/EmptyTestDependentResource.java index 4fe88296ac..25a849e3ab 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/EmptyTestDependentResource.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/EmptyTestDependentResource.java @@ -9,6 +9,8 @@ public class EmptyTestDependentResource implements DependentResource { + private String name; + @Override public ReconcileResult reconcile(TestCustomResource primary, Context context) { @@ -19,5 +21,13 @@ public ReconcileResult reconcile(TestCustomResource primary, public Class resourceType() { return Deployment.class; } -} + @Override + public String name() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesResourceMatcherTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesResourceMatcherTest.java index a2eea9279c..2663657157 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesResourceMatcherTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericKubernetesResourceMatcherTest.java @@ -13,15 +13,13 @@ import io.javaoperatorsdk.operator.MockKubernetesClient; import io.javaoperatorsdk.operator.ReconcilerUtils; import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.processing.dependent.Matcher; -import io.javaoperatorsdk.operator.processing.dependent.kubernetes.updatermatcher.GenericResourceUpdaterMatcher; import static io.javaoperatorsdk.operator.processing.dependent.kubernetes.GenericKubernetesResourceMatcher.match; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -@SuppressWarnings({"unchecked", "rawtypes"}) +@SuppressWarnings({"unchecked"}) class GenericKubernetesResourceMatcherTest { private static final Context context = mock(Context.class); @@ -29,7 +27,7 @@ class GenericKubernetesResourceMatcherTest { Deployment actual = createDeployment(); Deployment desired = createDeployment(); TestDependentResource dependentResource = new TestDependentResource(desired); - Matcher matcher = GenericKubernetesResourceMatcher.matcherFor(dependentResource); + @BeforeAll static void setUp() { @@ -39,15 +37,17 @@ static void setUp() { @Test void matchesTrivialCases() { - assertThat(matcher.match(actual, null, context).matched()).isTrue(); - assertThat(matcher.match(actual, null, context).computedDesired()).isPresent(); - assertThat(matcher.match(actual, null, context).computedDesired()).contains(desired); + assertThat(GenericKubernetesResourceMatcher.match(desired, actual, context).matched()).isTrue(); + assertThat(GenericKubernetesResourceMatcher.match(desired, actual, context).computedDesired()) + .isPresent(); + assertThat(GenericKubernetesResourceMatcher.match(desired, actual, context).computedDesired()) + .contains(desired); } @Test void matchesAdditiveOnlyChanges() { actual.getSpec().getTemplate().getMetadata().getLabels().put("new-key", "val"); - assertThat(matcher.match(actual, null, context).matched()) + assertThat(GenericKubernetesResourceMatcher.match(desired, actual, context).matched()) .withFailMessage("Additive changes should not cause a mismatch by default") .isTrue(); } @@ -55,8 +55,7 @@ void matchesAdditiveOnlyChanges() { @Test void matchesWithStrongSpecEquality() { actual.getSpec().getTemplate().getMetadata().getLabels().put("new-key", "val"); - assertThat(match(dependentResource, actual, null, context, true, true, - true) + assertThat(match(desired, actual, true, true, context) .matched()) .withFailMessage("Adding values should fail matching when strong equality is required") .isFalse(); @@ -65,7 +64,9 @@ void matchesWithStrongSpecEquality() { @Test void doesNotMatchRemovedValues() { actual = createDeployment(); - assertThat(matcher.match(actual, createPrimary("removed"), context).matched()) + assertThat(GenericKubernetesResourceMatcher + .match(dependentResource.desired(createPrimary("removed"), null), actual, context) + .matched()) .withFailMessage("Removing values in metadata should lead to a mismatch") .isFalse(); } @@ -74,7 +75,7 @@ void doesNotMatchRemovedValues() { void doesNotMatchChangedValues() { actual = createDeployment(); actual.getSpec().setReplicas(2); - assertThat(matcher.match(actual, null, context).matched()) + assertThat(GenericKubernetesResourceMatcher.match(desired, actual, context).matched()) .withFailMessage("Should not have matched because values have changed") .isFalse(); } @@ -83,7 +84,7 @@ void doesNotMatchChangedValues() { void ignoreStatus() { actual = createDeployment(); actual.setStatus(new DeploymentStatusBuilder().withReadyReplicas(1).build()); - assertThat(matcher.match(actual, null, context).matched()) + assertThat(GenericKubernetesResourceMatcher.match(desired, actual, context).matched()) .withFailMessage("Should ignore status in actual") .isTrue(); } @@ -127,11 +128,11 @@ void matchesMetadata() { .withFailMessage("Annotations shouldn't matter when metadata is not considered") .isTrue(); - assertThat(match(dependentResource, actual, null, context, true, true, true).matched()) + assertThat(match(desired, actual, true, true, context).matched()) .withFailMessage("Annotations should matter when metadata is considered") .isFalse(); - assertThat(match(dependentResource, actual, null, context, true, false).matched()) + assertThat(match(desired, actual, false, false, context).matched()) .withFailMessage( "Should match when strong equality is not considered and only additive changes are made") .isTrue(); @@ -147,8 +148,8 @@ void checkServiceAccount() { .addNewImagePullSecret("imagePullSecret3") .build(); - final var matcher = GenericResourceUpdaterMatcher.updaterMatcherFor(ServiceAccount.class); - assertThat(matcher.matches(actual, desired, context)).isTrue(); + assertThat(GenericKubernetesResourceMatcher.match(desired, actual, false, false, context) + .matched()).isTrue(); } @Test @@ -157,7 +158,7 @@ void matchConfigMap() { var actual = createConfigMap(); actual.getData().put("key2", "val2"); - var match = GenericKubernetesResourceMatcher.match(desired, actual, true, + var match = GenericKubernetesResourceMatcher.match(desired, actual, true, false, context); assertThat(match.matched()).isTrue(); } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericResourceUpdaterMatcherTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericResourceUpdaterTest.java similarity index 80% rename from operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericResourceUpdaterMatcherTest.java rename to operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericResourceUpdaterTest.java index 44f3fb51ea..313520b89e 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericResourceUpdaterMatcherTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/GenericResourceUpdaterTest.java @@ -14,14 +14,13 @@ import io.javaoperatorsdk.operator.api.config.ConfigurationService; import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.processing.dependent.kubernetes.updatermatcher.GenericResourceUpdaterMatcher; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @SuppressWarnings("rawtypes") -class GenericResourceUpdaterMatcherTest { +class GenericResourceUpdaterTest { private static final Context context = mock(Context.class); @@ -40,7 +39,6 @@ static void setUp() { @Test void preservesValues() { - var processor = GenericResourceUpdaterMatcher.updaterMatcherFor(Deployment.class); var desired = createDeployment(); var actual = createDeployment(); actual.getMetadata().setLabels(new HashMap<>()); @@ -48,7 +46,7 @@ void preservesValues() { actual.getMetadata().setResourceVersion("1234"); actual.getSpec().setRevisionHistoryLimit(5); - var result = processor.updateResource(actual, desired, context); + var result = GenericResourceUpdater.updateResource(actual, desired, context); assertThat(result.getMetadata().getLabels().get("additionalActualKey")).isEqualTo("value"); assertThat(result.getMetadata().getResourceVersion()).isEqualTo("1234"); @@ -57,27 +55,26 @@ void preservesValues() { @Test void checkNamespaces() { - var processor = GenericResourceUpdaterMatcher.updaterMatcherFor(Namespace.class); var desired = new NamespaceBuilder().withNewMetadata().withName("foo").endMetadata().build(); var actual = new NamespaceBuilder().withNewMetadata().withName("foo").endMetadata().build(); actual.getMetadata().setLabels(new HashMap<>()); actual.getMetadata().getLabels().put("additionalActualKey", "value"); actual.getMetadata().setResourceVersion("1234"); - var result = processor.updateResource(actual, desired, context); + var result = GenericResourceUpdater.updateResource(actual, desired, context); assertThat(result.getMetadata().getLabels().get("additionalActualKey")).isEqualTo("value"); assertThat(result.getMetadata().getResourceVersion()).isEqualTo("1234"); desired.setSpec(new NamespaceSpec(List.of("halkyon.io/finalizer"))); - result = processor.updateResource(actual, desired, context); + result = GenericResourceUpdater.updateResource(actual, desired, context); assertThat(result.getMetadata().getLabels().get("additionalActualKey")).isEqualTo("value"); assertThat(result.getMetadata().getResourceVersion()).isEqualTo("1234"); assertThat(result.getSpec().getFinalizers()).containsExactly("halkyon.io/finalizer"); desired = new NamespaceBuilder().withNewMetadata().withName("foo").endMetadata().build(); - result = processor.updateResource(actual, desired, context); + result = GenericResourceUpdater.updateResource(actual, desired, context); assertThat(result.getMetadata().getLabels().get("additionalActualKey")).isEqualTo("value"); assertThat(result.getMetadata().getResourceVersion()).isEqualTo("1234"); assertThat(result.getSpec()).isNull(); @@ -85,7 +82,6 @@ void checkNamespaces() { @Test void checkSecret() { - var processor = GenericResourceUpdaterMatcher.updaterMatcherFor(Secret.class); var desired = new SecretBuilder() .withMetadata(new ObjectMeta()) @@ -94,15 +90,14 @@ void checkSecret() { .withMetadata(new ObjectMeta()) .build(); - final var secret = processor.updateResource(actual, desired, context); + final var secret = GenericResourceUpdater.updateResource(actual, desired, context); assertThat(secret.getImmutable()).isTrue(); assertThat(secret.getType()).isEqualTo("Opaque"); assertThat(secret.getData()).containsOnlyKeys("foo"); } @Test - void checkSeviceAccount() { - var processor = GenericResourceUpdaterMatcher.updaterMatcherFor(ServiceAccount.class); + void checkServiceAccount() { var desired = new ServiceAccountBuilder() .withMetadata(new ObjectMetaBuilder().addToLabels("new", "label").build()) .build(); @@ -111,7 +106,7 @@ void checkSeviceAccount() { .withImagePullSecrets(new LocalObjectReferenceBuilder().withName("secret").build()) .build(); - final var serviceAccount = processor.updateResource(actual, desired, context); + final var serviceAccount = GenericResourceUpdater.updateResource(actual, desired, context); assertThat(serviceAccount.getMetadata().getLabels()) .isEqualTo(Map.of("a", "label", "new", "label")); assertThat(serviceAccount.getImagePullSecrets()).isNullOrEmpty(); @@ -119,7 +114,7 @@ void checkSeviceAccount() { Deployment createDeployment() { return ReconcilerUtils.loadYaml( - Deployment.class, GenericResourceUpdaterMatcherTest.class, "nginx-deployment.yaml"); + Deployment.class, GenericResourceUpdaterTest.class, "nginx-deployment.yaml"); } } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/SSABasedGenericKubernetesResourceMatcherTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/SSABasedGenericKubernetesResourceMatcherTest.java index bfbd7eacbb..f30b6949fa 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/SSABasedGenericKubernetesResourceMatcherTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/kubernetes/SSABasedGenericKubernetesResourceMatcherTest.java @@ -1,5 +1,7 @@ package io.javaoperatorsdk.operator.processing.dependent.kubernetes; +import java.util.HashMap; +import java.util.List; import java.util.Map; import org.junit.jupiter.api.BeforeEach; @@ -120,6 +122,48 @@ void addedLabelInDesiredMakesMatchFail() { assertThat(matcher.matches(actualConfigMap, desiredConfigMap, mockedContext)).isFalse(); } + @Test + @SuppressWarnings("unchecked") + void sortListItemsTest() { + var nestedMap1 = new HashMap(); + nestedMap1.put("z", 26); + nestedMap1.put("y", 25); + + var nestedMap2 = new HashMap(); + nestedMap2.put("b", 26); + nestedMap2.put("c", 25); + nestedMap2.put("a", 24); + + var unsortedListItems = List.of(1, nestedMap1, nestedMap2); + var sortedListItems = matcher.sortListItems(unsortedListItems); + assertThat(sortedListItems).element(0).isEqualTo(1); + + var sortedNestedMap1 = (Map) sortedListItems.get(1); + assertThat(sortedNestedMap1.keySet()).containsExactly("y", "z"); + + var sortedNestedMap2 = (Map) sortedListItems.get(2); + assertThat(sortedNestedMap2.keySet()).containsExactly("a", "b", "c"); + } + + @Test + @SuppressWarnings("unchecked") + void testSortMapWithNestedMap() { + var nestedMap = new HashMap(); + nestedMap.put("z", 26); + nestedMap.put("y", 25); + + var unsortedMap = new HashMap(); + unsortedMap.put("b", nestedMap); + unsortedMap.put("a", 1); + unsortedMap.put("c", 2); + + var sortedMap = matcher.sortMap(unsortedMap); + assertThat(sortedMap.keySet()).containsExactly("a", "b", "c"); + + var sortedNestedMap = (Map) sortedMap.get("b"); + assertThat(sortedNestedMap.keySet()).containsExactly("y", "z"); + } + @ParameterizedTest @ValueSource(strings = {"sample-sts-volumeclaimtemplates-desired.yaml", "sample-sts-volumeclaimtemplates-desired-with-status.yaml", diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/AbstractWorkflowExecutorTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/AbstractWorkflowExecutorTest.java index 941c3fa434..970e40eff6 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/AbstractWorkflowExecutorTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/AbstractWorkflowExecutorTest.java @@ -3,18 +3,24 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Optional; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; import io.javaoperatorsdk.operator.api.reconciler.dependent.Deleter; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; import io.javaoperatorsdk.operator.api.reconciler.dependent.GarbageCollected; import io.javaoperatorsdk.operator.api.reconciler.dependent.ReconcileResult; import io.javaoperatorsdk.operator.processing.dependent.Creator; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; +import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + public class AbstractWorkflowExecutorTest { public static final String VALUE = "value"; @@ -35,11 +41,8 @@ public class AbstractWorkflowExecutorTest { public class TestDependent extends KubernetesDependentResource { - private final String name; - public TestDependent(String name) { - super(ConfigMap.class); - this.name = name; + super(ConfigMap.class, name); } @Override @@ -50,9 +53,17 @@ public ReconcileResult reconcile(TestCustomResource primary, .resourceCreated(new ConfigMapBuilder().addToBinaryData("key", VALUE).build()); } + @Override + public synchronized Optional> eventSource( + EventSourceContext context) { + var mockIES = mock(InformerEventSource.class); + when(mockIES.name()).thenReturn(name); + return Optional.of(mockIES); + } + @Override public String toString() { - return name; + return name(); } } @@ -110,6 +121,11 @@ public Class resourceType() { return String.class; } + @Override + public String name() { + return name; + } + @Override public String toString() { return name; diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/CRDPresentActivationConditionTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/CRDPresentActivationConditionTest.java new file mode 100644 index 0000000000..58990214a3 --- /dev/null +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/CRDPresentActivationConditionTest.java @@ -0,0 +1,91 @@ +package io.javaoperatorsdk.operator.processing.dependent.workflow; + +import java.time.Duration; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; +import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class CRDPresentActivationConditionTest { + + public static final int TEST_CHECK_INTERVAL = 50; + public static final int TEST_CHECK_INTERVAL_WITH_SLACK = TEST_CHECK_INTERVAL + 10; + private final CRDPresentActivationCondition.CRDPresentChecker checkerMock = + mock(CRDPresentActivationCondition.CRDPresentChecker.class); + private final CRDPresentActivationCondition condition = + new CRDPresentActivationCondition(checkerMock, 2, + Duration.ofMillis(TEST_CHECK_INTERVAL)); + private final DependentResource dr = + mock(DependentResource.class); + private final Context context = mock(Context.class); + + + @BeforeEach + void setup() { + CRDPresentActivationCondition.clearState(); + when(checkerMock.checkIfCRDPresent(any(), any())).thenReturn(false); + when(dr.resourceType()).thenReturn(TestCustomResource.class); + } + + + @Test + void checkCRDIfNotCheckedBefore() { + when(checkerMock.checkIfCRDPresent(any(),any())).thenReturn(true); + + assertThat(condition.isMet(dr,null,context)).isTrue(); + verify(checkerMock, times(1)).checkIfCRDPresent(any(),any()); + } + + @Test + void instantMetCallSkipsApiCall() { + condition.isMet(dr, null, context); + verify(checkerMock, times(1)).checkIfCRDPresent(any(), any()); + + condition.isMet(dr, null, context); + verify(checkerMock, times(1)).checkIfCRDPresent(any(), any()); + } + + @Test + void intervalExpiredAPICheckedAgain() throws InterruptedException { + condition.isMet(dr, null, context); + verify(checkerMock, times(1)).checkIfCRDPresent(any(), any()); + + Thread.sleep(TEST_CHECK_INTERVAL_WITH_SLACK); + + condition.isMet(dr, null, context); + verify(checkerMock, times(2)).checkIfCRDPresent(any(), any()); + } + + @Test + void crdIsNotCheckedAnymoreIfIfOnceFound() throws InterruptedException { + when(checkerMock.checkIfCRDPresent(any(),any())).thenReturn(true); + + condition.isMet(dr,null,context); + verify(checkerMock, times(1)).checkIfCRDPresent(any(),any()); + + Thread.sleep(TEST_CHECK_INTERVAL_WITH_SLACK); + + condition.isMet(dr,null,context); + verify(checkerMock, times(1)).checkIfCRDPresent(any(),any()); + } + + @Test + void crdNotCheckedAnymoreIfCountExpires() throws InterruptedException { + condition.isMet(dr, null, context); + Thread.sleep(TEST_CHECK_INTERVAL_WITH_SLACK); + condition.isMet(dr, null, context); + Thread.sleep(TEST_CHECK_INTERVAL_WITH_SLACK); + condition.isMet(dr, null, context); + + verify(checkerMock, times(2)).checkIfCRDPresent(any(), any()); + } + +} diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ExecutionAssert.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ExecutionAssert.java index 095b090208..d857c0e9dd 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ExecutionAssert.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ExecutionAssert.java @@ -21,12 +21,13 @@ public static ExecutionAssert assertThat(List actual) { public ExecutionAssert reconciled(DependentResource... dependentResources) { for (int i = 0; i < dependentResources.length; i++) { - var rr = getReconcileRecordFor(dependentResources[i]); + final DependentResource dr = dependentResources[i]; + var rr = getReconcileRecordFor(dr); if (rr.isEmpty()) { - failWithMessage("Resource not reconciled: %s with index %d", dependentResources, i); + failWithMessage("Resource not reconciled: %s with index %d", dr, i); } else { if (rr.get().isDeleted()) { - failWithMessage("Resource deleted: %s with index %d", dependentResources, i); + failWithMessage("Resource deleted: %s with index %d", dr, i); } } } @@ -35,12 +36,13 @@ public ExecutionAssert reconciled(DependentResource... dependentResources) public ExecutionAssert deleted(DependentResource... dependentResources) { for (int i = 0; i < dependentResources.length; i++) { - var rr = getReconcileRecordFor(dependentResources[i]); + final DependentResource dr = dependentResources[i]; + var rr = getReconcileRecordFor(dr); if (rr.isEmpty()) { - failWithMessage("Resource not reconciled: %s with index %d", dependentResources, i); + failWithMessage("Resource not reconciled: %s with index %d", dr, i); } else { if (!rr.get().isDeleted()) { - failWithMessage("Resource not deleted: %s with index %d", dependentResources, i); + failWithMessage("Resource not deleted: %s with index %d", dr, i); } } } @@ -75,17 +77,18 @@ public ExecutionAssert reconciledInOrder(DependentResource... dependentRes public ExecutionAssert notReconciled(DependentResource... dependentResources) { for (int i = 0; i < dependentResources.length; i++) { - if (getActualDependentResources().contains(dependentResources[i])) { - failWithMessage("Resource was reconciled: %s with index %d", dependentResources, i); + final DependentResource dr = dependentResources[i]; + if (getActualDependentResources().contains(dr)) { + failWithMessage("Resource was reconciled: %s with index %d", dr, i); } } return this; } private void checkIfReconciled(int i, DependentResource[] dependentResources) { - if (!getActualDependentResources().contains(dependentResources[i])) { - failWithMessage("Dependent resource: %s, not reconciled on place %d", dependentResources[i], - i); + final DependentResource dr = dependentResources[i]; + if (!getActualDependentResources().contains(dr)) { + failWithMessage("Dependent resource: %s, not reconciled on place %d", dr, i); } } } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ManagedWorkflowTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ManagedWorkflowTest.java index 649e0c3050..e634a368d7 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ManagedWorkflowTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ManagedWorkflowTest.java @@ -1,12 +1,14 @@ package io.javaoperatorsdk.operator.processing.dependent.workflow; import java.util.List; +import java.util.Optional; import org.junit.jupiter.api.Test; import io.javaoperatorsdk.operator.api.config.BaseConfigurationService; 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.api.reconciler.dependent.Deleter; import io.javaoperatorsdk.operator.api.reconciler.dependent.GarbageCollected; @@ -60,9 +62,25 @@ void isCleanerIfHasDeleter() { @SuppressWarnings("unchecked") ManagedWorkflow managedWorkflow(DependentResourceSpec... specs) { final var configuration = mock(ControllerConfiguration.class); - final var specList = List.of(specs); - when(configuration.getDependentResources()).thenReturn(specList); + var ws = new WorkflowSpec() { + @Override + public List getDependentResourceSpecs() { + return List.of(specs); + } + + @Override + public boolean isExplicitInvocation() { + return false; + } + + @Override + public boolean handleExceptionsInReconciler() { + return false; + } + }; + when(configuration.getWorkflowSpec()).thenReturn(Optional.of(ws)); + return new BaseConfigurationService().getWorkflowFactory() .workflowFor(configuration); } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ManagedWorkflowTestUtils.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ManagedWorkflowTestUtils.java index b314b5b112..ae0731b8f5 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ManagedWorkflowTestUtils.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/ManagedWorkflowTestUtils.java @@ -11,9 +11,7 @@ import io.javaoperatorsdk.operator.processing.dependent.EmptyTestDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.withSettings; +import static org.mockito.Mockito.*; @SuppressWarnings("rawtypes") public class ManagedWorkflowTestUtils { diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowBuilderTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowBuilderTest.java index 9a61931a61..b41ee430f7 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowBuilderTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowBuilderTest.java @@ -13,8 +13,10 @@ class WorkflowBuilderTest { @Test void workflowIsCleanerIfAtLeastOneDRIsCleaner() { var dr = mock(DependentResource.class); + when(dr.name()).thenReturn("dr"); var deleter = mock(DependentResource.class); when(deleter.isDeletable()).thenReturn(true); + when(deleter.name()).thenReturn("deleter"); var workflow = new WorkflowBuilder() .addDependentResource(deleter) diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowCleanupExecutorTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowCleanupExecutorTest.java index 461a043862..878cec419c 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowCleanupExecutorTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowCleanupExecutorTest.java @@ -14,7 +14,7 @@ import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; -import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.ManagedDependentResourceContext; +import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.ManagedWorkflowAndDependentResourceContext; import io.javaoperatorsdk.operator.processing.event.EventSourceRetriever; import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; @@ -44,8 +44,8 @@ void setup() { when(eventSourceContextMock.getControllerConfiguration()).thenReturn(mockControllerConfig); when(mockControllerConfig.getConfigurationService()) .thenReturn(mock(ConfigurationService.class)); - when(mockContext.managedDependentResourceContext()) - .thenReturn(mock(ManagedDependentResourceContext.class)); + when(mockContext.managedWorkflowAndDependentResourceContext()) + .thenReturn(mock(ManagedWorkflowAndDependentResourceContext.class)); when(mockContext.getWorkflowExecutorService()).thenReturn(executorService); when(mockContext.eventSourceRetriever()).thenReturn(eventSourceRetrieverMock); } @@ -54,9 +54,9 @@ void setup() { void cleanUpDiamondWorkflow() { var workflow = new WorkflowBuilder() .addDependentResource(dd1) - .addDependentResource(dr1).dependsOn(dd1) - .addDependentResource(dd2).dependsOn(dd1) - .addDependentResource(dd3).dependsOn(dr1, dd2) + .addDependentResourceAndConfigure(dr1).dependsOn(dd1) + .addDependentResourceAndConfigure(dd2).dependsOn(dd1) + .addDependentResourceAndConfigure(dd3).dependsOn(dr1, dd2) .build(); var res = workflow.cleanup(new TestCustomResource(), mockContext); @@ -73,9 +73,9 @@ void cleanUpDiamondWorkflow() { void dontDeleteIfDependentErrored() { var workflow = new WorkflowBuilder() .addDependentResource(dd1) - .addDependentResource(dd2).dependsOn(dd1) - .addDependentResource(dd3).dependsOn(dd2) - .addDependentResource(errorDD).dependsOn(dd2) + .addDependentResourceAndConfigure(dd2).dependsOn(dd1) + .addDependentResourceAndConfigure(dd3).dependsOn(dd2) + .addDependentResourceAndConfigure(errorDD).dependsOn(dd2) .withThrowExceptionFurther(false) .build(); @@ -95,7 +95,8 @@ void dontDeleteIfDependentErrored() { void cleanupConditionTrivialCase() { var workflow = new WorkflowBuilder() .addDependentResource(dd1) - .addDependentResource(dd2).dependsOn(dd1).withDeletePostcondition(notMetCondition) + .addDependentResourceAndConfigure(dd2).dependsOn(dd1) + .withDeletePostcondition(notMetCondition) .build(); var res = workflow.cleanup(new TestCustomResource(), mockContext); @@ -110,7 +111,7 @@ void cleanupConditionTrivialCase() { void cleanupConditionMet() { var workflow = new WorkflowBuilder() .addDependentResource(dd1) - .addDependentResource(dd2).dependsOn(dd1).withDeletePostcondition(metCondition) + .addDependentResourceAndConfigure(dd2).dependsOn(dd1).withDeletePostcondition(metCondition) .build(); var res = workflow.cleanup(new TestCustomResource(), mockContext); @@ -126,9 +127,10 @@ void cleanupConditionMet() { void cleanupConditionDiamondWorkflow() { var workflow = new WorkflowBuilder() .addDependentResource(dd1) - .addDependentResource(dd2).dependsOn(dd1) - .addDependentResource(dd3).dependsOn(dd1).withDeletePostcondition(notMetCondition) - .addDependentResource(dd4).dependsOn(dd2, dd3) + .addDependentResourceAndConfigure(dd2).dependsOn(dd1) + .addDependentResourceAndConfigure(dd3).dependsOn(dd1) + .withDeletePostcondition(notMetCondition) + .addDependentResourceAndConfigure(dd4).dependsOn(dd2, dd3) .build(); var res = workflow.cleanup(new TestCustomResource(), mockContext); @@ -162,10 +164,10 @@ void dontDeleteIfGarbageCollected() { void ifDependentActiveDependentNormallyDeleted() { var workflow = new WorkflowBuilder() .addDependentResource(dd1) - .addDependentResource(dd2).dependsOn(dd1) - .addDependentResource(dd3).dependsOn(dd1) + .addDependentResourceAndConfigure(dd2).dependsOn(dd1) + .addDependentResourceAndConfigure(dd3).dependsOn(dd1) .withActivationCondition(metCondition) - .addDependentResource(dd4).dependsOn(dd2, dd3) + .addDependentResourceAndConfigure(dd4).dependsOn(dd2, dd3) .build(); var res = workflow.cleanup(new TestCustomResource(), mockContext); @@ -182,11 +184,11 @@ void ifDependentActiveDependentNormallyDeleted() { void ifDependentActiveDeletePostConditionIsChecked() { var workflow = new WorkflowBuilder() .addDependentResource(dd1) - .addDependentResource(dd2).dependsOn(dd1) - .addDependentResource(dd3).dependsOn(dd1) + .addDependentResourceAndConfigure(dd2).dependsOn(dd1) + .addDependentResourceAndConfigure(dd3).dependsOn(dd1) .withDeletePostcondition(notMetCondition) .withActivationCondition(metCondition) - .addDependentResource(dd4).dependsOn(dd2, dd3) + .addDependentResourceAndConfigure(dd4).dependsOn(dd2, dd3) .build(); var res = workflow.cleanup(new TestCustomResource(), mockContext); @@ -206,10 +208,10 @@ void ifDependentActiveDeletePostConditionIsChecked() { void ifDependentInactiveDeleteIsNotCalled() { var workflow = new WorkflowBuilder() .addDependentResource(dd1) - .addDependentResource(dd2).dependsOn(dd1) - .addDependentResource(dd3).dependsOn(dd1) + .addDependentResourceAndConfigure(dd2).dependsOn(dd1) + .addDependentResourceAndConfigure(dd3).dependsOn(dd1) .withActivationCondition(notMetCondition) - .addDependentResource(dd4).dependsOn(dd2, dd3) + .addDependentResourceAndConfigure(dd4).dependsOn(dd2, dd3) .build(); var res = workflow.cleanup(new TestCustomResource(), mockContext); @@ -225,11 +227,11 @@ void ifDependentInactiveDeleteIsNotCalled() { void ifDependentInactiveDeletePostConditionNotChecked() { var workflow = new WorkflowBuilder() .addDependentResource(dd1) - .addDependentResource(dd2).dependsOn(dd1) - .addDependentResource(dd3).dependsOn(dd1) + .addDependentResourceAndConfigure(dd2).dependsOn(dd1) + .addDependentResourceAndConfigure(dd3).dependsOn(dd1) .withDeletePostcondition(notMetCondition) .withActivationCondition(notMetCondition) - .addDependentResource(dd4).dependsOn(dd2, dd3) + .addDependentResourceAndConfigure(dd4).dependsOn(dd2, dd3) .build(); var res = workflow.cleanup(new TestCustomResource(), mockContext); @@ -243,7 +245,7 @@ void ifDependentInactiveDeletePostConditionNotChecked() { @Test void singleInactiveDependent() { var workflow = new WorkflowBuilder() - .addDependentResource(dd1) + .addDependentResourceAndConfigure(dd1) .withActivationCondition(notMetCondition) .build(); diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowReconcileExecutorTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowReconcileExecutorTest.java index d90e8d6d97..0aa93fb0f9 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowReconcileExecutorTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowReconcileExecutorTest.java @@ -6,18 +6,25 @@ import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.HasMetadata; import io.javaoperatorsdk.operator.AggregatedOperatorException; import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.ManagedDependentResourceContext; +import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; +import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.ManagedWorkflowAndDependentResourceContext; import io.javaoperatorsdk.operator.processing.event.EventSourceRetriever; import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; import static io.javaoperatorsdk.operator.processing.dependent.workflow.ExecutionAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; class WorkflowReconcileExecutorTest extends AbstractWorkflowExecutorTest { + private static final Logger log = LoggerFactory.getLogger(WorkflowReconcileExecutorTest.class); @SuppressWarnings("unchecked") Context mockContext = spy(Context.class); @@ -27,8 +34,11 @@ class WorkflowReconcileExecutorTest extends AbstractWorkflowExecutorTest { TestDependent dr4 = new TestDependent("DR_4"); @BeforeEach - void setup() { - when(mockContext.managedDependentResourceContext()).thenReturn(mock(ManagedDependentResourceContext.class)); + @SuppressWarnings("unchecked") + void setup(TestInfo testInfo) { + log.debug("==> Starting test {}", testInfo.getDisplayName()); + when(mockContext.managedWorkflowAndDependentResourceContext()) + .thenReturn(mock(ManagedWorkflowAndDependentResourceContext.class)); when(mockContext.getWorkflowExecutorService()).thenReturn(executorService); when(mockContext.eventSourceRetriever()).thenReturn(mock(EventSourceRetriever.class)); } @@ -51,7 +61,7 @@ void reconcileTopLevelResources() { void reconciliationWithSimpleDependsOn() { var workflow = new WorkflowBuilder() .addDependentResource(dr1) - .addDependentResource(dr2).dependsOn(dr1) + .addDependentResourceAndConfigure(dr2).dependsOn(dr1) .build(); var res = workflow.reconcile(new TestCustomResource(), mockContext); @@ -68,8 +78,8 @@ void reconciliationWithTwoTheDependsOns() { var workflow = new WorkflowBuilder() .addDependentResource(dr1) - .addDependentResource(dr2).dependsOn(dr1) - .addDependentResource(dr3).dependsOn(dr1) + .addDependentResourceAndConfigure(dr2).dependsOn(dr1) + .addDependentResourceAndConfigure(dr3).dependsOn(dr1) .build(); var res = workflow.reconcile(new TestCustomResource(), mockContext); @@ -86,9 +96,9 @@ void reconciliationWithTwoTheDependsOns() { void diamondShareWorkflowReconcile() { var workflow = new WorkflowBuilder() .addDependentResource(dr1) - .addDependentResource(dr2).dependsOn(dr1) - .addDependentResource(dr3).dependsOn(dr1) - .addDependentResource(dr4).dependsOn(dr3).dependsOn(dr2) + .addDependentResourceAndConfigure(dr2).dependsOn(dr1) + .addDependentResourceAndConfigure(dr3).dependsOn(dr1) + .addDependentResourceAndConfigure(dr4).dependsOn(dr3).dependsOn(dr2) .build(); var res = workflow.reconcile(new TestCustomResource(), mockContext); @@ -126,8 +136,8 @@ void exceptionHandlingSimpleCases() { void dependentsOnErroredResourceNotReconciled() { var workflow = new WorkflowBuilder() .addDependentResource(dr1) - .addDependentResource(drError).dependsOn(dr1) - .addDependentResource(dr2).dependsOn(drError) + .addDependentResourceAndConfigure(drError).dependsOn(dr1) + .addDependentResourceAndConfigure(dr2).dependsOn(drError) .withThrowExceptionFurther(false) .build(); @@ -146,9 +156,9 @@ void oneBranchErrorsOtherCompletes() { var workflow = new WorkflowBuilder() .addDependentResource(dr1) - .addDependentResource(drError).dependsOn(dr1) - .addDependentResource(dr2).dependsOn(dr1) - .addDependentResource(dr3).dependsOn(dr2) + .addDependentResourceAndConfigure(drError).dependsOn(dr1) + .addDependentResourceAndConfigure(dr2).dependsOn(dr1) + .addDependentResourceAndConfigure(dr3).dependsOn(dr2) .withThrowExceptionFurther(false) .build(); @@ -167,7 +177,7 @@ void onlyOneDependsOnErroredResourceNotReconciled() { var workflow = new WorkflowBuilder() .addDependentResource(dr1) .addDependentResource(drError) - .addDependentResource(dr2).dependsOn(drError, dr1) + .addDependentResourceAndConfigure(dr2).dependsOn(drError, dr1) .withThrowExceptionFurther(false) .build(); @@ -183,10 +193,20 @@ void onlyOneDependsOnErroredResourceNotReconciled() { @Test void simpleReconcileCondition() { + final var result = "Some error message"; + final var unmetWithResult = new DetailedCondition() { + @Override + public Result detailedIsMet( + DependentResource dependentResource, + TestCustomResource primary, Context context) { + return Result.withResult(false, result); + } + }; + var workflow = new WorkflowBuilder() - .addDependentResource(dr1).withReconcilePrecondition(notMetCondition) - .addDependentResource(dr2).withReconcilePrecondition(metCondition) - .addDependentResource(drDeleter).withReconcilePrecondition(notMetCondition) + .addDependentResourceAndConfigure(dr1).withReconcilePrecondition(unmetWithResult) + .addDependentResourceAndConfigure(dr2).withReconcilePrecondition(metCondition) + .addDependentResourceAndConfigure(drDeleter).withReconcilePrecondition(notMetCondition) .build(); var res = workflow.reconcile(new TestCustomResource(), mockContext); @@ -195,6 +215,8 @@ void simpleReconcileCondition() { Assertions.assertThat(res.getErroredDependents()).isEmpty(); Assertions.assertThat(res.getReconciledDependents()).containsExactlyInAnyOrder(dr2); Assertions.assertThat(res.getNotReadyDependents()).isEmpty(); + res.getDependentConditionResult(dr1, Condition.Type.RECONCILE, String.class) + .ifPresentOrElse(s -> assertEquals(result, s), org.junit.jupiter.api.Assertions::fail); } @@ -202,8 +224,8 @@ void simpleReconcileCondition() { void triangleOnceConditionNotMet() { var workflow = new WorkflowBuilder() .addDependentResource(dr1) - .addDependentResource(dr2).dependsOn(dr1) - .addDependentResource(drDeleter).withReconcilePrecondition(notMetCondition) + .addDependentResourceAndConfigure(dr2).dependsOn(dr1) + .addDependentResourceAndConfigure(drDeleter).withReconcilePrecondition(notMetCondition) .dependsOn(dr1) .build(); @@ -221,11 +243,11 @@ void reconcileConditionTransitiveDelete() { var workflow = new WorkflowBuilder() .addDependentResource(dr1) - .addDependentResource(dr2).dependsOn(dr1) + .addDependentResourceAndConfigure(dr2).dependsOn(dr1) .withReconcilePrecondition(notMetCondition) - .addDependentResource(drDeleter).dependsOn(dr2) + .addDependentResourceAndConfigure(drDeleter).dependsOn(dr2) .withReconcilePrecondition(metCondition) - .addDependentResource(drDeleter2).dependsOn(drDeleter) + .addDependentResourceAndConfigure(drDeleter2).dependsOn(drDeleter) .withReconcilePrecondition(metCondition) .build(); @@ -247,8 +269,8 @@ void reconcileConditionAlsoErrorDependsOn() { var workflow = new WorkflowBuilder() .addDependentResource(drError) - .addDependentResource(drDeleter).withReconcilePrecondition(notMetCondition) - .addDependentResource(drDeleter2).dependsOn(drError, drDeleter) + .addDependentResourceAndConfigure(drDeleter).withReconcilePrecondition(notMetCondition) + .addDependentResourceAndConfigure(drDeleter2).dependsOn(drError, drDeleter) .withReconcilePrecondition(metCondition) .withThrowExceptionFurther(false) .build(); @@ -270,8 +292,8 @@ void reconcileConditionAlsoErrorDependsOn() { void oneDependsOnConditionNotMet() { var workflow = new WorkflowBuilder() .addDependentResource(dr1) - .addDependentResource(dr2).withReconcilePrecondition(notMetCondition) - .addDependentResource(drDeleter).dependsOn(dr1, dr2) + .addDependentResourceAndConfigure(dr2).withReconcilePrecondition(notMetCondition) + .addDependentResourceAndConfigure(drDeleter).dependsOn(dr1, dr2) .build(); var res = workflow.reconcile(new TestCustomResource(), mockContext); @@ -289,9 +311,9 @@ void deletedIfReconcileConditionNotMet() { TestDeleterDependent drDeleter2 = new TestDeleterDependent("DR_DELETER_2"); var workflow = new WorkflowBuilder() .addDependentResource(dr1) - .addDependentResource(drDeleter).dependsOn(dr1) + .addDependentResourceAndConfigure(drDeleter).dependsOn(dr1) .withReconcilePrecondition(notMetCondition) - .addDependentResource(drDeleter2).dependsOn(dr1, drDeleter) + .addDependentResourceAndConfigure(drDeleter2).dependsOn(dr1, drDeleter) .build(); var res = workflow.reconcile(new TestCustomResource(), mockContext); @@ -313,11 +335,11 @@ void deleteDoneInReverseOrder() { var workflow = new WorkflowBuilder() .addDependentResource(dr1) - .addDependentResource(drDeleter).withReconcilePrecondition(notMetCondition) + .addDependentResourceAndConfigure(drDeleter).withReconcilePrecondition(notMetCondition) .dependsOn(dr1) - .addDependentResource(drDeleter2).dependsOn(drDeleter) - .addDependentResource(drDeleter3).dependsOn(drDeleter) - .addDependentResource(drDeleter4).dependsOn(drDeleter3) + .addDependentResourceAndConfigure(drDeleter2).dependsOn(drDeleter) + .addDependentResourceAndConfigure(drDeleter3).dependsOn(drDeleter) + .addDependentResourceAndConfigure(drDeleter4).dependsOn(drDeleter3) .build(); var res = workflow.reconcile(new TestCustomResource(), mockContext); @@ -339,11 +361,11 @@ void diamondDeleteWithPostConditionInMiddle() { TestDeleterDependent drDeleter4 = new TestDeleterDependent("DR_DELETER_4"); var workflow = new WorkflowBuilder() - .addDependentResource(drDeleter).withReconcilePrecondition(notMetCondition) - .addDependentResource(drDeleter2).dependsOn(drDeleter) - .addDependentResource(drDeleter3).dependsOn(drDeleter) + .addDependentResourceAndConfigure(drDeleter).withReconcilePrecondition(notMetCondition) + .addDependentResourceAndConfigure(drDeleter2).dependsOn(drDeleter) + .addDependentResourceAndConfigure(drDeleter3).dependsOn(drDeleter) .withDeletePostcondition(this.notMetCondition) - .addDependentResource(drDeleter4).dependsOn(drDeleter3, drDeleter2) + .addDependentResourceAndConfigure(drDeleter4).dependsOn(drDeleter3, drDeleter2) .build(); var res = workflow.reconcile(new TestCustomResource(), mockContext); @@ -363,10 +385,10 @@ void diamondDeleteErrorInMiddle() { TestDeleterDependent drDeleter3 = new TestDeleterDependent("DR_DELETER_3"); var workflow = new WorkflowBuilder() - .addDependentResource(drDeleter).withReconcilePrecondition(notMetCondition) - .addDependentResource(drDeleter2).dependsOn(drDeleter) - .addDependentResource(errorDD).dependsOn(drDeleter) - .addDependentResource(drDeleter3).dependsOn(errorDD, drDeleter2) + .addDependentResourceAndConfigure(drDeleter).withReconcilePrecondition(notMetCondition) + .addDependentResourceAndConfigure(drDeleter2).dependsOn(drDeleter) + .addDependentResourceAndConfigure(errorDD).dependsOn(drDeleter) + .addDependentResourceAndConfigure(drDeleter3).dependsOn(errorDD, drDeleter2) .withThrowExceptionFurther(false) .build(); @@ -384,8 +406,8 @@ void diamondDeleteErrorInMiddle() { @Test void readyConditionTrivialCase() { var workflow = new WorkflowBuilder() - .addDependentResource(dr1).withReadyPostcondition(metCondition) - .addDependentResource(dr2).dependsOn(dr1) + .addDependentResourceAndConfigure(dr1).withReadyPostcondition(metCondition) + .addDependentResourceAndConfigure(dr2).dependsOn(dr1) .build(); var res = workflow.reconcile(new TestCustomResource(), mockContext); @@ -400,8 +422,8 @@ void readyConditionTrivialCase() { @Test void readyConditionNotMetTrivialCase() { var workflow = new WorkflowBuilder() - .addDependentResource(dr1).withReadyPostcondition(notMetCondition) - .addDependentResource(dr2).dependsOn(dr1) + .addDependentResourceAndConfigure(dr1).withReadyPostcondition(notMetCondition) + .addDependentResourceAndConfigure(dr2).dependsOn(dr1) .build(); var res = workflow.reconcile(new TestCustomResource(), mockContext); @@ -418,9 +440,9 @@ void readyConditionNotMetTrivialCase() { void readyConditionNotMetInOneParent() { var workflow = new WorkflowBuilder() - .addDependentResource(dr1).withReadyPostcondition(notMetCondition) + .addDependentResourceAndConfigure(dr1).withReadyPostcondition(notMetCondition) .addDependentResource(dr2) - .addDependentResource(dr3).dependsOn(dr1, dr2) + .addDependentResourceAndConfigure(dr3).dependsOn(dr1, dr2) .build(); var res = workflow.reconcile(new TestCustomResource(), mockContext); @@ -435,9 +457,11 @@ void readyConditionNotMetInOneParent() { void diamondShareWithReadyCondition() { var workflow = new WorkflowBuilder() .addDependentResource(dr1) - .addDependentResource(dr2).dependsOn(dr1).withReadyPostcondition(notMetCondition) - .addDependentResource(dr3).dependsOn(dr1) - .addDependentResource(dr4).dependsOn(dr2, dr3) + .addDependentResourceAndConfigure(dr2) + .dependsOn(dr1) + .withReadyPostcondition(notMetCondition) + .addDependentResourceAndConfigure(dr3).dependsOn(dr1) + .addDependentResourceAndConfigure(dr4).dependsOn(dr2, dr3) .build(); var res = workflow.reconcile(new TestCustomResource(), mockContext); @@ -455,7 +479,7 @@ void diamondShareWithReadyCondition() { @Test void garbageCollectedResourceIsDeletedIfReconcilePreconditionDoesNotHold() { var workflow = new WorkflowBuilder() - .addDependentResource(gcDeleter).withReconcilePrecondition(notMetCondition) + .addDependentResourceAndConfigure(gcDeleter).withReconcilePrecondition(notMetCondition) .build(); var res = workflow.reconcile(new TestCustomResource(), mockContext); @@ -467,8 +491,8 @@ void garbageCollectedResourceIsDeletedIfReconcilePreconditionDoesNotHold() { @Test void garbageCollectedDeepResourceIsDeletedIfReconcilePreconditionDoesNotHold() { var workflow = new WorkflowBuilder() - .addDependentResource(dr1).withReconcilePrecondition(notMetCondition) - .addDependentResource(gcDeleter).dependsOn(dr1) + .addDependentResourceAndConfigure(dr1).withReconcilePrecondition(notMetCondition) + .addDependentResourceAndConfigure(gcDeleter).dependsOn(dr1) .build(); var res = workflow.reconcile(new TestCustomResource(), mockContext); @@ -480,7 +504,7 @@ void garbageCollectedDeepResourceIsDeletedIfReconcilePreconditionDoesNotHold() { @Test void notReconciledIfActivationConditionNotMet() { var workflow = new WorkflowBuilder() - .addDependentResource(dr1) + .addDependentResourceAndConfigure(dr1) .withActivationCondition(notMetCondition) .addDependentResource(dr2) .build(); @@ -494,10 +518,10 @@ void notReconciledIfActivationConditionNotMet() { @Test void dependentsOnANonActiveDependentNotReconciled() { var workflow = new WorkflowBuilder() - .addDependentResource(dr1) + .addDependentResourceAndConfigure(dr1) .withActivationCondition(notMetCondition) .addDependentResource(dr2) - .addDependentResource(dr3).dependsOn(dr1) + .addDependentResourceAndConfigure(dr3).dependsOn(dr1) .build(); var res = workflow.reconcile(new TestCustomResource(), mockContext); @@ -509,11 +533,11 @@ void dependentsOnANonActiveDependentNotReconciled() { @Test void readyConditionNotCheckedOnNonActiveDependent() { var workflow = new WorkflowBuilder() - .addDependentResource(dr1) + .addDependentResourceAndConfigure(dr1) .withActivationCondition(notMetCondition) .withReadyPostcondition(notMetCondition) .addDependentResource(dr2) - .addDependentResource(dr3).dependsOn(dr1) + .addDependentResourceAndConfigure(dr3).dependsOn(dr1) .build(); var res = workflow.reconcile(new TestCustomResource(), mockContext); @@ -522,11 +546,12 @@ void readyConditionNotCheckedOnNonActiveDependent() { } @Test + @SuppressWarnings("unchecked") void reconcilePreconditionNotCheckedOnNonActiveDependent() { var precondition = mock(Condition.class); var workflow = new WorkflowBuilder() - .addDependentResource(dr1) + .addDependentResourceAndConfigure(dr1) .withActivationCondition(notMetCondition) .withReconcilePrecondition(precondition) .build(); @@ -539,14 +564,14 @@ void reconcilePreconditionNotCheckedOnNonActiveDependent() { @Test void deletesDependentsOfNonActiveDependentButNotTheNonActive() { TestDeleterDependent drDeleter2 = new TestDeleterDependent("DR_DELETER_2"); - TestDeleterDependent drDeleter3 = new TestDeleterDependent("DR_DELETER_2"); + TestDeleterDependent drDeleter3 = new TestDeleterDependent("DR_DELETER_3"); var workflow = new WorkflowBuilder() - .addDependentResource(dr1).withActivationCondition(notMetCondition) - .addDependentResource(drDeleter).dependsOn(dr1) - .addDependentResource(drDeleter2).dependsOn(drDeleter) + .addDependentResourceAndConfigure(dr1).withActivationCondition(notMetCondition) + .addDependentResourceAndConfigure(drDeleter).dependsOn(dr1) + .addDependentResourceAndConfigure(drDeleter2).dependsOn(drDeleter) .withActivationCondition(notMetCondition) - .addDependentResource(drDeleter3).dependsOn(drDeleter2) + .addDependentResourceAndConfigure(drDeleter3).dependsOn(drDeleter2) .build(); var res = workflow.reconcile(new TestCustomResource(), mockContext); @@ -558,14 +583,15 @@ void deletesDependentsOfNonActiveDependentButNotTheNonActive() { } @Test + @SuppressWarnings("unchecked") void activationConditionOnlyCalledOnceOnDeleteDependents() { TestDeleterDependent drDeleter2 = new TestDeleterDependent("DR_DELETER_2"); var condition = mock(Condition.class); when(condition.isMet(any(), any(), any())).thenReturn(false); var workflow = new WorkflowBuilder() - .addDependentResource(drDeleter).withActivationCondition(condition) - .addDependentResource(drDeleter2).dependsOn(drDeleter) + .addDependentResourceAndConfigure(drDeleter).withActivationCondition(condition) + .addDependentResourceAndConfigure(drDeleter2).dependsOn(drDeleter) .build(); workflow.reconcile(new TestCustomResource(), mockContext); @@ -574,4 +600,80 @@ void activationConditionOnlyCalledOnceOnDeleteDependents() { verify(condition, times(1)).isMet(any(), any(), any()); } + + @Test + void resultFromReadyConditionShouldBeAvailableIfExisting() { + final var result = Integer.valueOf(42); + final var resultCondition = new DetailedCondition<>() { + @Override + public Result detailedIsMet(DependentResource dependentResource, + HasMetadata primary, Context context) { + return new Result<>() { + @Override + public Object getDetail() { + return result; + } + + @Override + public boolean isSuccess() { + return false; // force not ready + } + }; + } + }; + var workflow = new WorkflowBuilder() + .addDependentResourceAndConfigure(dr1) + .withReadyPostcondition(resultCondition) + .build(); + + final var reconcileResult = workflow.reconcile(new TestCustomResource(), mockContext); + assertEquals(result, + reconcileResult.getNotReadyDependentResult(dr1, Integer.class).orElseThrow()); + } + + @Test + void shouldThrowIllegalArgumentExceptionIfTypesDoNotMatch() { + final var result = "FOO"; + final var resultCondition = new DetailedCondition<>() { + @Override + public Result detailedIsMet(DependentResource dependentResource, + HasMetadata primary, Context context) { + return new Result<>() { + @Override + public Object getDetail() { + return result; + } + + @Override + public boolean isSuccess() { + return false; // force not ready + } + }; + } + }; + var workflow = new WorkflowBuilder() + .addDependentResourceAndConfigure(dr1) + .withReadyPostcondition(resultCondition) + .build(); + + final var reconcileResult = workflow.reconcile(new TestCustomResource(), mockContext); + final var expectedResultType = Integer.class; + final var e = assertThrows(IllegalArgumentException.class, + () -> reconcileResult.getNotReadyDependentResult(dr1, expectedResultType)); + final var message = e.getMessage(); + assertTrue(message.contains(dr1.name())); + assertTrue(message.contains(expectedResultType.getSimpleName())); + assertTrue(message.contains(result)); + } + + @Test + void shouldReturnEmptyIfNoConditionResultExists() { + var workflow = new WorkflowBuilder() + .addDependentResourceAndConfigure(dr1) + .withReadyPostcondition(notMetCondition) + .build(); + + final var reconcileResult = workflow.reconcile(new TestCustomResource(), mockContext); + assertTrue(reconcileResult.getNotReadyDependentResult(dr1, Integer.class).isEmpty()); + } } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowResultTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowResultTest.java index 48cf3fa75a..ca0b883e99 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowResultTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowResultTest.java @@ -13,11 +13,14 @@ import static org.assertj.core.api.Assertions.assertThat; class WorkflowResultTest { + private final static WorkflowResult.Detail detail = + new WorkflowResult.Detail<>(new RuntimeException(), null, null, null, null, null, false, + false, false); @Test void throwsExceptionWithoutNumberingIfAllDifferentClass() { - var res = new WorkflowResult(Map.of(new DependentA(), new RuntimeException(), - new DependentB(), new RuntimeException())); + var res = new WorkflowResult(Map.of(new DependentA(), detail, + new DependentB(), detail)); try { res.throwAggregateExceptionIfErrorsPresent(); } catch (AggregatedOperatorException e) { @@ -28,8 +31,8 @@ void throwsExceptionWithoutNumberingIfAllDifferentClass() { @Test void numbersDependentClassNamesIfMoreOfSameType() { - var res = new WorkflowResult(Map.of(new DependentA(), new RuntimeException(), - new DependentA(), new RuntimeException())); + var res = new WorkflowResult(Map.of(new DependentA("name1"), detail, + new DependentA("name2"), detail)); try { res.throwAggregateExceptionIfErrorsPresent(); } catch (AggregatedOperatorException e) { @@ -39,6 +42,25 @@ void numbersDependentClassNamesIfMoreOfSameType() { @SuppressWarnings("rawtypes") static class DependentA implements DependentResource { + + private final String name; + + public DependentA() { + this(null); + } + + public DependentA(String name) { + this.name = name; + } + + @Override + public String name() { + if (name == null) { + return DependentResource.super.name(); + } + return name; + } + @Override public ReconcileResult reconcile(HasMetadata primary, Context context) { return null; diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowTest.java index 72ec14ebbf..6d268082f5 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/dependent/workflow/WorkflowTest.java @@ -1,8 +1,6 @@ package io.javaoperatorsdk.operator.processing.dependent.workflow; import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; @@ -14,26 +12,25 @@ import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.withSettings; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.*; @SuppressWarnings("rawtypes") class WorkflowTest { - ExecutorService executorService = Executors.newCachedThreadPool(); - @Test void zeroTopLevelDRShouldThrowException() { - var dr1 = mock(DependentResource.class); - var dr2 = mock(DependentResource.class); - var dr3 = mock(DependentResource.class); + var dr1 = mockDependent("dr1"); + var dr2 = mockDependent("dr2"); + var dr3 = mockDependent("dr3"); var cyclicWorkflowBuilderSetup = new WorkflowBuilder() - .addDependentResource(dr1).dependsOn() - .addDependentResource(dr2).dependsOn(dr1) - .addDependentResource(dr3).dependsOn(dr2) - .addDependentResource(dr1).dependsOn(dr2); + .addDependentResourceAndConfigure(dr1).dependsOn() + .addDependentResourceAndConfigure(dr2).dependsOn(dr1) + .addDependentResourceAndConfigure(dr3).dependsOn(dr2) + .addDependentResourceAndConfigure(dr1).dependsOn(dr2); assertThrows(IllegalStateException.class, cyclicWorkflowBuilderSetup::build); @@ -41,15 +38,15 @@ void zeroTopLevelDRShouldThrowException() { @Test void calculatesTopLevelResources() { - var dr1 = mock(DependentResource.class); - var dr2 = mock(DependentResource.class); - var independentDR = mock(DependentResource.class); + var dr1 = mockDependent("dr1"); + var dr2 = mockDependent("dr2"); + var independentDR = mockDependent("independentDR"); var workflow = new WorkflowBuilder() .addDependentResource(independentDR) .addDependentResource(dr1) - .addDependentResource(dr2).dependsOn(dr1) - .build(); + .addDependentResourceAndConfigure(dr2).dependsOn(dr1) + .buildAsDefaultWorkflow(); Set topResources = workflow.getTopLevelDependentResources().stream() @@ -61,18 +58,18 @@ void calculatesTopLevelResources() { @Test void calculatesBottomLevelResources() { - var dr1 = mock(DependentResource.class); - var dr2 = mock(DependentResource.class); - var independentDR = mock(DependentResource.class); + var dr1 = mockDependent("dr1"); + var dr2 = mockDependent("dr2"); + var independentDR = mockDependent("independentDR"); - Workflow workflow = new WorkflowBuilder() + final var workflow = new WorkflowBuilder() .addDependentResource(independentDR) .addDependentResource(dr1) - .addDependentResource(dr2).dependsOn(dr1) - .build(); + .addDependentResourceAndConfigure(dr2).dependsOn(dr1) + .buildAsDefaultWorkflow(); Set bottomResources = - workflow.getBottomLevelResource().stream() + workflow.getBottomLevelDependentResources().stream() .map(DependentResourceNode::getDependentResource) .collect(Collectors.toSet()); @@ -98,4 +95,11 @@ void isDeletableShouldWork() { GarbageCollected.class)); assertFalse(DefaultWorkflow.isDeletable(dr.getClass())); } + + static DependentResource mockDependent(String name) { + var res = mock(DependentResource.class); + when(res.name()).thenReturn(name); + return res; + } + } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/EventProcessorTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/EventProcessorTest.java index 93e58a55c6..9f7e390c0a 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/EventProcessorTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/EventProcessorTest.java @@ -18,16 +18,16 @@ import io.javaoperatorsdk.operator.api.config.BaseConfigurationService; import io.javaoperatorsdk.operator.api.config.ConfigurationService; import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; -import io.javaoperatorsdk.operator.api.config.RetryConfiguration; import io.javaoperatorsdk.operator.api.monitoring.Metrics; import io.javaoperatorsdk.operator.processing.event.rate.LinearRateLimiter; import io.javaoperatorsdk.operator.processing.event.rate.RateLimiter; import io.javaoperatorsdk.operator.processing.event.rate.RateLimiter.RateLimitState; -import io.javaoperatorsdk.operator.processing.event.source.controller.ControllerResourceEventSource; +import io.javaoperatorsdk.operator.processing.event.source.controller.ControllerEventSource; import io.javaoperatorsdk.operator.processing.event.source.controller.ResourceAction; import io.javaoperatorsdk.operator.processing.event.source.controller.ResourceEvent; import io.javaoperatorsdk.operator.processing.event.source.timer.TimerEventSource; import io.javaoperatorsdk.operator.processing.retry.GenericRetry; +import io.javaoperatorsdk.operator.processing.retry.GradualRetry; import io.javaoperatorsdk.operator.processing.retry.Retry; import io.javaoperatorsdk.operator.processing.retry.RetryExecution; import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; @@ -66,8 +66,8 @@ class EventProcessorTest { mock(ReconciliationDispatcher.class); private final EventSourceManager eventSourceManagerMock = mock(EventSourceManager.class); private final TimerEventSource retryTimerEventSourceMock = mock(TimerEventSource.class); - private final ControllerResourceEventSource controllerResourceEventSourceMock = - mock(ControllerResourceEventSource.class); + private final ControllerEventSource controllerEventSourceMock = + mock(ControllerEventSource.class); private final Metrics metricsMock = mock(Metrics.class); private EventProcessor eventProcessor; private EventProcessor eventProcessorWithRetry; @@ -75,8 +75,8 @@ class EventProcessorTest { @BeforeEach void setup() { - when(eventSourceManagerMock.getControllerResourceEventSource()) - .thenReturn(controllerResourceEventSourceMock); + when(eventSourceManagerMock.getControllerEventSource()) + .thenReturn(controllerEventSourceMock); eventProcessor = spy(new EventProcessor(controllerConfiguration(null, rateLimiterMock), reconciliationDispatcherMock, @@ -103,7 +103,7 @@ void dispatchesEventsIfNoExecutionInProgress() { @Test void skipProcessingIfLatestCustomResourceNotInCache() { Event event = prepareCREvent(); - when(controllerResourceEventSourceMock.get(event.getRelatedCustomResourceID())) + when(controllerEventSourceMock.get(event.getRelatedCustomResourceID())) .thenReturn(Optional.empty()); eventProcessor.handleEvent(event); @@ -135,7 +135,7 @@ void schedulesAnEventRetryOnException() { verify(retryTimerEventSourceMock, times(1)) .scheduleOnce(eq(ResourceID.fromResource(customResource)), - eq(RetryConfiguration.DEFAULT_INITIAL_INTERVAL)); + eq(GradualRetry.DEFAULT_INITIAL_INTERVAL)); } @Test @@ -167,7 +167,7 @@ void executesTheControllerInstantlyAfterErrorIfNewEventsReceived() { assertThat(allValues).hasSize(2); verify(retryTimerEventSourceMock, never()) .scheduleOnce(eq(ResourceID.fromResource(customResource)), - eq(RetryConfiguration.DEFAULT_INITIAL_INTERVAL)); + eq(GradualRetry.DEFAULT_INITIAL_INTERVAL)); } @Test @@ -275,7 +275,7 @@ void startProcessedMarkedEventReceivedBefore() { LinearRateLimiter.deactivatedRateLimiter()), reconciliationDispatcherMock, eventSourceManagerMock, metricsMock)); - when(controllerResourceEventSourceMock.get(eq(crID))) + when(controllerEventSourceMock.get(eq(crID))) .thenReturn(Optional.of(testCustomResource())); eventProcessor.handleEvent(new Event(crID)); @@ -287,21 +287,6 @@ void startProcessedMarkedEventReceivedBefore() { verify(metricsMock, times(1)).reconcileCustomResource(any(HasMetadata.class), isNull(), any()); } - @Test - void updatesEventSourceHandlerIfResourceUpdated() { - TestCustomResource customResource = testCustomResource(); - ExecutionScope executionScope = - new ExecutionScope(null).setResource(customResource); - PostExecutionControl postExecutionControl = - PostExecutionControl.customResourceUpdated(customResource); - - eventProcessorWithRetry.eventProcessingFinished(executionScope, postExecutionControl); - - - verify(controllerResourceEventSourceMock, times(1)).handleRecentResourceUpdate(any(), any(), - any()); - } - @Test void notUpdatesEventSourceHandlerIfResourceUpdated() { TestCustomResource customResource = testCustomResource(); @@ -312,7 +297,7 @@ void notUpdatesEventSourceHandlerIfResourceUpdated() { eventProcessorWithRetry.eventProcessingFinished(executionScope, postExecutionControl); - verify(controllerResourceEventSourceMock, times(0)).handleRecentResourceUpdate(any(), any(), + verify(controllerEventSourceMock, times(0)).handleRecentResourceUpdate(any(), any(), any()); } @@ -367,7 +352,7 @@ void newResourceAfterMissedDeleteEvent() { @Test void rateLimitsReconciliationSubmission() { - // the refresh period value does not matter here + // the refresh defaultPollingPeriod value does not matter here var refreshPeriod = Duration.ofMillis(100); var event = prepareCREvent(); @@ -441,8 +426,8 @@ void executionOfReconciliationShouldNotStartIfProcessorStopped() throws Interrup eventSourceManagerMock, null)); eventProcessor.start(); - eventProcessor.handleEvent(prepareCREvent()); - eventProcessor.handleEvent(prepareCREvent()); + eventProcessor.handleEvent(prepareCREvent(new ResourceID("test1","default"))); + eventProcessor.handleEvent(prepareCREvent(new ResourceID("test1","default"))); eventProcessor.stop(); // wait until both event should be handled @@ -483,7 +468,7 @@ private ResourceEvent prepareCREvent() { } private ResourceEvent prepareCREvent(HasMetadata hasMetadata) { - when(controllerResourceEventSourceMock.get(eq(ResourceID.fromResource(hasMetadata)))) + when(controllerEventSourceMock.get(eq(ResourceID.fromResource(hasMetadata)))) .thenReturn(Optional.of(hasMetadata)); return new ResourceEvent(ResourceAction.UPDATED, ResourceID.fromResource(hasMetadata), hasMetadata); @@ -491,7 +476,7 @@ private ResourceEvent prepareCREvent(HasMetadata hasMetadata) { private ResourceEvent prepareCREvent(ResourceID resourceID) { TestCustomResource customResource = testCustomResource(resourceID); - when(controllerResourceEventSourceMock.get(eq(resourceID))) + when(controllerEventSourceMock.get(eq(resourceID))) .thenReturn(Optional.of(customResource)); return new ResourceEvent(ResourceAction.UPDATED, ResourceID.fromResource(customResource), customResource); diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/EventSourceManagerTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/EventSourceManagerTest.java index b56d79e6ed..9ddb877f07 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/EventSourceManagerTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/EventSourceManagerTest.java @@ -10,12 +10,13 @@ import io.javaoperatorsdk.operator.OperatorException; import io.javaoperatorsdk.operator.api.config.BaseConfigurationService; import io.javaoperatorsdk.operator.api.config.MockControllerConfiguration; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; import io.javaoperatorsdk.operator.processing.Controller; +import io.javaoperatorsdk.operator.processing.event.source.AbstractEventSource; import io.javaoperatorsdk.operator.processing.event.source.EventSource; import io.javaoperatorsdk.operator.processing.event.source.EventSourceStartPriority; -import io.javaoperatorsdk.operator.processing.event.source.controller.ControllerResourceEventSource; +import io.javaoperatorsdk.operator.processing.event.source.controller.ControllerEventSource; import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; import io.javaoperatorsdk.operator.processing.event.source.informer.ManagedInformerEventSource; import io.javaoperatorsdk.operator.processing.event.source.timer.TimerEventSource; @@ -34,10 +35,12 @@ class EventSourceManagerTest { @Test public void registersEventSource() { EventSource eventSource = mock(EventSource.class); + when(eventSource.resourceType()).thenReturn(EventSource.class); + when(eventSource.name()).thenReturn("name1"); eventSourceManager.registerEventSource(eventSource); - Set registeredSources = eventSourceManager.getRegisteredEventSources(); + final var registeredSources = eventSourceManager.getRegisteredEventSources(); assertThat(registeredSources).contains(eventSource); verify(eventSource, times(1)).setEventHandler(any()); @@ -46,7 +49,12 @@ public void registersEventSource() { @Test public void closeShouldCascadeToEventSources() { EventSource eventSource = mock(EventSource.class); + when(eventSource.name()).thenReturn("name1"); + when(eventSource.resourceType()).thenReturn(EventSource.class); + EventSource eventSource2 = mock(TimerEventSource.class); + when(eventSource2.name()).thenReturn("name2"); + when(eventSource2.resourceType()).thenReturn(AbstractEventSource.class); eventSourceManager.registerEventSource(eventSource); eventSourceManager.registerEventSource(eventSource2); @@ -61,8 +69,12 @@ public void closeShouldCascadeToEventSources() { public void startCascadesToEventSources() { EventSource eventSource = mock(EventSource.class); when(eventSource.priority()).thenReturn(EventSourceStartPriority.DEFAULT); + when(eventSource.name()).thenReturn("name1"); + when(eventSource.resourceType()).thenReturn(EventSource.class); EventSource eventSource2 = mock(TimerEventSource.class); when(eventSource2.priority()).thenReturn(EventSourceStartPriority.DEFAULT); + when(eventSource2.name()).thenReturn("name2"); + when(eventSource2.resourceType()).thenReturn(AbstractEventSource.class); eventSourceManager.registerEventSource(eventSource); eventSourceManager.registerEventSource(eventSource2); @@ -74,43 +86,44 @@ public void startCascadesToEventSources() { @Test void retrievingEventSourceForClassShouldWork() { - assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> eventSourceManager.getResourceEventSourceFor(Class.class)); + assertThatExceptionOfType(NoEventSourceForClassException.class) + .isThrownBy(() -> eventSourceManager.getEventSourceFor(Class.class)); // manager is initialized with a controller configured to handle HasMetadata EventSourceManager manager = initManager(); - assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> manager.getResourceEventSourceFor(HasMetadata.class, "unknown_name")); + assertThatExceptionOfType(NoEventSourceForClassException.class) + .isThrownBy(() -> manager.getEventSourceFor(HasMetadata.class, "unknown_name")); ManagedInformerEventSource eventSource = mock(ManagedInformerEventSource.class); when(eventSource.resourceType()).thenReturn(String.class); + when(eventSource.name()).thenReturn("name1"); manager.registerEventSource(eventSource); - var source = manager.getResourceEventSourceFor(String.class); + var source = manager.getEventSourceFor(String.class); assertThat(source).isNotNull(); assertEquals(eventSource, source); } @Test - void shouldNotBePossibleToAddEventSourcesForSameTypeAndName() { + void notPossibleAddEventSourcesForSameName() { EventSourceManager manager = initManager(); final var name = "name1"; ManagedInformerEventSource eventSource = mock(ManagedInformerEventSource.class); + when(eventSource.name()).thenReturn(name); when(eventSource.resourceType()).thenReturn(TestCustomResource.class); - manager.registerEventSource(name, eventSource); + manager.registerEventSource(eventSource); eventSource = mock(ManagedInformerEventSource.class); when(eventSource.resourceType()).thenReturn(TestCustomResource.class); + when(eventSource.name()).thenReturn(name); final var source = eventSource; final var exception = assertThrows(OperatorException.class, - () -> manager.registerEventSource(name, source)); + () -> manager.registerEventSource(source)); final var cause = exception.getCause(); - assertTrue(cause instanceof IllegalArgumentException); - assertThat(cause.getMessage()).contains( - "is already registered for the (io.javaoperatorsdk.operator.sample.simple.TestCustomResource, " - + name + ") class/name combination"); + assertInstanceOf(IllegalArgumentException.class, cause); + assertThat(cause.getMessage()).contains("is already registered with name"); } @Test @@ -119,20 +132,23 @@ void retrievingAnEventSourceWhenMultipleAreRegisteredForATypeShouldRequireAQuali ManagedInformerEventSource eventSource = mock(ManagedInformerEventSource.class); when(eventSource.resourceType()).thenReturn(TestCustomResource.class); - manager.registerEventSource("name1", eventSource); + when(eventSource.name()).thenReturn("name1"); + manager.registerEventSource(eventSource); + ManagedInformerEventSource eventSource2 = mock(ManagedInformerEventSource.class); + when(eventSource2.name()).thenReturn("name2"); when(eventSource2.resourceType()).thenReturn(TestCustomResource.class); - manager.registerEventSource("name2", eventSource2); + manager.registerEventSource(eventSource2); final var exception = assertThrows(IllegalArgumentException.class, - () -> manager.getResourceEventSourceFor(TestCustomResource.class)); + () -> manager.getEventSourceFor(TestCustomResource.class)); assertTrue(exception.getMessage().contains("name1")); assertTrue(exception.getMessage().contains("name2")); - assertEquals(manager.getResourceEventSourceFor(TestCustomResource.class, "name2"), + assertEquals(manager.getEventSourceFor(TestCustomResource.class, "name2"), eventSource2); - assertEquals(manager.getResourceEventSourceFor(TestCustomResource.class, "name1"), + assertEquals(manager.getEventSourceFor(TestCustomResource.class, "name1"), eventSource); } @@ -149,18 +165,19 @@ void changesNamespacesOnControllerAndInformerEventSources() { MockKubernetesClient.client(HasMetadata.class)); EventSources eventSources = spy(new EventSources()); - var controllerResourceEventSourceMock = mock(ControllerResourceEventSource.class); - doReturn(controllerResourceEventSourceMock).when(eventSources).controllerResourceEventSource(); + var controllerResourceEventSourceMock = mock(ControllerEventSource.class); + doReturn(controllerResourceEventSourceMock).when(eventSources).controllerEventSource(); when(controllerResourceEventSourceMock.allowsNamespaceChanges()).thenCallRealMethod(); var manager = new EventSourceManager(controller, eventSources); - InformerConfiguration informerConfigurationMock = mock(InformerConfiguration.class); - when(informerConfigurationMock.followControllerNamespaceChanges()).thenReturn(true); + InformerEventSourceConfiguration eventSourceConfigurationMock = + mock(InformerEventSourceConfiguration.class); InformerEventSource informerEventSource = mock(InformerEventSource.class); + when(informerEventSource.name()).thenReturn("ies"); when(informerEventSource.resourceType()).thenReturn(TestCustomResource.class); - when(informerEventSource.configuration()).thenReturn(informerConfigurationMock); - when(informerEventSource.allowsNamespaceChanges()).thenCallRealMethod(); - manager.registerEventSource("ies", informerEventSource); + when(informerEventSource.configuration()).thenReturn(eventSourceConfigurationMock); + when(informerEventSource.allowsNamespaceChanges()).thenReturn(true); + manager.registerEventSource(informerEventSource); manager.changeNamespaces(Set.of(newNamespaces)); diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/EventSourcesTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/EventSourcesTest.java index ad4faecc64..12f0cc7331 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/EventSourcesTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/EventSourcesTest.java @@ -3,7 +3,6 @@ import java.util.ConcurrentModificationException; import java.util.concurrent.Phaser; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; @@ -17,9 +16,7 @@ import io.javaoperatorsdk.operator.api.reconciler.Reconciler; import io.javaoperatorsdk.operator.processing.Controller; import io.javaoperatorsdk.operator.processing.event.source.EventSource; -import io.javaoperatorsdk.operator.processing.event.source.ResourceEventSource; -import static io.javaoperatorsdk.operator.processing.event.EventSources.RETRY_RESCHEDULE_TIMER_EVENT_SOURCE_NAME; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -35,99 +32,101 @@ class EventSourcesTest { @Test void cannotAddTwoDifferentEventSourcesWithSameName() { final var eventSources = new EventSources(); + var es1 = mock(EventSource.class); + when(es1.name()).thenReturn(EVENT_SOURCE_NAME); + when(es1.resourceType()).thenReturn(EventSource.class); + var es2 = mock(EventSource.class); + when(es2.name()).thenReturn(EVENT_SOURCE_NAME); + when(es2.resourceType()).thenReturn(EventSource.class); + + eventSources.add(es1); assertThrows(IllegalArgumentException.class, () -> { - eventSources.add(new NamedEventSource(mock(EventSource.class), "name")); - eventSources.add(new NamedEventSource(mock(EventSource.class), "name")); + eventSources.add(es2); }); } @Test - void cannotAddTwoEventSourcesWithSameNameUnlessTheyAreEqual() { + void cannotAddTwoEventSourcesWithSame() { final var eventSources = new EventSources(); final var source = mock(EventSource.class); - eventSources.add(new NamedEventSource(source, "name")); - eventSources.add(new NamedEventSource(source, "name")); - assertThat(eventSources.flatMappedSources()) - .containsExactly(new NamedEventSource(source, "name")); - } + when(source.name()).thenReturn("name"); + when(source.resourceType()).thenReturn(EventSource.class); + eventSources.add(source); + assertThrows(IllegalArgumentException.class, () -> eventSources.add(source)); + } @Test void eventSourcesStreamShouldNotReturnControllerEventSource() { final var eventSources = new EventSources(); final var source = mock(EventSource.class); - final var namedEventSource = new NamedEventSource(source, EVENT_SOURCE_NAME); - eventSources.add(namedEventSource); + when(source.name()).thenReturn(EVENT_SOURCE_NAME); + when(source.resourceType()).thenReturn(EventSource.class); - assertThat(eventSources.additionalNamedEventSources()).containsExactly( - new NamedEventSource(eventSources.retryEventSource(), - RETRY_RESCHEDULE_TIMER_EVENT_SOURCE_NAME), - namedEventSource); + eventSources.add(source); + + assertThat(eventSources.additionalEventSources()).containsExactly( + eventSources.retryEventSource(), + source); } @Test void additionalEventSourcesShouldNotContainNamedEventSources() { final var eventSources = new EventSources(); final var source = mock(EventSource.class); - final var namedEventSource = new NamedEventSource(source, EVENT_SOURCE_NAME); - eventSources.add(namedEventSource); + when(source.name()).thenReturn(EVENT_SOURCE_NAME); + when(source.resourceType()).thenReturn(EventSource.class); + eventSources.add(source); + assertThat(eventSources.additionalEventSources()).containsExactly( eventSources.retryEventSource(), source); } @Test - void checkControllerResourceEventSource() { + void checkControllerEventSource() { final var eventSources = new EventSources(); final var configuration = MockControllerConfiguration.forResource(HasMetadata.class); when(configuration.getConfigurationService()).thenReturn(new BaseConfigurationService()); final var controller = new Controller(mock(Reconciler.class), configuration, MockKubernetesClient.client(HasMetadata.class)); eventSources.createControllerEventSource(controller); - final var controllerResourceEventSource = eventSources.controllerResourceEventSource(); - assertNotNull(controllerResourceEventSource); - assertEquals(HasMetadata.class, controllerResourceEventSource.resourceType()); + final var controllerEventSource = eventSources.controllerEventSource(); + assertNotNull(controllerEventSource); + assertEquals(HasMetadata.class, controllerEventSource.resourceType()); - assertEquals(controllerResourceEventSource, - eventSources.namedControllerResourceEventSource().eventSource()); + assertEquals(controllerEventSource, + eventSources.controllerEventSource()); } @Test void flatMappedSourcesShouldReturnOnlyUserRegisteredEventSources() { final var eventSources = new EventSources(); - final var mock1 = mock(ResourceEventSource.class); - when(mock1.resourceType()).thenReturn(HasMetadata.class); - final var mock2 = mock(ResourceEventSource.class); - when(mock2.resourceType()).thenReturn(HasMetadata.class); - final var mock3 = mock(ResourceEventSource.class); - when(mock3.resourceType()).thenReturn(ConfigMap.class); - - final var named1 = new NamedEventSource(mock1, "name1"); - final var named2 = new NamedEventSource(mock2, "name2"); - final var named3 = new NamedEventSource(mock3, "name2"); - eventSources.add(named1); - eventSources.add(named2); - eventSources.add(named3); - - assertThat(eventSources.flatMappedSources()).contains(named1, named2, named3); + final var mock1 = + eventSourceMockWithName(EventSource.class, "name1", HasMetadata.class); + final var mock2 = + eventSourceMockWithName(EventSource.class, "name2", HasMetadata.class); + final var mock3 = eventSourceMockWithName(EventSource.class, "name3", ConfigMap.class); + + eventSources.add(mock1); + eventSources.add(mock2); + eventSources.add(mock3); + + assertThat(eventSources.flatMappedSources()).contains(mock1, mock2, mock3); } @Test void clearShouldWork() { final var eventSources = new EventSources(); - final var mock1 = mock(ResourceEventSource.class); - when(mock1.resourceType()).thenReturn(HasMetadata.class); - final var mock2 = mock(ResourceEventSource.class); - when(mock2.resourceType()).thenReturn(HasMetadata.class); - final var mock3 = mock(ResourceEventSource.class); - when(mock3.resourceType()).thenReturn(ConfigMap.class); - - final var named1 = new NamedEventSource(mock1, "name1"); - final var named2 = new NamedEventSource(mock2, "name2"); - final var named3 = new NamedEventSource(mock3, "name2"); - eventSources.add(named1); - eventSources.add(named2); - eventSources.add(named3); + final var mock1 = + eventSourceMockWithName(EventSource.class, "name1", HasMetadata.class); + final var mock2 = + eventSourceMockWithName(EventSource.class, "name2", HasMetadata.class); + final var mock3 = eventSourceMockWithName(EventSource.class, "name3", ConfigMap.class); + + eventSources.add(mock1); + eventSources.add(mock2); + eventSources.add(mock3); eventSources.clear(); assertThat(eventSources.flatMappedSources()).isEmpty(); @@ -136,23 +135,19 @@ void clearShouldWork() { @Test void getShouldWork() { final var eventSources = new EventSources(); - final var mock1 = mock(ResourceEventSource.class); - when(mock1.resourceType()).thenReturn(HasMetadata.class); - final var mock2 = mock(ResourceEventSource.class); - when(mock2.resourceType()).thenReturn(HasMetadata.class); - final var mock3 = mock(ResourceEventSource.class); - when(mock3.resourceType()).thenReturn(ConfigMap.class); - - final var named1 = new NamedEventSource(mock1, "name1"); - final var named2 = new NamedEventSource(mock2, "name2"); - final var named3 = new NamedEventSource(mock3, "name2"); - eventSources.add(named1); - eventSources.add(named2); - eventSources.add(named3); + final var mock1 = + eventSourceMockWithName(EventSource.class, "name1", HasMetadata.class); + final var mock2 = + eventSourceMockWithName(EventSource.class, "name2", HasMetadata.class); + final var mock3 = eventSourceMockWithName(EventSource.class, "name3", ConfigMap.class); + + eventSources.add(mock1); + eventSources.add(mock2); + eventSources.add(mock3); assertEquals(mock1, eventSources.get(HasMetadata.class, "name1")); assertEquals(mock2, eventSources.get(HasMetadata.class, "name2")); - assertEquals(mock3, eventSources.get(ConfigMap.class, "name2")); + assertEquals(mock3, eventSources.get(ConfigMap.class, "name3")); assertEquals(mock3, eventSources.get(ConfigMap.class, null)); @@ -166,19 +161,15 @@ void getShouldWork() { @Test void getEventSourcesShouldWork() { final var eventSources = new EventSources(); - final var mock1 = mock(ResourceEventSource.class); - when(mock1.resourceType()).thenReturn(HasMetadata.class); - final var mock2 = mock(ResourceEventSource.class); - when(mock2.resourceType()).thenReturn(HasMetadata.class); - final var mock3 = mock(ResourceEventSource.class); - when(mock3.resourceType()).thenReturn(ConfigMap.class); - - final var named1 = new NamedEventSource(mock1, "name1"); - final var named2 = new NamedEventSource(mock2, "name2"); - final var named3 = new NamedEventSource(mock3, "name2"); - eventSources.add(named1); - eventSources.add(named2); - eventSources.add(named3); + final var mock1 = + eventSourceMockWithName(EventSource.class, "name1", HasMetadata.class); + final var mock2 = + eventSourceMockWithName(EventSource.class, "name2", HasMetadata.class); + final var mock3 = eventSourceMockWithName(EventSource.class, "name3", ConfigMap.class); + + eventSources.add(mock1); + eventSources.add(mock2); + eventSources.add(mock3); var sources = eventSources.getEventSources(HasMetadata.class); assertThat(sources.size()).isEqualTo(2); @@ -193,18 +184,14 @@ void getEventSourcesShouldWork() { @Test void testConcurrentAddRemoveAndGet() throws InterruptedException { + final var concurrentExceptionFound = new AtomicBoolean(false); + for (int i = 0; i < 1000 && !concurrentExceptionFound.get(); i++) { final var eventSources = new EventSources(); var eventSourceList = - IntStream.range(1, 20).mapToObj(n -> { - var mockResES = mock(ResourceEventSource.class); - NamedEventSource eventSource = mock(NamedEventSource.class); - when(eventSource.original()).thenReturn(mockResES); - when(eventSource.name()).thenReturn("name" + n); - when(mockResES.resourceType()).thenReturn(HasMetadata.class); - return eventSource; - }).collect(Collectors.toList()); + IntStream.range(1, 20).mapToObj(n -> eventSourceMockWithName(EventSource.class, + "name" + n, HasMetadata.class)).toList(); IntStream.range(1, 10).forEach(n -> eventSources.add(eventSourceList.get(n - 1))); @@ -217,7 +204,7 @@ void testConcurrentAddRemoveAndGet() throws InterruptedException { var t2 = new Thread(() -> { phaser.arriveAndAwaitAdvance(); try { - eventSources.getEventSources(HasMetadata.class); + eventSources.getEventSources(eventSourceList.get(0).resourceType()); } catch (ConcurrentModificationException e) { concurrentExceptionFound.set(true); } @@ -227,8 +214,18 @@ void testConcurrentAddRemoveAndGet() throws InterruptedException { t1.join(); t2.join(); } + assertThat(concurrentExceptionFound) .withFailMessage("ConcurrentModificationException thrown") .isFalse(); } + + EventSource eventSourceMockWithName(Class clazz, String name, + Class resourceType) { + var mockedES = mock(clazz); + when(mockedES.name()).thenReturn(name); + when(mockedES.resourceType()).thenReturn(resourceType); + return mockedES; + } + } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/ReconciliationDispatcherTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/ReconciliationDispatcherTest.java index c6aacb9071..efec8c4228 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/ReconciliationDispatcherTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/ReconciliationDispatcherTest.java @@ -5,12 +5,11 @@ import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; +import java.util.function.Supplier; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -import org.mockito.ArgumentMatcher; import org.mockito.ArgumentMatchers; import org.mockito.stubbing.Answer; @@ -29,7 +28,6 @@ import io.javaoperatorsdk.operator.api.reconciler.Cleaner; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.DeleteControl; -import io.javaoperatorsdk.operator.api.reconciler.ErrorStatusHandler; import io.javaoperatorsdk.operator.api.reconciler.ErrorStatusUpdateControl; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; import io.javaoperatorsdk.operator.api.reconciler.RetryInfo; @@ -43,19 +41,9 @@ import static io.javaoperatorsdk.operator.TestUtils.markForDeletion; import static io.javaoperatorsdk.operator.processing.event.ReconciliationDispatcher.MAX_UPDATE_RETRY; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; @SuppressWarnings({"unchecked", "rawtypes"}) class ReconciliationDispatcherTest { @@ -70,8 +58,16 @@ class ReconciliationDispatcherTest { mock(ReconciliationDispatcher.CustomResourceFacade.class); private static ConfigurationService configurationService; - @BeforeAll - static void classSetup() { + @BeforeEach + void setup() { + initConfigService(true); + testCustomResource = TestUtils.testCustomResource(); + reconciler = spy(new TestReconciler()); + reconciliationDispatcher = + init(testCustomResource, reconciler, null, customResourceFacade, true); + } + + static void initConfigService(boolean useSSA) { /* * We need this for mock reconcilers to properly generate the expected UpdateControl: without * this, calls such as `when(reconciler.reconcile(eq(testCustomResource), @@ -87,15 +83,8 @@ static void classSetup() { public R clone(R object) { return object; } - })); - } - - @BeforeEach - void setup() { - testCustomResource = TestUtils.testCustomResource(); - reconciler = spy(new TestReconciler()); - reconciliationDispatcher = - init(testCustomResource, reconciler, null, customResourceFacade, true); + }) + .withUseSSAToPatchPrimaryResource(useSSA)); } private ReconciliationDispatcher init(R customResource, @@ -137,43 +126,47 @@ void addFinalizerOnNewResource() { verify(reconciler, never()) .reconcile(ArgumentMatchers.eq(testCustomResource), any()); verify(customResourceFacade, times(1)) - .updateResource( + .patchResourceWithSSA( argThat(testCustomResource -> testCustomResource.hasFinalizer(DEFAULT_FINALIZER))); - assertThat(testCustomResource.hasFinalizer(DEFAULT_FINALIZER)).isTrue(); } @Test - void callCreateOrUpdateOnNewResourceIfFinalizerSet() { - testCustomResource.addFinalizer(DEFAULT_FINALIZER); - reconciliationDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); - verify(reconciler, times(1)) + void addFinalizerOnNewResourceWithoutSSA() { + initConfigService(false); + final ReconciliationDispatcher dispatcher = + init(testCustomResource, reconciler, null, customResourceFacade, true); + + assertFalse(testCustomResource.hasFinalizer(DEFAULT_FINALIZER)); + dispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); + verify(reconciler, never()) .reconcile(ArgumentMatchers.eq(testCustomResource), any()); + verify(customResourceFacade, times(1)) + .patchResource( + argThat(testCustomResource -> testCustomResource.hasFinalizer(DEFAULT_FINALIZER)), + any()); + assertThat(testCustomResource.hasFinalizer(DEFAULT_FINALIZER)).isTrue(); } @Test - void updatesOnlyStatusSubResourceIfFinalizerSet() { + void callCreateOrUpdateOnNewResourceIfFinalizerSet() { testCustomResource.addFinalizer(DEFAULT_FINALIZER); - - reconciler.reconcile = (r, c) -> UpdateControl.patchStatus(testCustomResource); - reconciliationDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); - - verify(customResourceFacade, times(1)).patchStatus(eq(testCustomResource), any()); - verify(customResourceFacade, never()).updateResource(any()); + verify(reconciler, times(1)) + .reconcile(ArgumentMatchers.eq(testCustomResource), any()); } @Test - void updatesBothResourceAndStatusIfFinalizerSet() { + void patchesBothResourceAndStatusIfFinalizerSet() { testCustomResource.addFinalizer(DEFAULT_FINALIZER); - reconciler.reconcile = (r, c) -> UpdateControl.updateResourceAndStatus(testCustomResource); - when(customResourceFacade.updateResource(testCustomResource)) + reconciler.reconcile = (r, c) -> UpdateControl.patchResourceAndStatus(testCustomResource); + when(customResourceFacade.patchResource(eq(testCustomResource), any())) .thenReturn(testCustomResource); reconciliationDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); - verify(customResourceFacade, times(1)).updateResource(testCustomResource); - verify(customResourceFacade, times(1)).updateStatus(testCustomResource); + verify(customResourceFacade, times(1)).patchResource(eq(testCustomResource), any()); + verify(customResourceFacade, times(1)).patchStatus(eq(testCustomResource), any()); } @Test @@ -185,8 +178,7 @@ void patchesStatus() { reconciliationDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); verify(customResourceFacade, times(1)).patchStatus(eq(testCustomResource), any()); - verify(customResourceFacade, never()).updateStatus(any()); - verify(customResourceFacade, never()).updateResource(any()); + verify(customResourceFacade, never()).patchResource(any(), any()); } @Test @@ -218,7 +210,7 @@ void removesDefaultFinalizerOnDeleteIfSet() { reconciliationDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); assertThat(postExecControl.isFinalizerRemoved()).isTrue(); - verify(customResourceFacade, times(1)).updateResource(testCustomResource); + verify(customResourceFacade, times(1)).patchResourceWithoutSSA(eq(testCustomResource), any()); } @Test @@ -227,7 +219,7 @@ void retriesFinalizerRemovalWithFreshResource() { markForDeletion(testCustomResource); var resourceWithFinalizer = TestUtils.testCustomResource(); resourceWithFinalizer.addFinalizer(DEFAULT_FINALIZER); - when(customResourceFacade.updateResource(testCustomResource)) + when(customResourceFacade.patchResourceWithoutSSA(eq(testCustomResource), any())) .thenThrow(new KubernetesClientException(null, 409, null)) .thenReturn(testCustomResource); when(customResourceFacade.getResource(any(), any())).thenReturn(resourceWithFinalizer); @@ -236,7 +228,7 @@ void retriesFinalizerRemovalWithFreshResource() { reconciliationDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); assertThat(postExecControl.isFinalizerRemoved()).isTrue(); - verify(customResourceFacade, times(2)).updateResource(any()); + verify(customResourceFacade, times(2)).patchResourceWithoutSSA(any(), any()); verify(customResourceFacade, times(1)).getResource(any(), any()); } @@ -246,7 +238,7 @@ void nullResourceIsGracefullyHandledOnFinalizerRemovalRetry() { // of the finalizer removal testCustomResource.addFinalizer(DEFAULT_FINALIZER); markForDeletion(testCustomResource); - when(customResourceFacade.updateResource(any())) + when(customResourceFacade.patchResourceWithoutSSA(any(), any())) .thenThrow(new KubernetesClientException(null, 409, null)); when(customResourceFacade.getResource(any(), any())).thenReturn(null); @@ -254,7 +246,7 @@ void nullResourceIsGracefullyHandledOnFinalizerRemovalRetry() { reconciliationDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); assertThat(postExecControl.isFinalizerRemoved()).isTrue(); - verify(customResourceFacade, times(1)).updateResource(testCustomResource); + verify(customResourceFacade, times(1)).patchResourceWithoutSSA(eq(testCustomResource), any()); verify(customResourceFacade, times(1)).getResource(any(), any()); } @@ -262,7 +254,7 @@ void nullResourceIsGracefullyHandledOnFinalizerRemovalRetry() { void throwsExceptionIfFinalizerRemovalRetryExceeded() { testCustomResource.addFinalizer(DEFAULT_FINALIZER); markForDeletion(testCustomResource); - when(customResourceFacade.updateResource(any())) + when(customResourceFacade.patchResourceWithoutSSA(any(), any())) .thenThrow(new KubernetesClientException(null, 409, null)); when(customResourceFacade.getResource(any(), any())) .thenAnswer((Answer) invocationOnMock -> createResourceWithFinalizer()); @@ -274,7 +266,7 @@ void throwsExceptionIfFinalizerRemovalRetryExceeded() { assertThat(postExecControl.getRuntimeException()).isPresent(); assertThat(postExecControl.getRuntimeException().get()) .isInstanceOf(OperatorException.class); - verify(customResourceFacade, times(MAX_UPDATE_RETRY)).updateResource(any()); + verify(customResourceFacade, times(MAX_UPDATE_RETRY)).patchResourceWithoutSSA(any(), any()); verify(customResourceFacade, times(MAX_UPDATE_RETRY - 1)).getResource(any(), any()); } @@ -283,7 +275,7 @@ void throwsExceptionIfFinalizerRemovalRetryExceeded() { void throwsExceptionIfFinalizerRemovalClientExceptionIsNotConflict() { testCustomResource.addFinalizer(DEFAULT_FINALIZER); markForDeletion(testCustomResource); - when(customResourceFacade.updateResource(any())) + when(customResourceFacade.patchResourceWithoutSSA(any(), any())) .thenThrow(new KubernetesClientException(null, 400, null)); var res = @@ -291,7 +283,7 @@ void throwsExceptionIfFinalizerRemovalClientExceptionIsNotConflict() { assertThat(res.getRuntimeException()).isPresent(); assertThat(res.getRuntimeException().get()).isInstanceOf(KubernetesClientException.class); - verify(customResourceFacade, times(1)).updateResource(any()); + verify(customResourceFacade, times(1)).patchResourceWithoutSSA(any(), any()); verify(customResourceFacade, never()).getResource(any(), any()); } @@ -335,7 +327,7 @@ void doesNotRemovesTheSetFinalizerIfTheDeleteNotMethodInstructsIt() { reconciliationDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); assertEquals(1, testCustomResource.getMetadata().getFinalizers().size()); - verify(customResourceFacade, never()).updateResource(any()); + verify(customResourceFacade, never()).patchResource(any(), any()); } @Test @@ -345,22 +337,22 @@ void doesNotUpdateTheResourceIfNoUpdateUpdateControlIfFinalizerSet() { reconciler.reconcile = (r, c) -> UpdateControl.noUpdate(); reconciliationDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); - verify(customResourceFacade, never()).updateResource(any()); - verify(customResourceFacade, never()).updateStatus(testCustomResource); + verify(customResourceFacade, never()).patchResource(any(), any()); + verify(customResourceFacade, never()).patchStatus(eq(testCustomResource), any()); } @Test void addsFinalizerIfNotMarkedForDeletionAndEmptyCustomResourceReturned() { removeFinalizers(testCustomResource); reconciler.reconcile = (r, c) -> UpdateControl.noUpdate(); - when(customResourceFacade.updateResource(any())) + when(customResourceFacade.patchResourceWithSSA(any())) .thenReturn(testCustomResource); var postExecControl = reconciliationDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); - assertEquals(1, testCustomResource.getMetadata().getFinalizers().size()); - verify(customResourceFacade, times(1)).updateResource(any()); + verify(customResourceFacade, times(1)) + .patchResourceWithSSA(argThat(a -> !a.getMetadata().getFinalizers().isEmpty())); assertThat(postExecControl.updateIsStatusPatch()).isFalse(); assertThat(postExecControl.getUpdatedCustomResource()).isPresent(); } @@ -372,7 +364,7 @@ void doesNotCallDeleteIfMarkedForDeletionButNotOurFinalizer() { reconciliationDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); - verify(customResourceFacade, never()).updateResource(any()); + verify(customResourceFacade, never()).patchResource(any(), any()); verify(reconciler, never()).cleanup(eq(testCustomResource), any()); } @@ -443,30 +435,7 @@ void reScheduleOnDeleteWithoutFinalizerRemoval() { } @Test - void setObservedGenerationForStatusIfNeeded() throws Exception { - var observedGenResource = createObservedGenCustomResource(); - - Reconciler reconciler = mock(Reconciler.class); - ControllerConfiguration config = - MockControllerConfiguration.forResource(ObservedGenCustomResource.class); - CustomResourceFacade facade = mock(CustomResourceFacade.class); - var dispatcher = init(observedGenResource, reconciler, config, facade, true); - - when(config.isGenerationAware()).thenReturn(true); - - when(reconciler.reconcile(any(), any())) - .thenReturn(UpdateControl.patchStatus(observedGenResource)); - when(facade.patchStatus(eq(observedGenResource), any())).thenReturn(observedGenResource); - - PostExecutionControl control = dispatcher.handleExecution( - executionScopeWithCREvent(observedGenResource)); - assertThat(control.getUpdatedCustomResource().orElseGet(() -> fail("Missing optional")) - .getStatus().getObservedGeneration()) - .isEqualTo(1L); - } - - @Test - void updatesObservedGenerationOnNoUpdateUpdateControl() throws Exception { + void doesNotUpdatesObservedGenerationIfStatusIsNotPatchedWhenUsingSSA() throws Exception { var observedGenResource = createObservedGenCustomResource(); Reconciler reconciler = mock(Reconciler.class); @@ -475,18 +444,16 @@ void updatesObservedGenerationOnNoUpdateUpdateControl() throws Exception { when(config.isGenerationAware()).thenReturn(true); when(reconciler.reconcile(any(), any())) .thenReturn(UpdateControl.noUpdate()); - when(facade.updateStatus(observedGenResource)).thenReturn(observedGenResource); + when(facade.patchStatus(any(), any())).thenReturn(observedGenResource); var dispatcher = init(observedGenResource, reconciler, config, facade, true); PostExecutionControl control = dispatcher.handleExecution( executionScopeWithCREvent(observedGenResource)); - assertThat(control.getUpdatedCustomResource().orElseGet(() -> fail("Missing optional")) - .getStatus().getObservedGeneration()) - .isEqualTo(1L); + assertThat(control.getUpdatedCustomResource()).isEmpty(); } @Test - void updateObservedGenerationOnCustomResourceUpdate() throws Exception { + void doesNotPatchObservedGenerationOnCustomResourcePatch() throws Exception { var observedGenResource = createObservedGenCustomResource(); Reconciler reconciler = mock(Reconciler.class); @@ -494,16 +461,14 @@ void updateObservedGenerationOnCustomResourceUpdate() throws Exception { CustomResourceFacade facade = mock(CustomResourceFacade.class); when(config.isGenerationAware()).thenReturn(true); when(reconciler.reconcile(any(), any())) - .thenReturn(UpdateControl.updateResource(observedGenResource)); - when(facade.updateResource(any())).thenReturn(observedGenResource); - when(facade.updateStatus(observedGenResource)).thenReturn(observedGenResource); - var dispatcher = init(observedGenResource, reconciler, config, facade, true); + .thenReturn(UpdateControl.patchResource(observedGenResource)); + when(facade.patchResource(any(), any())).thenReturn(observedGenResource); + var dispatcher = init(observedGenResource, reconciler, config, facade, false); - PostExecutionControl control = dispatcher.handleExecution( + dispatcher.handleExecution( executionScopeWithCREvent(observedGenResource)); - assertThat(control.getUpdatedCustomResource().orElseGet(() -> fail("Missing optional")) - .getStatus().getObservedGeneration()) - .isEqualTo(1L); + + verify(facade, never()).patchStatus(any(), any()); } @Test @@ -513,9 +478,9 @@ void callErrorStatusHandlerIfImplemented() { reconciler.reconcile = (r, c) -> { throw new IllegalStateException("Error Status Test"); }; - reconciler.errorHandler = (r, ri, e) -> { + reconciler.errorHandler = () -> { testCustomResource.getStatus().setConfigMapStatus(ERROR_MESSAGE); - return ErrorStatusUpdateControl.updateStatus(testCustomResource); + return ErrorStatusUpdateControl.patchStatus(testCustomResource); }; reconciliationDispatcher.handleExecution( @@ -532,8 +497,8 @@ public boolean isLastAttempt() { } }).setResource(testCustomResource)); - verify(customResourceFacade, times(1)).updateStatus(testCustomResource); - verify(((ErrorStatusHandler) reconciler), times(1)).updateErrorStatus(eq(testCustomResource), + verify(customResourceFacade, times(1)).patchStatus(eq(testCustomResource), any()); + verify(reconciler, times(1)).updateErrorStatus(eq(testCustomResource), any(), any()); } @@ -544,15 +509,15 @@ void callErrorStatusHandlerEvenOnFirstError() { reconciler.reconcile = (r, c) -> { throw new IllegalStateException("Error Status Test"); }; - reconciler.errorHandler = (r, ri, e) -> { + reconciler.errorHandler = () -> { testCustomResource.getStatus().setConfigMapStatus(ERROR_MESSAGE); - return ErrorStatusUpdateControl.updateStatus(testCustomResource); + return ErrorStatusUpdateControl.patchStatus(testCustomResource); }; var postExecControl = reconciliationDispatcher.handleExecution( new ExecutionScope(null).setResource(testCustomResource)); - verify(customResourceFacade, times(1)).updateStatus(testCustomResource); - verify(((ErrorStatusHandler) reconciler), times(1)).updateErrorStatus(eq(testCustomResource), + verify(customResourceFacade, times(1)).patchStatus(eq(testCustomResource), any()); + verify(reconciler, times(1)).updateErrorStatus(eq(testCustomResource), any(), any()); assertThat(postExecControl.exceptionDuringExecution()).isTrue(); } @@ -563,17 +528,17 @@ void errorHandlerCanInstructNoRetryWithUpdate() { reconciler.reconcile = (r, c) -> { throw new IllegalStateException("Error Status Test"); }; - reconciler.errorHandler = (r, ri, e) -> { + reconciler.errorHandler = () -> { testCustomResource.getStatus().setConfigMapStatus(ERROR_MESSAGE); - return ErrorStatusUpdateControl.updateStatus(testCustomResource).withNoRetry(); + return ErrorStatusUpdateControl.patchStatus(testCustomResource).withNoRetry(); }; var postExecControl = reconciliationDispatcher.handleExecution( new ExecutionScope(null).setResource(testCustomResource)); - verify(((ErrorStatusHandler) reconciler), times(1)).updateErrorStatus(eq(testCustomResource), + verify(reconciler, times(1)).updateErrorStatus(eq(testCustomResource), any(), any()); - verify(customResourceFacade, times(1)).updateStatus(testCustomResource); + verify(customResourceFacade, times(1)).patchStatus(eq(testCustomResource), any()); assertThat(postExecControl.exceptionDuringExecution()).isFalse(); } @@ -583,7 +548,7 @@ void errorHandlerCanInstructNoRetryNoUpdate() { reconciler.reconcile = (r, c) -> { throw new IllegalStateException("Error Status Test"); }; - reconciler.errorHandler = (r, ri, e) -> { + reconciler.errorHandler = () -> { testCustomResource.getStatus().setConfigMapStatus(ERROR_MESSAGE); return ErrorStatusUpdateControl.noStatusUpdate().withNoRetry(); }; @@ -591,9 +556,9 @@ void errorHandlerCanInstructNoRetryNoUpdate() { var postExecControl = reconciliationDispatcher.handleExecution( new ExecutionScope(null).setResource(testCustomResource)); - verify(((ErrorStatusHandler) reconciler), times(1)).updateErrorStatus(eq(testCustomResource), + verify(reconciler, times(1)).updateErrorStatus(eq(testCustomResource), any(), any()); - verify(customResourceFacade, times(0)).updateStatus(testCustomResource); + verify(customResourceFacade, times(0)).patchStatus(eq(testCustomResource), any()); assertThat(postExecControl.exceptionDuringExecution()).isFalse(); } @@ -604,13 +569,13 @@ void errorStatusHandlerCanPatchResource() { throw new IllegalStateException("Error Status Test"); }; reconciler.errorHandler = - (r, ri, e) -> ErrorStatusUpdateControl.patchStatus(testCustomResource); + () -> ErrorStatusUpdateControl.patchStatus(testCustomResource); reconciliationDispatcher.handleExecution( new ExecutionScope(null).setResource(testCustomResource)); verify(customResourceFacade, times(1)).patchStatus(eq(testCustomResource), any()); - verify(((ErrorStatusHandler) reconciler), times(1)).updateErrorStatus(eq(testCustomResource), + verify(reconciler, times(1)).updateErrorStatus(eq(testCustomResource), any(), any()); } @@ -626,16 +591,14 @@ void ifRetryLimitedToZeroMaxAttemptsErrorHandlerGetsCorrectLastAttempt() { reconciler.reconcile = (r, c) -> { throw new IllegalStateException("Error Status Test"); }; - var mockErrorHandler = mock(ErrorStatusHandler.class); - when(mockErrorHandler.updateErrorStatus(any(), any(), any())) - .thenReturn(ErrorStatusUpdateControl.noStatusUpdate()); - reconciler.errorHandler = mockErrorHandler; + + reconciler.errorHandler = () -> ErrorStatusUpdateControl.noStatusUpdate(); reconciliationDispatcher.handleExecution( new ExecutionScope(null).setResource(testCustomResource)); - verify(mockErrorHandler, times(1)).updateErrorStatus(any(), - ArgumentMatchers.argThat((ArgumentMatcher>) context -> { + verify(reconciler, times(1)).updateErrorStatus(any(), + ArgumentMatchers.argThat(context -> { var retryInfo = context.getRetryInfo().orElseThrow(); return retryInfo.isLastAttempt(); }), any()); @@ -656,10 +619,14 @@ void canSkipSchedulingMaxDelayIf() { } @Test - void retriesAddingFinalizer() { + void retriesAddingFinalizerWithoutSSA() { + initConfigService(false); + reconciliationDispatcher = + init(testCustomResource, reconciler, null, customResourceFacade, true); + removeFinalizers(testCustomResource); reconciler.reconcile = (r, c) -> UpdateControl.noUpdate(); - when(customResourceFacade.updateResource(any())) + when(customResourceFacade.patchResource(any(), any())) .thenThrow(new KubernetesClientException(null, 409, null)) .thenReturn(testCustomResource); when(customResourceFacade.getResource(any(), any())) @@ -670,7 +637,7 @@ void retriesAddingFinalizer() { reconciliationDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); - verify(customResourceFacade, times(2)).updateResource(any()); + verify(customResourceFacade, times(2)).patchResource(any(), any()); } @Test @@ -681,7 +648,7 @@ void reSchedulesFromErrorHandler() { throw new IllegalStateException("Error Status Test"); }; reconciler.errorHandler = - (r, ri, e) -> ErrorStatusUpdateControl.noStatusUpdate() + () -> ErrorStatusUpdateControl.noStatusUpdate() .rescheduleAfter(delay); var res = reconciliationDispatcher.handleExecution( @@ -691,6 +658,12 @@ void reSchedulesFromErrorHandler() { assertThat(res.getRuntimeException()).isEmpty(); } + @Test + void addsFinalizerToPatchWithSSA() { + + } + + private ObservedGenCustomResource createObservedGenCustomResource() { ObservedGenCustomResource observedGenCustomResource = new ObservedGenCustomResource(); observedGenCustomResource.setMetadata(new ObjectMeta()); @@ -715,12 +688,11 @@ public ExecutionScope executionScopeWithCREvent(T res } private class TestReconciler - implements Reconciler, Cleaner, - ErrorStatusHandler { + implements Reconciler, Cleaner { private BiFunction> reconcile; private BiFunction cleanup; - private ErrorStatusHandler errorHandler; + private Supplier errorHandler; @Override public UpdateControl reconcile(TestCustomResource resource, @@ -743,7 +715,7 @@ public DeleteControl cleanup(TestCustomResource resource, Context context) { public ErrorStatusUpdateControl updateErrorStatus( TestCustomResource resource, Context context, Exception e) { - return errorHandler != null ? errorHandler.updateErrorStatus(resource, context, e) + return errorHandler != null ? errorHandler.get() : ErrorStatusUpdateControl.noStatusUpdate(); } } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/AbstractEventSourceTestBase.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/AbstractEventSourceTestBase.java index de5df68319..41b8b76623 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/AbstractEventSourceTestBase.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/AbstractEventSourceTestBase.java @@ -2,8 +2,7 @@ import org.junit.jupiter.api.AfterEach; -import io.javaoperatorsdk.operator.api.config.BaseConfigurationService; -import io.javaoperatorsdk.operator.api.config.ConfigurationService; +import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.processing.event.EventHandler; import io.javaoperatorsdk.operator.processing.event.source.informer.ManagedInformerEventSource; @@ -23,7 +22,7 @@ public void setUpSource(S source) { } - public void setUpSource(S source, boolean start, ConfigurationService configurationService) { + public void setUpSource(S source, boolean start, ControllerConfiguration configurationService) { setUpSource(source, (T) mock(EventHandler.class), start, configurationService); } @@ -37,16 +36,16 @@ public void setUpSource(S source, T eventHandler) { } public void setUpSource(S source, T eventHandler, boolean start) { - setUpSource(source, eventHandler, start, new BaseConfigurationService()); + setUpSource(source, eventHandler, start, mock(ControllerConfiguration.class)); } public void setUpSource(S source, T eventHandler, boolean start, - ConfigurationService configurationService) { + ControllerConfiguration controllerConfiguration) { this.eventHandler = eventHandler; this.source = source; if (source instanceof ManagedInformerEventSource) { - ((ManagedInformerEventSource) source).setConfigurationService(configurationService); + ((ManagedInformerEventSource) source).setControllerConfiguration(controllerConfiguration); } source.setEventHandler(eventHandler); diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/ResourceEventFilterTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/ResourceEventFilterTest.java deleted file mode 100644 index c8ec839b59..0000000000 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/ResourceEventFilterTest.java +++ /dev/null @@ -1,166 +0,0 @@ -package io.javaoperatorsdk.operator.processing.event.source; - -import java.util.List; -import java.util.Objects; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import io.fabric8.kubernetes.api.model.HasMetadata; -import io.javaoperatorsdk.operator.MockKubernetesClient; -import io.javaoperatorsdk.operator.ReconcilerUtils; -import io.javaoperatorsdk.operator.TestUtils; -import io.javaoperatorsdk.operator.api.config.BaseConfigurationService; -import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; -import io.javaoperatorsdk.operator.api.config.ResolvedControllerConfiguration; -import io.javaoperatorsdk.operator.processing.Controller; -import io.javaoperatorsdk.operator.processing.event.EventHandler; -import io.javaoperatorsdk.operator.processing.event.EventSourceManager; -import io.javaoperatorsdk.operator.processing.event.source.controller.ControllerResourceEventSource; -import io.javaoperatorsdk.operator.processing.event.source.controller.ResourceAction; -import io.javaoperatorsdk.operator.processing.event.source.controller.ResourceEventFilter; -import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; - -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -class ResourceEventFilterTest { - public static final String FINALIZER = - ReconcilerUtils.getDefaultFinalizerName(TestCustomResource.class); - - private EventHandler eventHandler; - - @BeforeEach - public void before() { - this.eventHandler = mock(EventHandler.class); - } - - private ControllerResourceEventSource init(Controller controller) { - var eventSource = new ControllerResourceEventSource<>(controller); - eventSource.setEventHandler(eventHandler); - return eventSource; - } - - @Test - public void eventFilteredByCustomPredicate() { - var config = new TestControllerConfig( - FINALIZER, - false, - (configuration, oldResource, newResource) -> oldResource == null || !Objects.equals( - oldResource.getStatus().getConfigMapStatus(), - newResource.getStatus().getConfigMapStatus())); - - final var eventSource = init(new TestController(config)); - - TestCustomResource cr = TestUtils.testCustomResource(); - cr.getMetadata().setFinalizers(List.of(FINALIZER)); - cr.getMetadata().setGeneration(1L); - cr.getStatus().setConfigMapStatus("1"); - - TestCustomResource cr2 = TestUtils.testCustomResource(); - cr.getMetadata().setFinalizers(List.of(FINALIZER)); - cr.getMetadata().setGeneration(1L); - cr.getStatus().setConfigMapStatus("2"); - - eventSource.eventReceived(ResourceAction.UPDATED, cr, cr2); - verify(eventHandler, times(1)).handleEvent(any()); - - cr.getMetadata().setGeneration(1L); - cr.getStatus().setConfigMapStatus("1"); - - eventSource.eventReceived(ResourceAction.UPDATED, cr, cr); - verify(eventHandler, times(1)).handleEvent(any()); - } - - @Test - public void eventFilteredByCustomPredicateAndGenerationAware() { - var config = new TestControllerConfig( - FINALIZER, - true, - (configuration, oldResource, newResource) -> oldResource == null || !Objects.equals( - oldResource.getStatus().getConfigMapStatus(), - newResource.getStatus().getConfigMapStatus())); - - final var eventSource = init(new TestController(config)); - - TestCustomResource cr = TestUtils.testCustomResource(); - cr.getMetadata().setFinalizers(List.of(FINALIZER)); - cr.getMetadata().setGeneration(1L); - cr.getStatus().setConfigMapStatus("1"); - - TestCustomResource cr2 = TestUtils.testCustomResource(); - cr.getMetadata().setFinalizers(List.of(FINALIZER)); - cr.getMetadata().setGeneration(2L); - cr.getStatus().setConfigMapStatus("1"); - - eventSource.eventReceived(ResourceAction.UPDATED, cr, cr2); - verify(eventHandler, times(1)).handleEvent(any()); - - cr.getMetadata().setGeneration(1L); - cr.getStatus().setConfigMapStatus("2"); - - eventSource.eventReceived(ResourceAction.UPDATED, cr, cr); - verify(eventHandler, times(1)).handleEvent(any()); - } - - @Test - public void eventAlwaysFilteredByCustomPredicate() { - var config = new TestControllerConfig( - FINALIZER, - false, - (configuration, oldResource, newResource) -> !Objects.equals( - oldResource.getStatus().getConfigMapStatus(), - newResource.getStatus().getConfigMapStatus())); - - final var eventSource = init(new TestController(config)); - - TestCustomResource cr = TestUtils.testCustomResource(); - cr.getMetadata().setGeneration(1L); - cr.getStatus().setConfigMapStatus("1"); - - eventSource.eventReceived(ResourceAction.UPDATED, cr, cr); - verify(eventHandler, times(0)).handleEvent(any()); - } - - private static class TestControllerConfig extends ControllerConfig { - public TestControllerConfig(String finalizer, boolean generationAware, - ResourceEventFilter eventFilter) { - super(finalizer, generationAware, eventFilter, TestCustomResource.class); - } - } - - private static class ControllerConfig extends - ResolvedControllerConfiguration { - - public ControllerConfig(String finalizer, boolean generationAware, - ResourceEventFilter eventFilter, Class customResourceClass) { - super(customResourceClass, - "test", - generationAware, - null, - null, - null, - null, - null, - null, - null, null, null, finalizer, null, null, null, new BaseConfigurationService(), null); - setEventFilter(eventFilter); - } - } - - private static class TestController extends Controller { - - public TestController(ControllerConfiguration configuration) { - super(null, configuration, MockKubernetesClient.client(TestCustomResource.class)); - } - - @SuppressWarnings("unchecked") - @Override - public EventSourceManager getEventSourceManager() { - return mock(EventSourceManager.class); - } - } - -} diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/controller/ControllerResourceEventSourceTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/controller/ControllerEventSourceTest.java similarity index 80% rename from operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/controller/ControllerResourceEventSourceTest.java rename to operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/controller/ControllerEventSourceTest.java index 64f0993139..4ba2a5184c 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/controller/ControllerResourceEventSourceTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/controller/ControllerEventSourceTest.java @@ -10,7 +10,11 @@ import io.javaoperatorsdk.operator.ReconcilerUtils; import io.javaoperatorsdk.operator.TestUtils; import io.javaoperatorsdk.operator.api.config.BaseConfigurationService; +import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.config.ResolvedControllerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.javaoperatorsdk.operator.processing.Controller; import io.javaoperatorsdk.operator.processing.event.EventHandler; import io.javaoperatorsdk.operator.processing.event.EventSourceManager; @@ -21,24 +25,23 @@ import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.*; -class ControllerResourceEventSourceTest extends - AbstractEventSourceTestBase, EventHandler> { +class ControllerEventSourceTest extends + AbstractEventSourceTestBase, EventHandler> { public static final String FINALIZER = ReconcilerUtils.getDefaultFinalizerName(TestCustomResource.class); private final TestController testController = new TestController(true); + private final ControllerConfiguration controllerConfig = mock(ControllerConfiguration.class); @BeforeEach public void setup() { - setUpSource(new ControllerResourceEventSource<>(testController), true, - new BaseConfigurationService()); + + when(controllerConfig.getConfigurationService()).thenReturn(new BaseConfigurationService()); + + setUpSource(new ControllerEventSource<>(testController), true, controllerConfig); } @Test @@ -85,7 +88,7 @@ void normalExecutionIfGenerationChanges() { @Test void handlesAllEventIfNotGenerationAware() { source = - new ControllerResourceEventSource<>(new TestController(false)); + new ControllerEventSource<>(new TestController(false)); setup(); TestCustomResource customResource1 = TestUtils.testCustomResource(); @@ -124,9 +127,9 @@ void filtersOutEventsOnAddAndUpdate() { OnAddFilter onAddFilter = (res) -> false; OnUpdateFilter onUpdatePredicate = (res, res2) -> false; source = - new ControllerResourceEventSource<>( + new ControllerEventSource<>( new TestController(onAddFilter, onUpdatePredicate, null)); - setUpSource(source); + setUpSource(source, true, controllerConfig); source.eventReceived(ResourceAction.ADDED, cr, null); source.eventReceived(ResourceAction.UPDATED, cr, cr); @@ -139,8 +142,8 @@ void genericFilterFiltersOutAddUpdateAndDeleteEvents() { TestCustomResource cr = TestUtils.testCustomResource(); source = - new ControllerResourceEventSource<>(new TestController(null, null, res -> false)); - setUpSource(source); + new ControllerEventSource<>(new TestController(null, null, res -> false)); + setUpSource(source, true, controllerConfig); source.eventReceived(ResourceAction.ADDED, cr, null); source.eventReceived(ResourceAction.UPDATED, cr, cr); @@ -152,18 +155,21 @@ void genericFilterFiltersOutAddUpdateAndDeleteEvents() { @SuppressWarnings("unchecked") private static class TestController extends Controller { + private static final Reconciler reconciler = + (resource, context) -> UpdateControl.noUpdate(); + private final EventSourceManager eventSourceManager = mock(EventSourceManager.class); public TestController(OnAddFilter onAddFilter, OnUpdateFilter onUpdateFilter, GenericFilter genericFilter) { - super(null, new TestConfiguration(true, onAddFilter, onUpdateFilter, genericFilter), + super(reconciler, new TestConfiguration(true, onAddFilter, onUpdateFilter, genericFilter), MockKubernetesClient.client(TestCustomResource.class)); } public TestController(boolean generationAware) { - super(null, new TestConfiguration(generationAware, null, null, null), + super(reconciler, new TestConfiguration(generationAware, null, null, null), MockKubernetesClient.client(TestCustomResource.class)); } @@ -185,21 +191,19 @@ public TestConfiguration(boolean generationAware, OnAddFilter onUpdateFilter, GenericFilter genericFilter) { super( - TestCustomResource.class, "test", generationAware, null, null, null, null, - onAddFilter, - onUpdateFilter, - genericFilter, + FINALIZER, null, null, - FINALIZER, - null, null, null, new BaseConfigurationService(), - null); + new BaseConfigurationService(), + InformerConfiguration.builder(TestCustomResource.class).withOnAddFilter(onAddFilter) + .withOnUpdateFilter(onUpdateFilter).withGenericFilter(genericFilter) + .buildForController()); } } } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSourceTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSourceTest.java index 5b8aac89e6..ce027846f0 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSourceTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/InformerEventSourceTest.java @@ -14,8 +14,10 @@ import io.javaoperatorsdk.operator.OperatorException; import io.javaoperatorsdk.operator.api.config.BaseConfigurationService; import io.javaoperatorsdk.operator.api.config.ConfigurationService; +import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.config.InformerStoppedHandler; import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; import io.javaoperatorsdk.operator.processing.event.EventHandler; import io.javaoperatorsdk.operator.processing.event.ResourceID; import io.javaoperatorsdk.operator.processing.event.source.SecondaryToPrimaryMapper; @@ -43,23 +45,27 @@ class InformerEventSourceTest { private final TemporaryResourceCache temporaryResourceCacheMock = mock(TemporaryResourceCache.class); private final EventHandler eventHandlerMock = mock(EventHandler.class); - private final InformerConfiguration informerConfiguration = - mock(InformerConfiguration.class); + private final InformerEventSourceConfiguration informerEventSourceConfiguration = + mock(InformerEventSourceConfiguration.class); @BeforeEach void setup() { - when(informerConfiguration.getEffectiveNamespaces(any())) - .thenReturn(DEFAULT_NAMESPACES_SET); - when(informerConfiguration.getSecondaryToPrimaryMapper()) + final var informerConfig = mock(InformerConfiguration.class); + when(informerEventSourceConfiguration.getInformerConfig()).thenReturn(informerConfig); + when(informerConfig.getEffectiveNamespaces(any())).thenReturn(DEFAULT_NAMESPACES_SET); + when(informerEventSourceConfiguration.getSecondaryToPrimaryMapper()) .thenReturn(mock(SecondaryToPrimaryMapper.class)); - when(informerConfiguration.getResourceClass()).thenReturn(Deployment.class); + when(informerEventSourceConfiguration.getResourceClass()).thenReturn(Deployment.class); - informerEventSource = new InformerEventSource<>(informerConfiguration, clientMock); + informerEventSource = new InformerEventSource<>(informerEventSourceConfiguration, clientMock); + + var mockControllerConfig = mock(ControllerConfiguration.class); + when(mockControllerConfig.getConfigurationService()).thenReturn(new BaseConfigurationService()); informerEventSource.setEventHandler(eventHandlerMock); - informerEventSource.setConfigurationService(new BaseConfigurationService()); + informerEventSource.setControllerConfiguration(mockControllerConfig); SecondaryToPrimaryMapper secondaryToPrimaryMapper = mock(SecondaryToPrimaryMapper.class); - when(informerConfiguration.getSecondaryToPrimaryMapper()) + when(informerEventSourceConfiguration.getSecondaryToPrimaryMapper()) .thenReturn(secondaryToPrimaryMapper); when(secondaryToPrimaryMapper.toPrimaryResourceIDs(any())) .thenReturn(Set.of(ResourceID.fromResource(testDeployment()))); @@ -177,11 +183,14 @@ void informerStoppedHandlerShouldBeCalledWhenInformerStops() { ConfigurationService.newOverriddenConfigurationService(new BaseConfigurationService(), o -> o.withInformerStoppedHandler(informerStoppedHandler)); - informerEventSource = new InformerEventSource<>(informerConfiguration, + var mockControllerConfig = mock(ControllerConfiguration.class); + when(mockControllerConfig.getConfigurationService()).thenReturn(configuration); + + informerEventSource = new InformerEventSource<>(informerEventSourceConfiguration, MockKubernetesClient.client(Deployment.class, unused -> { throw exception; })); - informerEventSource.setConfigurationService(configuration); + informerEventSource.setControllerConfiguration(mockControllerConfig); // by default informer fails to start if there is an exception in the client on start. // Throws the exception further. diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/MappersTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/MappersTest.java new file mode 100644 index 0000000000..12e7b54706 --- /dev/null +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/MappersTest.java @@ -0,0 +1,56 @@ +package io.javaoperatorsdk.operator.processing.event.source.informer; + +import java.util.UUID; + +import org.junit.jupiter.api.Test; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.TestUtils; +import io.javaoperatorsdk.operator.processing.event.ResourceID; +import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; +import io.javaoperatorsdk.operator.sample.simple.TestCustomResourceOtherV1; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +class MappersTest { + + + @Test + void secondaryToPrimaryMapperFromOwnerReference() { + var primary = TestUtils.testCustomResource(); + primary.getMetadata().setUid(UUID.randomUUID().toString()); + var secondary = getConfigMap(primary); + secondary.addOwnerReference(primary); + + var res = Mappers.fromOwnerReferences(TestCustomResource.class) + .toPrimaryResourceIDs(secondary); + + assertThat(res).contains(ResourceID.fromResource(primary)); + } + + @Test + void secondaryToPrimaryMapperFromOwnerReferenceFiltersByType() { + var primary = TestUtils.testCustomResource(); + primary.getMetadata().setUid(UUID.randomUUID().toString()); + var secondary = getConfigMap(primary); + secondary.addOwnerReference(primary); + + var res = Mappers.fromOwnerReferences(TestCustomResourceOtherV1.class) + .toPrimaryResourceIDs(secondary); + + assertThat(res).isEmpty(); + } + + + private static ConfigMap getConfigMap(TestCustomResource primary) { + return new ConfigMapBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("test1") + .withNamespace(primary.getMetadata().getNamespace()) + .build()) + .build(); + } +} diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/PrimaryToSecondaryIndexTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/PrimaryToSecondaryIndexTest.java index 62f395f2d6..6793b09550 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/PrimaryToSecondaryIndexTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/informer/PrimaryToSecondaryIndexTest.java @@ -23,10 +23,10 @@ class PrimaryToSecondaryIndexTest { private final PrimaryToSecondaryIndex primaryToSecondaryIndex = new DefaultPrimaryToSecondaryIndex<>(secondaryToPrimaryMapperMock); - private ResourceID primaryID1 = new ResourceID("id1", "default"); - private ResourceID primaryID2 = new ResourceID("id2", "default"); - private ConfigMap secondary1 = secondary("secondary1"); - private ConfigMap secondary2 = secondary("secondary2"); + private final ResourceID primaryID1 = new ResourceID("id1", "default"); + private final ResourceID primaryID2 = new ResourceID("id2", "default"); + private final ConfigMap secondary1 = secondary("secondary1"); + private final ConfigMap secondary2 = secondary("secondary2"); @BeforeEach void setup() { diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSourceTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSourceTest.java index 70249f6125..fd5b85aa16 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSourceTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PerResourcePollingEventSourceTest.java @@ -11,19 +11,17 @@ import io.javaoperatorsdk.operator.TestUtils; import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; import io.javaoperatorsdk.operator.processing.event.EventHandler; -import io.javaoperatorsdk.operator.processing.event.source.*; +import io.javaoperatorsdk.operator.processing.event.source.AbstractEventSourceTestBase; +import io.javaoperatorsdk.operator.processing.event.source.CacheKeyMapper; +import io.javaoperatorsdk.operator.processing.event.source.IndexerResourceCache; +import io.javaoperatorsdk.operator.processing.event.source.SampleExternalResource; import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.atLeast; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; class PerResourcePollingEventSourceTest extends AbstractEventSourceTestBase, EventHandler> { @@ -45,8 +43,10 @@ public void setup() { .thenReturn(Set.of(SampleExternalResource.testResource1())); when(context.getPrimaryCache()).thenReturn(resourceCache); - setUpSource(new PerResourcePollingEventSource<>(supplier, context, Duration.ofMillis(PERIOD), - SampleExternalResource.class, r -> r.getName() + "#" + r.getValue())); + setUpSource(new PerResourcePollingEventSource<>(SampleExternalResource.class, context, + new PerResourcePollingConfigurationBuilder<>(supplier, Duration.ofMillis(PERIOD)) + .withCacheKeyMapper(r -> r.getName() + "#" + r.getValue()) + .build())); } @Test @@ -62,9 +62,14 @@ void pollsTheResourceAfterAwareOfIt() { @Test void registeringTaskOnAPredicate() { - setUpSource(new PerResourcePollingEventSource<>(supplier, context, Duration.ofMillis(PERIOD), - testCustomResource -> testCustomResource.getMetadata().getGeneration() > 1, - SampleExternalResource.class, CacheKeyMapper.singleResourceCacheKeyMapper())); + setUpSource(new PerResourcePollingEventSource<>(SampleExternalResource.class, context, + new PerResourcePollingConfigurationBuilder<>( + supplier, Duration.ofMillis(PERIOD)) + .withRegisterPredicate( + testCustomResource -> testCustomResource.getMetadata().getGeneration() > 1) + .withCacheKeyMapper(CacheKeyMapper.singleResourceCacheKeyMapper()) + .build())); + source.onResourceCreated(testCustomResource); diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSourceTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSourceTest.java index bd0179d4cb..ced96e9b7d 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSourceTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/source/polling/PollingEventSourceTest.java @@ -25,14 +25,15 @@ class PollingEventSourceTest AbstractEventSourceTestBase, EventHandler> { public static final int DEFAULT_WAIT_PERIOD = 100; - public static final long POLL_PERIOD = 30L; + public static final Duration POLL_PERIOD = Duration.ofMillis(30L); @SuppressWarnings("unchecked") private final PollingEventSource.GenericResourceFetcher resourceFetcher = mock(PollingEventSource.GenericResourceFetcher.class); private final PollingEventSource pollingEventSource = - new PollingEventSource<>(resourceFetcher, POLL_PERIOD, SampleExternalResource.class, - (SampleExternalResource er) -> er.getName() + "#" + er.getValue()); + new PollingEventSource<>(SampleExternalResource.class, + new PollingConfiguration<>(null, resourceFetcher, POLL_PERIOD, + (SampleExternalResource er) -> er.getName() + "#" + er.getValue())); @BeforeEach public void setup() { @@ -92,7 +93,7 @@ void updatesHealthIndicatorBasedOnExceptionsInFetcher() throws InterruptedExcept .thenThrow(new RuntimeException("test exception")) .thenReturn(testResponseWithOneValue()); - await().pollInterval(Duration.ofMillis(POLL_PERIOD)).untilAsserted( + await().pollInterval(POLL_PERIOD).untilAsserted( () -> assertThat(pollingEventSource.getStatus()).isEqualTo(Status.UNHEALTHY)); await() diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/retry/GenericRetryExecutionTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/retry/GenericRetryExecutionTest.java index 1dcd9df464..1659995877 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/retry/GenericRetryExecutionTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/retry/GenericRetryExecutionTest.java @@ -4,38 +4,10 @@ import org.junit.jupiter.api.Test; -import io.javaoperatorsdk.operator.api.config.RetryConfiguration; - import static org.assertj.core.api.Assertions.assertThat; public class GenericRetryExecutionTest { - @Test - public void forFirstBackOffAlwaysReturnsInitialInterval() { - assertThat(getDefaultRetryExecution().nextDelay().get()) - .isEqualTo(RetryConfiguration.DEFAULT_INITIAL_INTERVAL); - } - - @Test - public void delayIsMultipliedEveryNextDelayCall() { - RetryExecution retryExecution = getDefaultRetryExecution(); - - Optional res = callNextDelayNTimes(retryExecution, 1); - assertThat(res.get()).isEqualTo(RetryConfiguration.DEFAULT_INITIAL_INTERVAL); - - res = retryExecution.nextDelay(); - assertThat(res.get()) - .isEqualTo((long) (RetryConfiguration.DEFAULT_INITIAL_INTERVAL - * RetryConfiguration.DEFAULT_MULTIPLIER)); - - res = retryExecution.nextDelay(); - assertThat(res.get()) - .isEqualTo( - (long) (RetryConfiguration.DEFAULT_INITIAL_INTERVAL - * RetryConfiguration.DEFAULT_MULTIPLIER - * RetryConfiguration.DEFAULT_MULTIPLIER)); - } - @Test public void noNextDelayIfMaxAttemptLimitReached() { RetryExecution retryExecution = diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/observedgeneration/ObservedGenStatus.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/observedgeneration/ObservedGenStatus.java index d4ffee5416..81ce9a435d 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/observedgeneration/ObservedGenStatus.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/observedgeneration/ObservedGenStatus.java @@ -1,7 +1,5 @@ package io.javaoperatorsdk.operator.sample.observedgeneration; -import io.javaoperatorsdk.operator.api.ObservedGenerationAwareStatus; - -public class ObservedGenStatus extends ObservedGenerationAwareStatus { +public class ObservedGenStatus { } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomReconciler.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomReconciler.java index 748b76b72d..be2c80667e 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomReconciler.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomReconciler.java @@ -104,7 +104,7 @@ public UpdateControl reconcile( } resource.getStatus().setConfigMapStatus("ConfigMap Ready"); } - return UpdateControl.updateResource(resource); + return UpdateControl.patchResource(resource); } private Map configMapData(TestCustomResource resource) { diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceOtherV1.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceOtherV1.java index f768ba491f..90e226abc8 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceOtherV1.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceOtherV1.java @@ -7,7 +7,7 @@ @Group("sample.javaoperatorsdk.io") @Version("v1") -@Kind("TestCustomResource") // this is needed to override the automatically generated kind +@Kind("TestCustomResourceOtherV1") // this is needed to override the automatically generated kind public class TestCustomResourceOtherV1 extends CustomResource { diff --git a/operator-framework-junit5/pom.xml b/operator-framework-junit5/pom.xml index f421c5ad58..8477be3783 100644 --- a/operator-framework-junit5/pom.xml +++ b/operator-framework-junit5/pom.xml @@ -1,22 +1,15 @@ - + + 4.0.0 - java-operator-sdk io.javaoperatorsdk - 4.9.7-SNAPSHOT + java-operator-sdk + 5.0.0-SNAPSHOT - 4.0.0 operator-framework-junit-5 Operator SDK - Framework - JUnit 5 extension - - 11 - 11 - - io.javaoperatorsdk @@ -46,4 +39,4 @@ - \ No newline at end of file + diff --git a/operator-framework-junit5/src/main/java/io/javaoperatorsdk/operator/junit/AbstractOperatorExtension.java b/operator-framework-junit5/src/main/java/io/javaoperatorsdk/operator/junit/AbstractOperatorExtension.java index eb05fcb5d8..d46987caa6 100644 --- a/operator-framework-junit5/src/main/java/io/javaoperatorsdk/operator/junit/AbstractOperatorExtension.java +++ b/operator-framework-junit5/src/main/java/io/javaoperatorsdk/operator/junit/AbstractOperatorExtension.java @@ -111,30 +111,15 @@ public T create(T resource) { return kubernetesClient.resource(resource).inNamespace(namespace).create(); } - @Deprecated(forRemoval = true) - public T create(Class type, T resource) { - return create(resource); - } - public T replace(T resource) { return kubernetesClient.resource(resource).inNamespace(namespace).replace(); } - @Deprecated(forRemoval = true) - public T replace(Class type, T resource) { - return replace(resource); - } - public boolean delete(T resource) { var res = kubernetesClient.resource(resource).inNamespace(namespace).delete(); return res.size() == 1 && res.get(0).getCauses().isEmpty(); } - @Deprecated(forRemoval = true) - public boolean delete(Class type, T resource) { - return delete(resource); - } - protected void beforeAllImpl(ExtensionContext context) { if (oneNamespacePerClass) { namespace = perClassNamespaceNameSupplier.apply(context); diff --git a/operator-framework-junit5/src/main/java/io/javaoperatorsdk/operator/junit/KubernetesClientAware.java b/operator-framework-junit5/src/main/java/io/javaoperatorsdk/operator/junit/KubernetesClientAware.java deleted file mode 100644 index 8e94e71b53..0000000000 --- a/operator-framework-junit5/src/main/java/io/javaoperatorsdk/operator/junit/KubernetesClientAware.java +++ /dev/null @@ -1,13 +0,0 @@ -package io.javaoperatorsdk.operator.junit; - -import io.fabric8.kubernetes.client.KubernetesClient; -import io.javaoperatorsdk.operator.api.reconciler.Context; - -/** - * @deprecated It shouldn't be needed to pass a {@link KubernetesClient} instance to the reconciler - * anymore as the client should be accessed via {@link Context#getClient()} instead. - */ -@Deprecated(since = "4.5.0", forRemoval = true) -public interface KubernetesClientAware extends HasKubernetesClient { - void setKubernetesClient(KubernetesClient kubernetesClient); -} diff --git a/operator-framework/pom.xml b/operator-framework/pom.xml index d7dc9140dd..455b1268fd 100644 --- a/operator-framework/pom.xml +++ b/operator-framework/pom.xml @@ -1,13 +1,11 @@ - + + 4.0.0 - java-operator-sdk io.javaoperatorsdk - 4.9.7-SNAPSHOT + java-operator-sdk + 5.0.0-SNAPSHOT - 4.0.0 operator-framework Operator SDK - Framework - Plain Java @@ -59,11 +57,6 @@ compile-testing test - - io.fabric8 - crd-generator-apt - test - io.fabric8 @@ -72,7 +65,7 @@ org.apache.logging.log4j - log4j-slf4j-impl + log4j-slf4j2-impl test @@ -87,8 +80,8 @@ test - io.javaoperatorsdk - jenvtest + io.fabric8 + kube-api-test-client-inject test @@ -103,19 +96,22 @@ However, this is needed to compile the tests so let's disable apt just for the compile phase --> default-compile - compile compile + compile - -proc:none - + -proc:none + + + org.apache.maven.plugins + maven-surefire-plugin + - diff --git a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/DefaultConfigurationService.java b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/DefaultConfigurationService.java index 12573b50f7..1a1214aa78 100644 --- a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/DefaultConfigurationService.java +++ b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/DefaultConfigurationService.java @@ -11,7 +11,6 @@ public class DefaultConfigurationService extends BaseConfigurationService { @Override protected ControllerConfiguration configFor(Reconciler reconciler) { final var other = super.configFor(reconciler); - return new ResolvedControllerConfiguration<>( - RuntimeControllerMetadata.getResourceClass(reconciler), other); + return new ResolvedControllerConfiguration<>(other); } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/CustomResourceFilterIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/CustomResourceFilterIT.java deleted file mode 100644 index 6733abaa47..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/CustomResourceFilterIT.java +++ /dev/null @@ -1,48 +0,0 @@ -package io.javaoperatorsdk.operator; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -import io.fabric8.kubernetes.api.model.ObjectMeta; -import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.customfilter.CustomFilteringTestReconciler; -import io.javaoperatorsdk.operator.sample.customfilter.CustomFilteringTestResource; -import io.javaoperatorsdk.operator.sample.customfilter.CustomFilteringTestResourceSpec; - -import static org.assertj.core.api.Assertions.assertThat; - -class CustomResourceFilterIT { - - @RegisterExtension - LocallyRunOperatorExtension operator = - LocallyRunOperatorExtension.builder().withReconciler(new CustomFilteringTestReconciler()) - .build(); - - @Test - void doesCustomFiltering() throws InterruptedException { - var filtered1 = createTestResource("filtered1", true, false); - var filtered2 = createTestResource("filtered2", false, true); - var notFiltered = createTestResource("notfiltered", true, true); - operator.create(filtered1); - operator.create(filtered2); - operator.create(notFiltered); - - Thread.sleep(300); - - assertThat( - ((CustomFilteringTestReconciler) operator.getReconcilers().get(0)).getNumberOfExecutions()) - .isEqualTo(1); - } - - - CustomFilteringTestResource createTestResource(String name, boolean filter1, boolean filter2) { - CustomFilteringTestResource resource = new CustomFilteringTestResource(); - resource.setMetadata(new ObjectMeta()); - resource.getMetadata().setName(name); - resource.setSpec(new CustomFilteringTestResourceSpec()); - resource.getSpec().setFilter1(filter1); - resource.getSpec().setFilter2(filter2); - return resource; - } - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/IndexDiscriminatorIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/IndexDiscriminatorIT.java deleted file mode 100644 index fe5b63de8a..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/IndexDiscriminatorIT.java +++ /dev/null @@ -1,77 +0,0 @@ -package io.javaoperatorsdk.operator; - -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.ObjectMetaBuilder; -import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.indexdiscriminator.IndexDiscriminatorTestCustomResource; -import io.javaoperatorsdk.operator.sample.indexdiscriminator.IndexDiscriminatorTestReconciler; -import io.javaoperatorsdk.operator.sample.indexdiscriminator.IndexDiscriminatorTestSpec; - -import static io.javaoperatorsdk.operator.sample.indexdiscriminator.IndexDiscriminatorTestDRConfigMap.DATA_KEY; -import static io.javaoperatorsdk.operator.sample.indexdiscriminator.IndexDiscriminatorTestReconciler.FIRST_CONFIG_MAP_SUFFIX_1; -import static io.javaoperatorsdk.operator.sample.indexdiscriminator.IndexDiscriminatorTestReconciler.FIRST_CONFIG_MAP_SUFFIX_2; -import static org.assertj.core.api.Assertions.assertThat; -import static org.awaitility.Awaitility.await; - -class IndexDiscriminatorIT { - - public static final String TEST_RESOURCE_1 = "test1"; - public static final String CHANGED_SPEC_VALUE = "otherValue"; - @RegisterExtension - LocallyRunOperatorExtension operator = - LocallyRunOperatorExtension.builder().withReconciler(IndexDiscriminatorTestReconciler.class) - .build(); - - @Test - void resourcesFoundAndReconciled() { - var res = operator.create(createTestCustomResource()); - var reconciler = operator.getReconcilerOfType(IndexDiscriminatorTestReconciler.class); - - await().untilAsserted(() -> { - assertThat(reconciler.getNumberOfExecutions()).isEqualTo(1); - assertThat(operator.get(ConfigMap.class, TEST_RESOURCE_1 + FIRST_CONFIG_MAP_SUFFIX_1)) - .isNotNull(); - assertThat(operator.get(ConfigMap.class, TEST_RESOURCE_1 + FIRST_CONFIG_MAP_SUFFIX_2)) - .isNotNull(); - }); - - res.getSpec().setValue(CHANGED_SPEC_VALUE); - res = operator.replace(res); - - await().untilAsserted(() -> { - assertThat(reconciler.getNumberOfExecutions()).isEqualTo(2); - var cm1 = operator.get(ConfigMap.class, TEST_RESOURCE_1 + FIRST_CONFIG_MAP_SUFFIX_1); - var cm2 = operator.get(ConfigMap.class, TEST_RESOURCE_1 + FIRST_CONFIG_MAP_SUFFIX_2); - assertThat(cm1).isNotNull(); - assertThat(cm2).isNotNull(); - assertThat(cm1.getData().get(DATA_KEY)).isEqualTo(CHANGED_SPEC_VALUE); - assertThat(cm2.getData().get(DATA_KEY)).isEqualTo(CHANGED_SPEC_VALUE); - }); - - operator.delete(res); - - await().untilAsserted(() -> { - var cm1 = operator.get(ConfigMap.class, TEST_RESOURCE_1 + FIRST_CONFIG_MAP_SUFFIX_1); - var cm2 = operator.get(ConfigMap.class, TEST_RESOURCE_1 + FIRST_CONFIG_MAP_SUFFIX_2); - assertThat(cm1).isNull(); - assertThat(cm2).isNull(); - }); - } - - public IndexDiscriminatorTestCustomResource createTestCustomResource() { - IndexDiscriminatorTestCustomResource resource = - new IndexDiscriminatorTestCustomResource(); - resource.setMetadata( - new ObjectMetaBuilder() - .withName(TEST_RESOURCE_1) - .withNamespace(operator.getNamespace()) - .build()); - resource.setSpec(new IndexDiscriminatorTestSpec()); - resource.getSpec().setValue("default"); - return resource; - } - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ObservedGenerationHandlingIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/ObservedGenerationHandlingIT.java deleted file mode 100644 index 0e28ddec4c..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ObservedGenerationHandlingIT.java +++ /dev/null @@ -1,37 +0,0 @@ -package io.javaoperatorsdk.operator; - -import java.util.concurrent.TimeUnit; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -import io.fabric8.kubernetes.api.model.ObjectMeta; -import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.observedgeneration.ObservedGenerationTestCustomResource; -import io.javaoperatorsdk.operator.sample.observedgeneration.ObservedGenerationTestReconciler; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.awaitility.Awaitility.await; - -class ObservedGenerationHandlingIT { - @RegisterExtension - LocallyRunOperatorExtension operator = - LocallyRunOperatorExtension.builder().withReconciler(new ObservedGenerationTestReconciler()) - .build(); - - @Test - void testReconciliationOfNonCustomResourceAndStatusUpdate() { - var resource = new ObservedGenerationTestCustomResource(); - resource.setMetadata(new ObjectMeta()); - resource.getMetadata().setName("observed-gen1"); - - var createdResource = operator.create(resource); - - await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> { - var d = operator.get(ObservedGenerationTestCustomResource.class, - createdResource.getMetadata().getName()); - assertThat(d.getStatus().getObservedGeneration()).isNotNull(); - assertThat(d.getStatus().getObservedGeneration()).isEqualTo(1); - }); - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ConcurrencyIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/ConcurrencyIT.java similarity index 95% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/ConcurrencyIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/ConcurrencyIT.java index f33c581538..eb60907e12 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ConcurrencyIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/ConcurrencyIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi; import java.util.List; import java.util.concurrent.TimeUnit; @@ -10,9 +10,9 @@ import org.slf4j.LoggerFactory; import io.fabric8.kubernetes.api.model.ConfigMap; +import io.javaoperatorsdk.operator.baseapi.simple.TestCustomResource; +import io.javaoperatorsdk.operator.baseapi.simple.TestReconciler; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; -import io.javaoperatorsdk.operator.sample.simple.TestReconciler; import io.javaoperatorsdk.operator.support.TestUtils; import static org.assertj.core.api.Assertions.assertThat; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/InformerErrorHandlerStartIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/InformerErrorHandlerStartIT.java similarity index 94% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/InformerErrorHandlerStartIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/InformerErrorHandlerStartIT.java index b1edf3e108..b18e9b6763 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/InformerErrorHandlerStartIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/InformerErrorHandlerStartIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi; import java.time.Duration; @@ -9,6 +9,7 @@ import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.KubernetesClientBuilder; +import io.javaoperatorsdk.operator.Operator; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/LeaderElectionPermissionIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/LeaderElectionPermissionIT.java similarity index 90% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/LeaderElectionPermissionIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/LeaderElectionPermissionIT.java index e1c8435b8a..2523e15423 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/LeaderElectionPermissionIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/LeaderElectionPermissionIT.java @@ -1,14 +1,16 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi; import org.junit.jupiter.api.Test; import io.fabric8.kubernetes.api.model.ConfigMap; -import io.fabric8.kubernetes.api.model.authorization.v1.*; import io.fabric8.kubernetes.api.model.rbac.Role; import io.fabric8.kubernetes.api.model.rbac.RoleBinding; import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.KubernetesClientBuilder; +import io.javaoperatorsdk.operator.Operator; +import io.javaoperatorsdk.operator.OperatorException; +import io.javaoperatorsdk.operator.ReconcilerUtils; import io.javaoperatorsdk.operator.api.config.LeaderElectionConfiguration; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; @@ -32,7 +34,8 @@ void operatorStopsIfNoLeaderElectionPermission() { .withImpersonateUsername("leader-elector-stop-noaccess") .build()).build(); - var operator = new Operator(client, o -> { + var operator = new Operator(o -> { + o.withKubernetesClient(client); o.withLeaderElectionConfiguration( new LeaderElectionConfiguration("lease1", "default")); o.withStopOnInformerErrorDuringStartup(false); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/BuiltInResourceCleanerIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/builtinresourcecleaner/BuiltInResourceCleanerIT.java similarity index 74% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/BuiltInResourceCleanerIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/builtinresourcecleaner/BuiltInResourceCleanerIT.java index f5c663b358..3867711f7f 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/BuiltInResourceCleanerIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/builtinresourcecleaner/BuiltInResourceCleanerIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.builtinresourcecleaner; import java.util.Map; @@ -8,8 +8,9 @@ import org.slf4j.LoggerFactory; import io.fabric8.kubernetes.api.model.Service; +import io.javaoperatorsdk.operator.ReconcilerUtils; +import io.javaoperatorsdk.operator.dependent.standalonedependent.StandaloneDependentResourceIT; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.builtinresourcecleaner.ObservedGenerationTestReconciler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; @@ -21,7 +22,7 @@ class BuiltInResourceCleanerIT { @RegisterExtension LocallyRunOperatorExtension operator = LocallyRunOperatorExtension.builder() - .withReconciler(new ObservedGenerationTestReconciler()) + .withReconciler(new BuiltInResourceCleanerReconciler()) .build(); /** @@ -33,7 +34,7 @@ void cleanerIsCalledOnBuiltInResource() { var service = operator.create(testService()); await().untilAsserted(() -> { - assertThat(operator.getReconcilerOfType(ObservedGenerationTestReconciler.class) + assertThat(operator.getReconcilerOfType(BuiltInResourceCleanerReconciler.class) .getReconcileCount()).isPositive(); var actualService = operator.get(Service.class, service.getMetadata().getName()); assertThat(actualService.getMetadata().getFinalizers()).isNotEmpty(); @@ -42,14 +43,14 @@ void cleanerIsCalledOnBuiltInResource() { operator.delete(service); await().untilAsserted(() -> { - assertThat(operator.getReconcilerOfType(ObservedGenerationTestReconciler.class) + assertThat(operator.getReconcilerOfType(BuiltInResourceCleanerReconciler.class) .getCleanCount()).isPositive(); }); } Service testService() { Service service = ReconcilerUtils.loadYaml(Service.class, StandaloneDependentResourceIT.class, - "service-template.yaml"); + "/io/javaoperatorsdk/operator/service-template.yaml"); service.getMetadata().setLabels(Map.of("builtintest", "true")); return service; } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/builtinresourcecleaner/ObservedGenerationTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/builtinresourcecleaner/BuiltInResourceCleanerReconciler.java similarity index 71% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/builtinresourcecleaner/ObservedGenerationTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/builtinresourcecleaner/BuiltInResourceCleanerReconciler.java index cba16a5c1f..79150eb745 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/builtinresourcecleaner/ObservedGenerationTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/builtinresourcecleaner/BuiltInResourceCleanerReconciler.java @@ -1,19 +1,15 @@ -package io.javaoperatorsdk.operator.sample.builtinresourcecleaner; +package io.javaoperatorsdk.operator.baseapi.builtinresourcecleaner; import java.util.concurrent.atomic.AtomicInteger; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import io.fabric8.kubernetes.api.model.Service; +import io.javaoperatorsdk.operator.api.config.informer.Informer; import io.javaoperatorsdk.operator.api.reconciler.*; -@ControllerConfiguration(labelSelector = "builtintest=true") -public class ObservedGenerationTestReconciler +@ControllerConfiguration(informer = @Informer(labelSelector = "builtintest=true")) +public class BuiltInResourceCleanerReconciler implements Reconciler, Cleaner { - private static final Logger log = LoggerFactory.getLogger(ObservedGenerationTestReconciler.class); - private final AtomicInteger reconciled = new AtomicInteger(0); private final AtomicInteger cleaned = new AtomicInteger(0); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ChangeNamespaceIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/changenamespace/ChangeNamespaceIT.java similarity index 96% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/ChangeNamespaceIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/changenamespace/ChangeNamespaceIT.java index e669f6d06c..1f6806aed7 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ChangeNamespaceIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/changenamespace/ChangeNamespaceIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.changenamespace; import java.time.Duration; import java.util.Map; @@ -14,10 +14,9 @@ import io.fabric8.kubernetes.api.model.NamespaceBuilder; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.client.KubernetesClient; +import io.javaoperatorsdk.operator.RegisteredController; import io.javaoperatorsdk.operator.api.reconciler.Constants; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.changenamespace.ChangeNamespaceTestCustomResource; -import io.javaoperatorsdk.operator.sample.changenamespace.ChangeNamespaceTestReconciler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/changenamespace/ChangeNamespaceTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/changenamespace/ChangeNamespaceTestCustomResource.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/changenamespace/ChangeNamespaceTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/changenamespace/ChangeNamespaceTestCustomResource.java index a333dbe164..eff8a4bb3f 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/changenamespace/ChangeNamespaceTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/changenamespace/ChangeNamespaceTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.changenamespace; +package io.javaoperatorsdk.operator.baseapi.changenamespace; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/changenamespace/ChangeNamespaceTestCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/changenamespace/ChangeNamespaceTestCustomResourceStatus.java similarity index 85% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/changenamespace/ChangeNamespaceTestCustomResourceStatus.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/changenamespace/ChangeNamespaceTestCustomResourceStatus.java index a3858cda05..009d1340e9 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/changenamespace/ChangeNamespaceTestCustomResourceStatus.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/changenamespace/ChangeNamespaceTestCustomResourceStatus.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.changenamespace; +package io.javaoperatorsdk.operator.baseapi.changenamespace; public class ChangeNamespaceTestCustomResourceStatus { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/changenamespace/ChangeNamespaceTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/changenamespace/ChangeNamespaceTestReconciler.java similarity index 81% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/changenamespace/ChangeNamespaceTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/changenamespace/ChangeNamespaceTestReconciler.java index 7d51f311e1..bac97514b6 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/changenamespace/ChangeNamespaceTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/changenamespace/ChangeNamespaceTestReconciler.java @@ -1,11 +1,12 @@ -package io.javaoperatorsdk.operator.sample.changenamespace; +package io.javaoperatorsdk.operator.baseapi.changenamespace; +import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; import io.javaoperatorsdk.operator.api.reconciler.*; import io.javaoperatorsdk.operator.processing.event.ResourceID; import io.javaoperatorsdk.operator.processing.event.source.EventSource; @@ -13,21 +14,23 @@ @ControllerConfiguration public class ChangeNamespaceTestReconciler - implements Reconciler, - EventSourceInitializer { + implements Reconciler { private final ConcurrentHashMap numberOfResourceReconciliations = new ConcurrentHashMap<>(); @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { InformerEventSource configMapES = - new InformerEventSource<>(InformerConfiguration.from(ConfigMap.class, context) - .build(), context); + new InformerEventSource<>( + InformerEventSourceConfiguration + .from(ConfigMap.class, ChangeNamespaceTestCustomResource.class) + .build(), + context); - return EventSourceInitializer.nameEventSources(configMapES); + return List.of(configMapES); } @Override diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanerforreconciler/CleanerForReconcilerCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanerforreconciler/CleanerForReconcilerCustomResource.java similarity index 89% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanerforreconciler/CleanerForReconcilerCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanerforreconciler/CleanerForReconcilerCustomResource.java index 7a4b255d28..4367d6d089 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanerforreconciler/CleanerForReconcilerCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanerforreconciler/CleanerForReconcilerCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.cleanerforreconciler; +package io.javaoperatorsdk.operator.baseapi.cleanerforreconciler; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/CleanerForReconcilerIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanerforreconciler/CleanerForReconcilerIT.java similarity index 91% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/CleanerForReconcilerIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanerforreconciler/CleanerForReconcilerIT.java index bf5fa243cf..04ea2f9646 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/CleanerForReconcilerIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanerforreconciler/CleanerForReconcilerIT.java @@ -1,12 +1,10 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.cleanerforreconciler; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.cleanerforreconciler.CleanerForReconcilerCustomResource; -import io.javaoperatorsdk.operator.sample.cleanerforreconciler.CleanerForReconcilerTestReconciler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanerforreconciler/CleanerForReconcilerTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanerforreconciler/CleanerForReconcilerTestReconciler.java similarity index 96% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanerforreconciler/CleanerForReconcilerTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanerforreconciler/CleanerForReconcilerTestReconciler.java index a6f404e7f6..8bb5fa1062 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanerforreconciler/CleanerForReconcilerTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanerforreconciler/CleanerForReconcilerTestReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.cleanerforreconciler; +package io.javaoperatorsdk.operator.baseapi.cleanerforreconciler; import java.util.concurrent.atomic.AtomicInteger; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanupconflict/CleanupConflictCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanupconflict/CleanupConflictCustomResource.java similarity index 90% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanupconflict/CleanupConflictCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanupconflict/CleanupConflictCustomResource.java index 9675273085..82f51c1f83 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanupconflict/CleanupConflictCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanupconflict/CleanupConflictCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.cleanupconflict; +package io.javaoperatorsdk.operator.baseapi.cleanupconflict; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanupconflict/CleanupConflictCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanupconflict/CleanupConflictCustomResourceStatus.java similarity index 80% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanupconflict/CleanupConflictCustomResourceStatus.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanupconflict/CleanupConflictCustomResourceStatus.java index 3488981eb1..19794e2173 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanupconflict/CleanupConflictCustomResourceStatus.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanupconflict/CleanupConflictCustomResourceStatus.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.cleanupconflict; +package io.javaoperatorsdk.operator.baseapi.cleanupconflict; public class CleanupConflictCustomResourceStatus { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/CleanupConflictIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanupconflict/CleanupConflictIT.java similarity index 85% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/CleanupConflictIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanupconflict/CleanupConflictIT.java index e1c571c4a5..4d79d6d1d3 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/CleanupConflictIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanupconflict/CleanupConflictIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.cleanupconflict; import java.time.Duration; @@ -7,10 +7,8 @@ import io.fabric8.kubernetes.api.model.ObjectMeta; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.cleanupconflict.CleanupConflictCustomResource; -import io.javaoperatorsdk.operator.sample.cleanupconflict.CleanupConflictReconciler; -import static io.javaoperatorsdk.operator.sample.cleanupconflict.CleanupConflictReconciler.WAIT_TIME; +import static io.javaoperatorsdk.operator.baseapi.cleanupconflict.CleanupConflictReconciler.WAIT_TIME; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanupconflict/CleanupConflictReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanupconflict/CleanupConflictReconciler.java similarity index 95% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanupconflict/CleanupConflictReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanupconflict/CleanupConflictReconciler.java index 14d8f8617f..1c66fde159 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanupconflict/CleanupConflictReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/cleanupconflict/CleanupConflictReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.cleanupconflict; +package io.javaoperatorsdk.operator.baseapi.cleanupconflict; import java.util.concurrent.atomic.AtomicInteger; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/clusterscopedresource/ClusterScopedCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/clusterscopedresource/ClusterScopedCustomResource.java similarity index 86% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/clusterscopedresource/ClusterScopedCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/clusterscopedresource/ClusterScopedCustomResource.java index 957b396df4..0e26316cfb 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/clusterscopedresource/ClusterScopedCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/clusterscopedresource/ClusterScopedCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.clusterscopedresource; +package io.javaoperatorsdk.operator.baseapi.clusterscopedresource; import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.model.annotation.Group; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/clusterscopedresource/ClusterScopedCustomResourceReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/clusterscopedresource/ClusterScopedCustomResourceReconciler.java similarity index 64% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/clusterscopedresource/ClusterScopedCustomResourceReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/clusterscopedresource/ClusterScopedCustomResourceReconciler.java index a6f5e00c96..3be5a055d7 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/clusterscopedresource/ClusterScopedCustomResourceReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/clusterscopedresource/ClusterScopedCustomResourceReconciler.java @@ -1,20 +1,24 @@ -package io.javaoperatorsdk.operator.sample.clusterscopedresource; +package io.javaoperatorsdk.operator.baseapi.clusterscopedresource; +import java.util.List; import java.util.Map; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; -import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.javaoperatorsdk.operator.processing.event.source.EventSource; import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; import io.javaoperatorsdk.operator.processing.event.source.informer.Mappers; @ControllerConfiguration public class ClusterScopedCustomResourceReconciler - implements Reconciler, - EventSourceInitializer { + implements Reconciler { public static final String DATA_KEY = "data-key"; @@ -53,12 +57,16 @@ private ConfigMap desired(ClusterScopedCustomResource resource) { } @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { - var ies = new InformerEventSource<>(InformerConfiguration.from(ConfigMap.class, context) - .withSecondaryToPrimaryMapper(Mappers.fromOwnerReference(true)) - .withLabelSelector(TEST_LABEL_KEY + "=" + TEST_LABEL_VALUE) - .build(), context); - return EventSourceInitializer.nameEventSources(ies); + var ies = new InformerEventSource<>( + InformerEventSourceConfiguration.from(ConfigMap.class, ClusterScopedCustomResource.class) + .withSecondaryToPrimaryMapper( + Mappers.fromOwnerReferences(context.getPrimaryResourceClass(), true)) + .withInformerConfiguration( + c -> c.withLabelSelector(TEST_LABEL_KEY + "=" + TEST_LABEL_VALUE)) + .build(), + context); + return List.of(ies); } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/clusterscopedresource/ClusterScopedCustomResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/clusterscopedresource/ClusterScopedCustomResourceSpec.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/clusterscopedresource/ClusterScopedCustomResourceSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/clusterscopedresource/ClusterScopedCustomResourceSpec.java index 825b0c443e..8facc07e18 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/clusterscopedresource/ClusterScopedCustomResourceSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/clusterscopedresource/ClusterScopedCustomResourceSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.clusterscopedresource; +package io.javaoperatorsdk.operator.baseapi.clusterscopedresource; public class ClusterScopedCustomResourceSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/clusterscopedresource/ClusterScopedCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/clusterscopedresource/ClusterScopedCustomResourceStatus.java similarity index 79% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/clusterscopedresource/ClusterScopedCustomResourceStatus.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/clusterscopedresource/ClusterScopedCustomResourceStatus.java index 7c4d49f3a1..7ed5c6c1b4 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/clusterscopedresource/ClusterScopedCustomResourceStatus.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/clusterscopedresource/ClusterScopedCustomResourceStatus.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.clusterscopedresource; +package io.javaoperatorsdk.operator.baseapi.clusterscopedresource; public class ClusterScopedCustomResourceStatus { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ClusterScopedResourceIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/clusterscopedresource/ClusterScopedResourceIT.java similarity index 85% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/ClusterScopedResourceIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/clusterscopedresource/ClusterScopedResourceIT.java index b1a3797bea..e923084425 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ClusterScopedResourceIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/clusterscopedresource/ClusterScopedResourceIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.clusterscopedresource; import java.time.Duration; @@ -8,10 +8,8 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.clusterscopedresource.ClusterScopedCustomResource; -import io.javaoperatorsdk.operator.sample.clusterscopedresource.ClusterScopedCustomResourceReconciler; -import io.javaoperatorsdk.operator.sample.clusterscopedresource.ClusterScopedCustomResourceSpec; +import static io.javaoperatorsdk.operator.IntegrationTestConstants.GARBAGE_COLLECTION_TIMEOUT_SECONDS; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; @@ -49,7 +47,7 @@ void crudOperationOnClusterScopedCustomResource() { }); operator.delete(resource); - await().atMost(Duration.ofSeconds(30)) + await().atMost(Duration.ofSeconds(GARBAGE_COLLECTION_TIMEOUT_SECONDS)) .untilAsserted(() -> assertThat(operator.get(ConfigMap.class, TEST_NAME)).isNull()); } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createupdateeventfilter/CreateUpdateEventFilterTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/createupdateeventfilter/CreateUpdateEventFilterTestCustomResource.java similarity index 64% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createupdateeventfilter/CreateUpdateEventFilterTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/createupdateeventfilter/CreateUpdateEventFilterTestCustomResource.java index 5797a44d9d..31ef818cd6 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createupdateeventfilter/CreateUpdateEventFilterTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/createupdateeventfilter/CreateUpdateEventFilterTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.createupdateeventfilter; +package io.javaoperatorsdk.operator.baseapi.createupdateeventfilter; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; @@ -11,12 +11,7 @@ @ShortNames("cue") public class CreateUpdateEventFilterTestCustomResource extends - CustomResource + CustomResource implements Namespaced { - @Override - protected CreateUpdateEventFilterTestCustomResourceStatus initStatus() { - return new CreateUpdateEventFilterTestCustomResourceStatus(); - } - } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createupdateeventfilter/CreateUpdateEventFilterTestCustomResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/createupdateeventfilter/CreateUpdateEventFilterTestCustomResourceSpec.java similarity index 79% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createupdateeventfilter/CreateUpdateEventFilterTestCustomResourceSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/createupdateeventfilter/CreateUpdateEventFilterTestCustomResourceSpec.java index fcd3807bc8..4575e68db0 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createupdateeventfilter/CreateUpdateEventFilterTestCustomResourceSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/createupdateeventfilter/CreateUpdateEventFilterTestCustomResourceSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.createupdateeventfilter; +package io.javaoperatorsdk.operator.baseapi.createupdateeventfilter; public class CreateUpdateEventFilterTestCustomResourceSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createupdateeventfilter/CreateUpdateEventFilterTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/createupdateeventfilter/CreateUpdateEventFilterTestReconciler.java similarity index 74% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createupdateeventfilter/CreateUpdateEventFilterTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/createupdateeventfilter/CreateUpdateEventFilterTestReconciler.java index ab0369d998..041021cf68 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createupdateeventfilter/CreateUpdateEventFilterTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/createupdateeventfilter/CreateUpdateEventFilterTestReconciler.java @@ -1,50 +1,29 @@ -package io.javaoperatorsdk.operator.sample.createupdateeventfilter; +package io.javaoperatorsdk.operator.baseapi.createupdateeventfilter; import java.util.HashMap; -import java.util.Map; +import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMeta; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; -import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; import io.javaoperatorsdk.operator.processing.event.source.EventSource; import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; @ControllerConfiguration public class CreateUpdateEventFilterTestReconciler - implements Reconciler, - EventSourceInitializer { - - private static final class DirectConfigMapDependentResource - extends - CRUDKubernetesDependentResource { - - private ConfigMap desired; - - private DirectConfigMapDependentResource(Class resourceType) { - super(resourceType); - } - - @Override - protected ConfigMap desired(CreateUpdateEventFilterTestCustomResource primary, - Context context) { - return desired; - } - - @Override - public void setEventSource( - io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource eventSource) { - super.setEventSource(eventSource); - } - } + implements Reconciler { public static final String CONFIG_MAP_TEST_DATA_KEY = "key"; private final AtomicInteger numberOfExecutions = new AtomicInteger(0); - private InformerEventSource informerEventSource; - private DirectConfigMapDependentResource configMapDR = + private final DirectConfigMapDependentResource configMapDR = new DirectConfigMapDependentResource(ConfigMap.class); @Override @@ -88,19 +67,46 @@ private ConfigMap createConfigMap(CreateUpdateEventFilterTestCustomResource reso } @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { - InformerConfiguration informerConfiguration = - InformerConfiguration.from(ConfigMap.class) - .withLabelSelector("integrationtest = " + this.getClass().getSimpleName()) + InformerEventSourceConfiguration informerConfiguration = + InformerEventSourceConfiguration + .from(ConfigMap.class, CreateUpdateEventFilterTestCustomResource.class) + .withInformerConfiguration(c -> c + .withLabelSelector("integrationtest = " + this.getClass().getSimpleName())) .build(); - informerEventSource = new InformerEventSource<>(informerConfiguration, context.getClient()); + final var informerEventSource = + new InformerEventSource( + informerConfiguration, context); this.configMapDR.setEventSource(informerEventSource); - return EventSourceInitializer.nameEventSources(informerEventSource); + return List.of(informerEventSource); } public int getNumberOfExecutions() { return numberOfExecutions.get(); } + + private static final class DirectConfigMapDependentResource + extends + CRUDKubernetesDependentResource { + + private ConfigMap desired; + + private DirectConfigMapDependentResource(Class resourceType) { + super(resourceType); + } + + @Override + protected ConfigMap desired(CreateUpdateEventFilterTestCustomResource primary, + Context context) { + return desired; + } + + @Override + public void setEventSource( + io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource eventSource) { + super.setEventSource(eventSource); + } + } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/CreateUpdateInformerEventSourceEventFilterIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/createupdateeventfilter/CreateUpdateInformerEventSourceEventFilterIT.java similarity index 83% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/CreateUpdateInformerEventSourceEventFilterIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/createupdateeventfilter/CreateUpdateInformerEventSourceEventFilterIT.java index 8a68c9a2b3..9c69087e74 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/CreateUpdateInformerEventSourceEventFilterIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/createupdateeventfilter/CreateUpdateInformerEventSourceEventFilterIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.createupdateeventfilter; import java.time.Duration; @@ -8,11 +8,8 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.createupdateeventfilter.CreateUpdateEventFilterTestCustomResource; -import io.javaoperatorsdk.operator.sample.createupdateeventfilter.CreateUpdateEventFilterTestCustomResourceSpec; -import io.javaoperatorsdk.operator.sample.createupdateeventfilter.CreateUpdateEventFilterTestReconciler; -import static io.javaoperatorsdk.operator.sample.createupdateeventfilter.CreateUpdateEventFilterTestReconciler.CONFIG_MAP_TEST_DATA_KEY; +import static io.javaoperatorsdk.operator.baseapi.createupdateeventfilter.CreateUpdateEventFilterTestReconciler.CONFIG_MAP_TEST_DATA_KEY; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/PreviousAnnotationDisabledIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/createupdateeventfilter/PreviousAnnotationDisabledIT.java similarity index 83% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/PreviousAnnotationDisabledIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/createupdateeventfilter/PreviousAnnotationDisabledIT.java index c636737d0a..209c5fd15c 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/PreviousAnnotationDisabledIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/createupdateeventfilter/PreviousAnnotationDisabledIT.java @@ -1,11 +1,9 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.createupdateeventfilter; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.createupdateeventfilter.CreateUpdateEventFilterTestCustomResource; -import io.javaoperatorsdk.operator.sample.createupdateeventfilter.CreateUpdateEventFilterTestReconciler; class PreviousAnnotationDisabledIT { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/deployment/DeploymentReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/deployment/DeploymentReconciler.java similarity index 89% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/deployment/DeploymentReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/deployment/DeploymentReconciler.java index fc721af52c..ef04ca644a 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/deployment/DeploymentReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/deployment/DeploymentReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.deployment; +package io.javaoperatorsdk.operator.baseapi.deployment; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicInteger; @@ -9,13 +9,15 @@ import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.apps.DeploymentCondition; import io.fabric8.kubernetes.api.model.apps.DeploymentStatus; +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.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -@ControllerConfiguration(labelSelector = "test=KubernetesResourceStatusUpdateIT") +@ControllerConfiguration( + informer = @Informer(labelSelector = "test=KubernetesResourceStatusUpdateIT")) public class DeploymentReconciler implements Reconciler, TestExecutionInfoProvider { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/KubernetesResourceStatusUpdateIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/deployment/KubernetesResourceStatusUpdateIT.java similarity index 93% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/KubernetesResourceStatusUpdateIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/deployment/KubernetesResourceStatusUpdateIT.java index 02cd982af9..dff60df5cd 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/KubernetesResourceStatusUpdateIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/deployment/KubernetesResourceStatusUpdateIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.deployment; import java.util.HashMap; import java.util.List; @@ -18,9 +18,8 @@ import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.apps.DeploymentSpec; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.deployment.DeploymentReconciler; -import static io.javaoperatorsdk.operator.sample.deployment.DeploymentReconciler.STATUS_MESSAGE; +import static io.javaoperatorsdk.operator.baseapi.deployment.DeploymentReconciler.STATUS_MESSAGE; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dynamicgenericeventsourceregistration/DynamicGenericEventSourceRegistrationCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/dynamicgenericeventsourceregistration/DynamicGenericEventSourceRegistrationCustomResource.java similarity index 85% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dynamicgenericeventsourceregistration/DynamicGenericEventSourceRegistrationCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/dynamicgenericeventsourceregistration/DynamicGenericEventSourceRegistrationCustomResource.java index fd82d7bf71..339f14434a 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dynamicgenericeventsourceregistration/DynamicGenericEventSourceRegistrationCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/dynamicgenericeventsourceregistration/DynamicGenericEventSourceRegistrationCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dynamicgenericeventsourceregistration; +package io.javaoperatorsdk.operator.baseapi.dynamicgenericeventsourceregistration; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DynamicGenericEventSourceRegistrationIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/dynamicgenericeventsourceregistration/DynamicGenericEventSourceRegistrationIT.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/DynamicGenericEventSourceRegistrationIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/dynamicgenericeventsourceregistration/DynamicGenericEventSourceRegistrationIT.java index 308630a365..b00573e334 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DynamicGenericEventSourceRegistrationIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/dynamicgenericeventsourceregistration/DynamicGenericEventSourceRegistrationIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.dynamicgenericeventsourceregistration; import java.time.Duration; @@ -9,8 +9,6 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.api.model.Secret; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.dynamicgenericeventsourceregistration.DynamicGenericEventSourceRegistrationCustomResource; -import io.javaoperatorsdk.operator.sample.dynamicgenericeventsourceregistration.DynamicGenericEventSourceRegistrationReconciler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dynamicgenericeventsourceregistration/DynamicGenericEventSourceRegistrationReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/dynamicgenericeventsourceregistration/DynamicGenericEventSourceRegistrationReconciler.java similarity index 86% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dynamicgenericeventsourceregistration/DynamicGenericEventSourceRegistrationReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/dynamicgenericeventsourceregistration/DynamicGenericEventSourceRegistrationReconciler.java index a1bc4a80f8..0abf91f32f 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dynamicgenericeventsourceregistration/DynamicGenericEventSourceRegistrationReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/dynamicgenericeventsourceregistration/DynamicGenericEventSourceRegistrationReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dynamicgenericeventsourceregistration; +package io.javaoperatorsdk.operator.baseapi.dynamicgenericeventsourceregistration; import java.util.Base64; import java.util.Map; @@ -6,7 +6,7 @@ import io.fabric8.kubernetes.api.model.*; import io.fabric8.kubernetes.client.dsl.NonDeletingOperation; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; @@ -28,16 +28,16 @@ public UpdateControl reconc numberOfExecutions.addAndGet(1); - context.eventSourceRetriever().dynamicallyRegisterEventSource(ConfigMap.class.getSimpleName(), + context.eventSourceRetriever().dynamicallyRegisterEventSource( genericInformerFor(ConfigMap.class, context)); - context.eventSourceRetriever().dynamicallyRegisterEventSource(Secret.class.getSimpleName(), + context.eventSourceRetriever().dynamicallyRegisterEventSource( genericInformerFor(Secret.class, context)); context.getClient().resource(secret(primary)).createOr(NonDeletingOperation::update); context.getClient().resource(configMap(primary)).createOr(NonDeletingOperation::update); numberOfEventSources.set(context.eventSourceRetriever() - .getResourceEventSourcesFor(GenericKubernetesResource.class).size()); + .getEventSourcesFor(GenericKubernetesResource.class).size()); return UpdateControl.noUpdate(); } @@ -71,8 +71,11 @@ private InformerEventSource context) { return new InformerEventSource<>( - InformerConfiguration.from(GroupVersionKind.gvkFor(clazz), - context.eventSourceRetriever().eventSourceContextForDynamicRegistration()).build(), + InformerEventSourceConfiguration + .from(GroupVersionKind.gvkFor(clazz), + DynamicGenericEventSourceRegistrationCustomResource.class) + .withName(clazz.getSimpleName()) + .build(), context.eventSourceRetriever().eventSourceContextForDynamicRegistration()); } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ErrorStatusHandlerIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/errorstatushandler/ErrorStatusHandlerIT.java similarity index 89% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/ErrorStatusHandlerIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/errorstatushandler/ErrorStatusHandlerIT.java index e66fd2dcce..6e69a50e82 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ErrorStatusHandlerIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/errorstatushandler/ErrorStatusHandlerIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.errorstatushandler; import java.util.concurrent.TimeUnit; @@ -8,8 +8,6 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; import io.javaoperatorsdk.operator.processing.retry.GenericRetry; -import io.javaoperatorsdk.operator.sample.errorstatushandler.ErrorStatusHandlerTestCustomResource; -import io.javaoperatorsdk.operator.sample.errorstatushandler.ErrorStatusHandlerTestReconciler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/errorstatushandler/ErrorStatusHandlerTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/errorstatushandler/ErrorStatusHandlerTestCustomResource.java similarity index 90% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/errorstatushandler/ErrorStatusHandlerTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/errorstatushandler/ErrorStatusHandlerTestCustomResource.java index d6056ea486..0606115f5f 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/errorstatushandler/ErrorStatusHandlerTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/errorstatushandler/ErrorStatusHandlerTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.errorstatushandler; +package io.javaoperatorsdk.operator.baseapi.errorstatushandler; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/errorstatushandler/ErrorStatusHandlerTestCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/errorstatushandler/ErrorStatusHandlerTestCustomResourceStatus.java similarity index 86% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/errorstatushandler/ErrorStatusHandlerTestCustomResourceStatus.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/errorstatushandler/ErrorStatusHandlerTestCustomResourceStatus.java index 4e54c877a5..42fe4b4b34 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/errorstatushandler/ErrorStatusHandlerTestCustomResourceStatus.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/errorstatushandler/ErrorStatusHandlerTestCustomResourceStatus.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.errorstatushandler; +package io.javaoperatorsdk.operator.baseapi.errorstatushandler; import java.util.ArrayList; import java.util.List; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/errorstatushandler/ErrorStatusHandlerTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/errorstatushandler/ErrorStatusHandlerTestReconciler.java similarity index 90% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/errorstatushandler/ErrorStatusHandlerTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/errorstatushandler/ErrorStatusHandlerTestReconciler.java index 412a784b7c..e51286ef5f 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/errorstatushandler/ErrorStatusHandlerTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/errorstatushandler/ErrorStatusHandlerTestReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.errorstatushandler; +package io.javaoperatorsdk.operator.baseapi.errorstatushandler; import java.util.concurrent.atomic.AtomicInteger; @@ -10,8 +10,7 @@ @ControllerConfiguration public class ErrorStatusHandlerTestReconciler - implements Reconciler, TestExecutionInfoProvider, - ErrorStatusHandler { + implements Reconciler, TestExecutionInfoProvider { private static final Logger log = LoggerFactory.getLogger(ErrorStatusHandlerTestReconciler.class); private final AtomicInteger numberOfExecutions = new AtomicInteger(0); @@ -51,6 +50,6 @@ public ErrorStatusUpdateControl updateErro ensureStatusExists(resource); resource.getStatus().getMessages() .add(ERROR_STATUS_MESSAGE + context.getRetryInfo().orElseThrow().getAttemptCount()); - return ErrorStatusUpdateControl.updateStatus(resource); + return ErrorStatusUpdateControl.patchStatus(resource); } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/EventSourceIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/event/EventSourceIT.java similarity index 84% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/EventSourceIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/event/EventSourceIT.java index 7432e5da0a..227adaeadc 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/EventSourceIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/event/EventSourceIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.event; import java.util.concurrent.TimeUnit; @@ -7,9 +7,6 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.event.EventSourceTestCustomReconciler; -import io.javaoperatorsdk.operator.sample.event.EventSourceTestCustomResource; -import io.javaoperatorsdk.operator.sample.event.EventSourceTestCustomResourceSpec; import io.javaoperatorsdk.operator.support.TestUtils; import static org.assertj.core.api.Assertions.assertThat; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/event/EventSourceTestCustomReconciler.java similarity index 96% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/event/EventSourceTestCustomReconciler.java index 4435f72f98..59f27e5723 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/event/EventSourceTestCustomReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.event; +package io.javaoperatorsdk.operator.baseapi.event; import java.util.concurrent.atomic.AtomicInteger; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/event/EventSourceTestCustomResource.java similarity index 92% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/event/EventSourceTestCustomResource.java index 1a22ec4f8d..2493fc138b 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/event/EventSourceTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.event; +package io.javaoperatorsdk.operator.baseapi.event; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/event/EventSourceTestCustomResourceSpec.java similarity index 82% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomResourceSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/event/EventSourceTestCustomResourceSpec.java index d22f34ce97..203fd21440 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomResourceSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/event/EventSourceTestCustomResourceSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.event; +package io.javaoperatorsdk.operator.baseapi.event; public class EventSourceTestCustomResourceSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/event/EventSourceTestCustomResourceStatus.java similarity index 85% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomResourceStatus.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/event/EventSourceTestCustomResourceStatus.java index 581b4dd74e..bb4c9cd5f1 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomResourceStatus.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/event/EventSourceTestCustomResourceStatus.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.event; +package io.javaoperatorsdk.operator.baseapi.event; public class EventSourceTestCustomResourceStatus { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/FilterIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/filter/FilterIT.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/FilterIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/filter/FilterIT.java index 28ce794de9..634873ec86 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/FilterIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/filter/FilterIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.filter; import java.time.Duration; @@ -7,11 +7,8 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.filter.FilterTestCustomResource; -import io.javaoperatorsdk.operator.sample.filter.FilterTestReconciler; -import io.javaoperatorsdk.operator.sample.filter.FilterTestResourceSpec; -import static io.javaoperatorsdk.operator.sample.filter.FilterTestReconciler.CONFIG_MAP_FILTER_VALUE; +import static io.javaoperatorsdk.operator.baseapi.filter.FilterTestReconciler.CONFIG_MAP_FILTER_VALUE; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/filter/FilterTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/filter/FilterTestCustomResource.java similarity index 91% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/filter/FilterTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/filter/FilterTestCustomResource.java index 3314861ee5..a9f560b9bb 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/filter/FilterTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/filter/FilterTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.filter; +package io.javaoperatorsdk.operator.baseapi.filter; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/filter/FilterTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/filter/FilterTestReconciler.java similarity index 59% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/filter/FilterTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/filter/FilterTestReconciler.java index ab5c9b7400..22a9bc7067 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/filter/FilterTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/filter/FilterTestReconciler.java @@ -1,19 +1,24 @@ -package io.javaoperatorsdk.operator.sample.filter; +package io.javaoperatorsdk.operator.baseapi.filter; +import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; -import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.config.informer.Informer; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.javaoperatorsdk.operator.processing.event.source.EventSource; import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; -@ControllerConfiguration(onUpdateFilter = UpdateFilter.class) +@ControllerConfiguration(informer = @Informer(onUpdateFilter = UpdateFilter.class)) public class FilterTestReconciler - implements Reconciler, - EventSourceInitializer { + implements Reconciler { public static final String CONFIG_MAP_FILTER_VALUE = "config_map_skip_this"; public static final String CUSTOM_RESOURCE_FILTER_VALUE = "custom_resource_skip_this"; @@ -49,16 +54,18 @@ public int getNumberOfExecutions() { } @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { + final var informerConfiguration = InformerEventSourceConfiguration + .from(ConfigMap.class, FilterTestCustomResource.class) + .withInformerConfiguration(c -> c.withOnUpdateFilter((newCM, + oldCM) -> !newCM.getData().get(CM_VALUE_KEY) + .equals(CONFIG_MAP_FILTER_VALUE))) + .build(); InformerEventSource configMapES = - new InformerEventSource<>(InformerConfiguration - .from(ConfigMap.class, context) - .withOnUpdateFilter((newCM, oldCM) -> !newCM.getData().get(CM_VALUE_KEY) - .equals(CONFIG_MAP_FILTER_VALUE)) - .build(), context); + new InformerEventSource<>(informerConfiguration, context); - return EventSourceInitializer.nameEventSources(configMapES); + return List.of(configMapES); } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/filter/FilterTestResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/filter/FilterTestResourceSpec.java similarity index 80% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/filter/FilterTestResourceSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/filter/FilterTestResourceSpec.java index 044b0ea883..1b4cebbfb6 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/filter/FilterTestResourceSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/filter/FilterTestResourceSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.filter; +package io.javaoperatorsdk.operator.baseapi.filter; public class FilterTestResourceSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/filter/FilterTestResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/filter/FilterTestResourceStatus.java new file mode 100644 index 0000000000..1714a2135d --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/filter/FilterTestResourceStatus.java @@ -0,0 +1,5 @@ +package io.javaoperatorsdk.operator.baseapi.filter; + +public class FilterTestResourceStatus { + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/filter/UpdateFilter.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/filter/UpdateFilter.java similarity index 69% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/filter/UpdateFilter.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/filter/UpdateFilter.java index 618cf4f814..7f697d32a1 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/filter/UpdateFilter.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/filter/UpdateFilter.java @@ -1,8 +1,8 @@ -package io.javaoperatorsdk.operator.sample.filter; +package io.javaoperatorsdk.operator.baseapi.filter; import io.javaoperatorsdk.operator.processing.event.source.filter.OnUpdateFilter; -import static io.javaoperatorsdk.operator.sample.filter.FilterTestReconciler.CUSTOM_RESOURCE_FILTER_VALUE; +import static io.javaoperatorsdk.operator.baseapi.filter.FilterTestReconciler.CUSTOM_RESOURCE_FILTER_VALUE; public class UpdateFilter implements OnUpdateFilter { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesresourcehandling/GenericKubernetesResourceHandlingCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/generickubernetesresourcehandling/GenericKubernetesResourceHandlingCustomResource.java similarity index 70% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesresourcehandling/GenericKubernetesResourceHandlingCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/generickubernetesresourcehandling/GenericKubernetesResourceHandlingCustomResource.java index 47b3a14a5a..45f424b8eb 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesresourcehandling/GenericKubernetesResourceHandlingCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/generickubernetesresourcehandling/GenericKubernetesResourceHandlingCustomResource.java @@ -1,11 +1,11 @@ -package io.javaoperatorsdk.operator.sample.generickubernetesresource.generickubernetesresourcehandling; +package io.javaoperatorsdk.operator.baseapi.generickubernetesresourcehandling; 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; -import io.javaoperatorsdk.operator.sample.generickubernetesresource.GenericKubernetesDependentSpec; +import io.javaoperatorsdk.operator.dependent.generickubernetesresource.GenericKubernetesDependentSpec; @Group("sample.javaoperatorsdk") @Version("v1") diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/GenericKubernetesResourceHandlingIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/generickubernetesresourcehandling/GenericKubernetesResourceHandlingIT.java similarity index 64% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/GenericKubernetesResourceHandlingIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/generickubernetesresourcehandling/GenericKubernetesResourceHandlingIT.java index b3ee935553..0e4700a482 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/GenericKubernetesResourceHandlingIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/generickubernetesresourcehandling/GenericKubernetesResourceHandlingIT.java @@ -1,12 +1,11 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.generickubernetesresourcehandling; import org.junit.jupiter.api.extension.RegisterExtension; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.dependent.generickubernetesresource.GenericKubernetesDependentSpec; +import io.javaoperatorsdk.operator.dependent.generickubernetesresource.GenericKubernetesDependentTestBase; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.generickubernetesresource.GenericKubernetesDependentSpec; -import io.javaoperatorsdk.operator.sample.generickubernetesresource.generickubernetesresourcehandling.GenericKubernetesResourceHandlingCustomResource; -import io.javaoperatorsdk.operator.sample.generickubernetesresource.generickubernetesresourcehandling.GenericKubernetesResourceHandlingReconciler; public class GenericKubernetesResourceHandlingIT extends GenericKubernetesDependentTestBase { @@ -23,7 +22,7 @@ public LocallyRunOperatorExtension extension() { } @Override - GenericKubernetesResourceHandlingCustomResource testResource(String name, String data) { + public GenericKubernetesResourceHandlingCustomResource testResource(String name, String data) { var resource = new GenericKubernetesResourceHandlingCustomResource(); resource.setMetadata(new ObjectMetaBuilder() .withName(name) diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesresourcehandling/GenericKubernetesResourceHandlingReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/generickubernetesresourcehandling/GenericKubernetesResourceHandlingReconciler.java similarity index 84% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesresourcehandling/GenericKubernetesResourceHandlingReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/generickubernetesresourcehandling/GenericKubernetesResourceHandlingReconciler.java index 45be0281f6..2d7cf217bc 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesresourcehandling/GenericKubernetesResourceHandlingReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/generickubernetesresourcehandling/GenericKubernetesResourceHandlingReconciler.java @@ -1,12 +1,13 @@ -package io.javaoperatorsdk.operator.sample.generickubernetesresource.generickubernetesresourcehandling; +package io.javaoperatorsdk.operator.baseapi.generickubernetesresourcehandling; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; +import java.util.List; import java.util.Map; import io.fabric8.kubernetes.api.model.GenericKubernetesResource; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; import io.javaoperatorsdk.operator.api.reconciler.*; import io.javaoperatorsdk.operator.processing.GroupVersionKind; import io.javaoperatorsdk.operator.processing.event.source.EventSource; @@ -14,8 +15,7 @@ @ControllerConfiguration public class GenericKubernetesResourceHandlingReconciler - implements Reconciler, - EventSourceInitializer { + implements Reconciler { public static final String VERSION = "v1"; @@ -65,13 +65,14 @@ GenericKubernetesResource desiredConfigMap( @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { - var informerEventSource = new InformerEventSource<>(InformerConfiguration.from( - new GroupVersionKind("", VERSION, KIND), context).build(), + var informerEventSource = new InformerEventSource<>(InformerEventSourceConfiguration.from( + new GroupVersionKind("", VERSION, KIND), + GenericKubernetesResourceHandlingCustomResource.class).build(), context); - return EventSourceInitializer.nameEventSources(informerEventSource); + return List.of(informerEventSource); } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/GracefulStopIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/gracefulstop/GracefulStopIT.java similarity index 71% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/GracefulStopIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/gracefulstop/GracefulStopIT.java index 715921ecbb..a28d6da07d 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/GracefulStopIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/gracefulstop/GracefulStopIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.gracefulstop; import java.time.Duration; @@ -7,37 +7,29 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.gracefulstop.GracefulStopTestCustomResource; -import io.javaoperatorsdk.operator.sample.gracefulstop.GracefulStopTestCustomResourceSpec; -import io.javaoperatorsdk.operator.sample.gracefulstop.GracefulStopTestReconciler; -import static io.javaoperatorsdk.operator.sample.gracefulstop.GracefulStopTestReconciler.RECONCILER_SLEEP; +import static io.javaoperatorsdk.operator.baseapi.gracefulstop.GracefulStopTestReconciler.RECONCILER_SLEEP; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; public class GracefulStopIT { public static final String TEST_1 = "test1"; - public static final String TEST_2 = "test2"; @RegisterExtension LocallyRunOperatorExtension operator = LocallyRunOperatorExtension.builder() - .withConfigurationService(o -> o.withCloseClientOnStop(false)) + .withConfigurationService(o -> o.withCloseClientOnStop(false) + .withReconciliationTerminationTimeout(Duration.ofMillis(RECONCILER_SLEEP))) .withReconciler(new GracefulStopTestReconciler()) .build(); @Test - void stopsGracefullyWIthTimeout() { - testGracefulStop(TEST_1, RECONCILER_SLEEP, 2); + void stopsGracefullyWithTimeoutConfiguration() { + testGracefulStop(TEST_1, 2); } - @Test - void stopsGracefullyWithExpiredTimeout() { - testGracefulStop(TEST_2, RECONCILER_SLEEP / 5, 1); - } - - private void testGracefulStop(String resourceName, int stopTimeout, int expectedFinalGeneration) { + private void testGracefulStop(String resourceName, int expectedFinalGeneration) { var testRes = operator.create(testResource(resourceName)); await().untilAsserted(() -> { var r = operator.get(GracefulStopTestCustomResource.class, resourceName); @@ -54,7 +46,7 @@ private void testGracefulStop(String resourceName, int stopTimeout, int expected () -> assertThat(operator.getReconcilerOfType(GracefulStopTestReconciler.class) .getNumberOfExecutions()).isEqualTo(2)); - operator.getOperator().stop(Duration.ofMillis(stopTimeout)); + operator.getOperator().stop(); await().untilAsserted(() -> { var r = operator.get(GracefulStopTestCustomResource.class, resourceName); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/gracefulstop/GracefulStopTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/gracefulstop/GracefulStopTestCustomResource.java similarity index 89% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/gracefulstop/GracefulStopTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/gracefulstop/GracefulStopTestCustomResource.java index 529c5ff480..0a3f0c680f 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/gracefulstop/GracefulStopTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/gracefulstop/GracefulStopTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.gracefulstop; +package io.javaoperatorsdk.operator.baseapi.gracefulstop; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/gracefulstop/GracefulStopTestCustomResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/gracefulstop/GracefulStopTestCustomResourceSpec.java similarity index 76% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/gracefulstop/GracefulStopTestCustomResourceSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/gracefulstop/GracefulStopTestCustomResourceSpec.java index 4d1f45e646..f1c4b42af2 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/gracefulstop/GracefulStopTestCustomResourceSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/gracefulstop/GracefulStopTestCustomResourceSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.gracefulstop; +package io.javaoperatorsdk.operator.baseapi.gracefulstop; public class GracefulStopTestCustomResourceSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/gracefulstop/GracefulStopTestCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/gracefulstop/GracefulStopTestCustomResourceStatus.java new file mode 100644 index 0000000000..3e4e992399 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/gracefulstop/GracefulStopTestCustomResourceStatus.java @@ -0,0 +1,14 @@ +package io.javaoperatorsdk.operator.baseapi.gracefulstop; + +public class GracefulStopTestCustomResourceStatus { + + private long observedGeneration; + + public long getObservedGeneration() { + return observedGeneration; + } + + public void setObservedGeneration(long observedGeneration) { + this.observedGeneration = observedGeneration; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/gracefulstop/GracefulStopTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/gracefulstop/GracefulStopTestReconciler.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/gracefulstop/GracefulStopTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/gracefulstop/GracefulStopTestReconciler.java index cf266c0b48..7b33c68722 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/gracefulstop/GracefulStopTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/gracefulstop/GracefulStopTestReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.gracefulstop; +package io.javaoperatorsdk.operator.baseapi.gracefulstop; import java.util.concurrent.atomic.AtomicInteger; @@ -22,6 +22,7 @@ public UpdateControl reconcile( numberOfExecutions.addAndGet(1); resource.setStatus(new GracefulStopTestCustomResourceStatus()); + resource.getStatus().setObservedGeneration(resource.getMetadata().getGeneration()); Thread.sleep(RECONCILER_SLEEP); return UpdateControl.patchStatus(resource); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/InformerEventSourceIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informereventsource/InformerEventSourceIT.java similarity index 83% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/InformerEventSourceIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informereventsource/InformerEventSourceIT.java index 45983145da..81e0a0febe 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/InformerEventSourceIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informereventsource/InformerEventSourceIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.informereventsource; import java.util.HashMap; import java.util.concurrent.TimeUnit; @@ -9,12 +9,10 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.informereventsource.InformerEventSourceTestCustomReconciler; -import io.javaoperatorsdk.operator.sample.informereventsource.InformerEventSourceTestCustomResource; -import static io.javaoperatorsdk.operator.sample.informereventsource.InformerEventSourceTestCustomReconciler.MISSING_CONFIG_MAP; -import static io.javaoperatorsdk.operator.sample.informereventsource.InformerEventSourceTestCustomReconciler.RELATED_RESOURCE_NAME; -import static io.javaoperatorsdk.operator.sample.informereventsource.InformerEventSourceTestCustomReconciler.TARGET_CONFIG_MAP_KEY; +import static io.javaoperatorsdk.operator.baseapi.informereventsource.InformerEventSourceTestCustomReconciler.MISSING_CONFIG_MAP; +import static io.javaoperatorsdk.operator.baseapi.informereventsource.InformerEventSourceTestCustomReconciler.RELATED_RESOURCE_NAME; +import static io.javaoperatorsdk.operator.baseapi.informereventsource.InformerEventSourceTestCustomReconciler.TARGET_CONFIG_MAP_KEY; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informereventsource/InformerEventSourceTestCustomReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informereventsource/InformerEventSourceTestCustomReconciler.java similarity index 69% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informereventsource/InformerEventSourceTestCustomReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informereventsource/InformerEventSourceTestCustomReconciler.java index bf92550542..5028d6a0f4 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informereventsource/InformerEventSourceTestCustomReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informereventsource/InformerEventSourceTestCustomReconciler.java @@ -1,6 +1,6 @@ -package io.javaoperatorsdk.operator.sample.informereventsource; +package io.javaoperatorsdk.operator.baseapi.informereventsource; -import java.util.Map; +import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; @@ -8,13 +8,8 @@ import org.slf4j.LoggerFactory; import io.fabric8.kubernetes.api.model.ConfigMap; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; -import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; -import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; -import io.javaoperatorsdk.operator.api.reconciler.EventSourceInitializer; -import io.javaoperatorsdk.operator.api.reconciler.Reconciler; -import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.*; import io.javaoperatorsdk.operator.processing.event.source.EventSource; import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; import io.javaoperatorsdk.operator.processing.event.source.informer.Mappers; @@ -25,29 +20,31 @@ */ @ControllerConfiguration public class InformerEventSourceTestCustomReconciler - implements Reconciler, - EventSourceInitializer { + implements Reconciler { private static final Logger LOGGER = LoggerFactory.getLogger(InformerEventSourceTestCustomReconciler.class); public static final String RELATED_RESOURCE_NAME = "relatedResourceName"; + public static final String RELATED_RESOURCE_TYPE = "relatedResourceType"; public static final String TARGET_CONFIG_MAP_KEY = "targetStatus"; public static final String MISSING_CONFIG_MAP = "Missing Config Map"; private final AtomicInteger numberOfExecutions = new AtomicInteger(0); @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { - InformerConfiguration config = - InformerConfiguration.from(ConfigMap.class) - .withSecondaryToPrimaryMapper(Mappers.fromAnnotation(RELATED_RESOURCE_NAME)) + InformerEventSourceConfiguration config = + InformerEventSourceConfiguration + .from(ConfigMap.class, InformerEventSourceTestCustomResource.class) + .withSecondaryToPrimaryMapper( + Mappers.fromAnnotation(RELATED_RESOURCE_NAME, RELATED_RESOURCE_TYPE, + InformerEventSourceTestCustomResource.class)) .build(); - return EventSourceInitializer - .nameEventSources(new InformerEventSource<>(config, context)); + return List.of(new InformerEventSource<>(config, context)); } @Override diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informereventsource/InformerEventSourceTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informereventsource/InformerEventSourceTestCustomResource.java similarity index 90% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informereventsource/InformerEventSourceTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informereventsource/InformerEventSourceTestCustomResource.java index ff1c6758bb..4d1077c64e 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informereventsource/InformerEventSourceTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informereventsource/InformerEventSourceTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.informereventsource; +package io.javaoperatorsdk.operator.baseapi.informereventsource; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informereventsource/InformerEventSourceTestCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informereventsource/InformerEventSourceTestCustomResourceStatus.java similarity index 83% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informereventsource/InformerEventSourceTestCustomResourceStatus.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informereventsource/InformerEventSourceTestCustomResourceStatus.java index b4b6b93958..529b53db13 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informereventsource/InformerEventSourceTestCustomResourceStatus.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informereventsource/InformerEventSourceTestCustomResourceStatus.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.informereventsource; +package io.javaoperatorsdk.operator.baseapi.informereventsource; public class InformerEventSourceTestCustomResourceStatus { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informerremotecluster/InformerRemoteClusterCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informerremotecluster/InformerRemoteClusterCustomResource.java new file mode 100644 index 0000000000..c7e6ee43b4 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informerremotecluster/InformerRemoteClusterCustomResource.java @@ -0,0 +1,14 @@ +package io.javaoperatorsdk.operator.baseapi.informerremotecluster; + +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("sample.javaoperatorsdk") +@Version("v1") +@ShortNames("irc") +public class InformerRemoteClusterCustomResource + extends CustomResource implements Namespaced { +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informerremotecluster/InformerRemoteClusterIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informerremotecluster/InformerRemoteClusterIT.java new file mode 100644 index 0000000000..3ad274d954 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informerremotecluster/InformerRemoteClusterIT.java @@ -0,0 +1,88 @@ +package io.javaoperatorsdk.operator.baseapi.informerremotecluster; + +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import io.fabric8.kubeapitest.junit.EnableKubeAPIServer; +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; +import io.javaoperatorsdk.operator.processing.event.source.informer.Mappers; + +import static io.javaoperatorsdk.operator.baseapi.informerremotecluster.InformerRemoteClusterReconciler.DATA_KEY; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +@EnableKubeAPIServer +class InformerRemoteClusterIT { + + public static final String NAME = "test1"; + public static final String CONFIG_MAP_NAME = "testcm"; + public static final String INITIAL_VALUE = "initial_value"; + public static final String CHANGED_VALUE = "changed_value"; + public static final String CM_NAMESPACE = "default"; + + // injected by Kube API Test. Client for another cluster. + static KubernetesClient kubernetesClient; + + @RegisterExtension + LocallyRunOperatorExtension extension = + LocallyRunOperatorExtension.builder() + .withReconciler(new InformerRemoteClusterReconciler(kubernetesClient)) + .build(); + + @Test + void testRemoteClusterInformer() { + var r = extension.create(testCustomResource()); + + var cm = kubernetesClient.configMaps() + .resource(remoteConfigMap(r.getMetadata().getName(), + r.getMetadata().getNamespace())) + .create(); + + // config map does not exist on the primary resource cluster + assertThat(extension.getKubernetesClient().configMaps() + .inNamespace(CM_NAMESPACE) + .withName(CONFIG_MAP_NAME).get()).isNull(); + + await().untilAsserted(() -> { + var cr = extension.get(InformerRemoteClusterCustomResource.class, NAME); + assertThat(cr.getStatus()).isNotNull(); + assertThat(cr.getStatus().getRemoteConfigMapMessage()).isEqualTo(INITIAL_VALUE); + }); + + cm.getData().put(DATA_KEY, CHANGED_VALUE); + kubernetesClient.configMaps().resource(cm).update(); + + await().untilAsserted(() -> { + var cr = extension.get(InformerRemoteClusterCustomResource.class, NAME); + assertThat(cr.getStatus().getRemoteConfigMapMessage()).isEqualTo(CHANGED_VALUE); + }); + } + + InformerRemoteClusterCustomResource testCustomResource() { + var res = new InformerRemoteClusterCustomResource(); + res.setMetadata(new ObjectMetaBuilder() + .withName(NAME) + .build()); + return res; + } + + ConfigMap remoteConfigMap(String ownerName, String ownerNamespace) { + return new ConfigMapBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName(CONFIG_MAP_NAME) + .withNamespace(CM_NAMESPACE) + .withAnnotations(Map.of( + Mappers.DEFAULT_ANNOTATION_FOR_NAME, ownerName, + Mappers.DEFAULT_ANNOTATION_FOR_NAMESPACE, ownerNamespace)) + .build()) + .withData(Map.of(DATA_KEY, INITIAL_VALUE)) + .build(); + } + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informerremotecluster/InformerRemoteClusterReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informerremotecluster/InformerRemoteClusterReconciler.java new file mode 100644 index 0000000000..9246e0bbd5 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informerremotecluster/InformerRemoteClusterReconciler.java @@ -0,0 +1,66 @@ +package io.javaoperatorsdk.operator.baseapi.informerremotecluster; + +import java.util.List; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; +import io.javaoperatorsdk.operator.processing.event.source.EventSource; +import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; +import io.javaoperatorsdk.operator.processing.event.source.informer.Mappers; + +@ControllerConfiguration +public class InformerRemoteClusterReconciler + implements Reconciler { + + public static final String DATA_KEY = "key"; + + private final KubernetesClient remoteClient; + + public InformerRemoteClusterReconciler(KubernetesClient remoteClient) { + this.remoteClient = remoteClient; + } + + @Override + public UpdateControl reconcile( + InformerRemoteClusterCustomResource resource, + Context context) throws Exception { + + return context.getSecondaryResource(ConfigMap.class).map(cm -> { + var r = new InformerRemoteClusterCustomResource(); + r.setMetadata(new ObjectMetaBuilder() + .withName(resource.getMetadata().getName()) + .withNamespace(resource.getMetadata().getNamespace()) + .build()); + r.setStatus(new InformerRemoteClusterStatus()); + r.getStatus().setRemoteConfigMapMessage(cm.getData().get(DATA_KEY)); + return UpdateControl.patchStatus(r); + }).orElseGet(UpdateControl::noUpdate); + } + + @Override + public List> prepareEventSources( + EventSourceContext context) { + + var es = new InformerEventSource<>(InformerEventSourceConfiguration + .from(ConfigMap.class, InformerRemoteClusterCustomResource.class) + // owner references do not work cross cluster, using + // annotations here to reference primary resource + .withSecondaryToPrimaryMapper( + Mappers.fromDefaultAnnotations(InformerRemoteClusterCustomResource.class)) + // setting remote client for informer + .withKubernetesClient(remoteClient) + .withInformerConfiguration( + InformerConfiguration.Builder::withWatchAllNamespaces) + .build(), context); + + return List.of(es); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informerremotecluster/InformerRemoteClusterStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informerremotecluster/InformerRemoteClusterStatus.java new file mode 100644 index 0000000000..e49322fb10 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/informerremotecluster/InformerRemoteClusterStatus.java @@ -0,0 +1,14 @@ +package io.javaoperatorsdk.operator.baseapi.informerremotecluster; + +public class InformerRemoteClusterStatus { + + private String remoteConfigMapMessage; + + public String getRemoteConfigMapMessage() { + return remoteConfigMapMessage; + } + + public void setRemoteConfigMapMessage(String remoteConfigMapMessage) { + this.remoteConfigMapMessage = remoteConfigMapMessage; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/LabelSelectorIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/labelselector/LabelSelectorIT.java similarity index 75% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/LabelSelectorIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/labelselector/LabelSelectorIT.java index 8324a8c1d2..41411fa16f 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/LabelSelectorIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/labelselector/LabelSelectorIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.labelselector; import java.time.Duration; import java.util.Collections; @@ -9,11 +9,9 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.labelselector.LabelSelectorTestCustomResource; -import io.javaoperatorsdk.operator.sample.labelselector.LabelSelectorTestReconciler; -import static io.javaoperatorsdk.operator.sample.labelselector.LabelSelectorTestReconciler.LABEL_KEY; -import static io.javaoperatorsdk.operator.sample.labelselector.LabelSelectorTestReconciler.LABEL_VALUE; +import static io.javaoperatorsdk.operator.baseapi.labelselector.LabelSelectorTestReconciler.LABEL_KEY; +import static io.javaoperatorsdk.operator.baseapi.labelselector.LabelSelectorTestReconciler.LABEL_VALUE; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; @@ -24,7 +22,6 @@ class LabelSelectorIT { LocallyRunOperatorExtension.builder().withReconciler(new LabelSelectorTestReconciler()) .build(); - @Test void filtersCustomResourceByLabel() { operator.create(resource("r1", true)); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/labelselector/LabelSelectorTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/labelselector/LabelSelectorTestCustomResource.java similarity index 88% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/labelselector/LabelSelectorTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/labelselector/LabelSelectorTestCustomResource.java index 0b304aa9e7..321c684eef 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/labelselector/LabelSelectorTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/labelselector/LabelSelectorTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.labelselector; +package io.javaoperatorsdk.operator.baseapi.labelselector; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/labelselector/LabelSelectorTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/labelselector/LabelSelectorTestReconciler.java similarity index 65% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/labelselector/LabelSelectorTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/labelselector/LabelSelectorTestReconciler.java index 3fc0a78630..a225f6a7be 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/labelselector/LabelSelectorTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/labelselector/LabelSelectorTestReconciler.java @@ -1,14 +1,16 @@ -package io.javaoperatorsdk.operator.sample.labelselector; +package io.javaoperatorsdk.operator.baseapi.labelselector; import java.util.concurrent.atomic.AtomicInteger; +import io.javaoperatorsdk.operator.api.config.informer.Informer; import io.javaoperatorsdk.operator.api.reconciler.*; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -import static io.javaoperatorsdk.operator.sample.labelselector.LabelSelectorTestReconciler.LABEL_KEY; -import static io.javaoperatorsdk.operator.sample.labelselector.LabelSelectorTestReconciler.LABEL_VALUE; +import static io.javaoperatorsdk.operator.baseapi.labelselector.LabelSelectorTestReconciler.LABEL_KEY; +import static io.javaoperatorsdk.operator.baseapi.labelselector.LabelSelectorTestReconciler.LABEL_VALUE; -@ControllerConfiguration(labelSelector = LABEL_KEY + "=" + LABEL_VALUE) +@ControllerConfiguration( + informer = @Informer(labelSelector = LABEL_KEY + "=" + LABEL_VALUE)) public class LabelSelectorTestReconciler implements Reconciler, TestExecutionInfoProvider { @@ -20,6 +22,7 @@ public class LabelSelectorTestReconciler @Override public UpdateControl reconcile( LabelSelectorTestCustomResource resource, Context context) { + numberOfExecutions.addAndGet(1); return UpdateControl.noUpdate(); } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/leaderelectionchangenamespace/LeaderElectionChangeNamespaceCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/leaderelectionchangenamespace/LeaderElectionChangeNamespaceCustomResource.java similarity index 86% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/leaderelectionchangenamespace/LeaderElectionChangeNamespaceCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/leaderelectionchangenamespace/LeaderElectionChangeNamespaceCustomResource.java index 8a37720955..7b4a38d429 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/leaderelectionchangenamespace/LeaderElectionChangeNamespaceCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/leaderelectionchangenamespace/LeaderElectionChangeNamespaceCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.leaderelectionchangenamespace; +package io.javaoperatorsdk.operator.baseapi.leaderelectionchangenamespace; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/LeaderElectionChangeNamespaceIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/leaderelectionchangenamespace/LeaderElectionChangeNamespaceIT.java similarity index 92% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/LeaderElectionChangeNamespaceIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/leaderelectionchangenamespace/LeaderElectionChangeNamespaceIT.java index 1a3a450b90..dab495ba18 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/LeaderElectionChangeNamespaceIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/leaderelectionchangenamespace/LeaderElectionChangeNamespaceIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.leaderelectionchangenamespace; import java.time.Duration; import java.time.ZonedDateTime; @@ -16,8 +16,6 @@ import io.fabric8.kubernetes.client.KubernetesClientBuilder; import io.javaoperatorsdk.operator.api.config.LeaderElectionConfiguration; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.leaderelectionchangenamespace.LeaderElectionChangeNamespaceCustomResource; -import io.javaoperatorsdk.operator.sample.leaderelectionchangenamespace.LeaderElectionChangeNamespaceReconciler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/leaderelectionchangenamespace/LeaderElectionChangeNamespaceReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/leaderelectionchangenamespace/LeaderElectionChangeNamespaceReconciler.java similarity index 93% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/leaderelectionchangenamespace/LeaderElectionChangeNamespaceReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/leaderelectionchangenamespace/LeaderElectionChangeNamespaceReconciler.java index 8651a4774e..70b45035b7 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/leaderelectionchangenamespace/LeaderElectionChangeNamespaceReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/leaderelectionchangenamespace/LeaderElectionChangeNamespaceReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.leaderelectionchangenamespace; +package io.javaoperatorsdk.operator.baseapi.leaderelectionchangenamespace; import java.util.concurrent.atomic.AtomicInteger; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/manualobservedgeneration/ManualObservedGenerationCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/manualobservedgeneration/ManualObservedGenerationCustomResource.java new file mode 100644 index 0000000000..d33f9dd5b3 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/manualobservedgeneration/ManualObservedGenerationCustomResource.java @@ -0,0 +1,15 @@ +package io.javaoperatorsdk.operator.baseapi.manualobservedgeneration; + +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("sample.javaoperatorsdk") +@Version("v1") +@ShortNames("mog") +public class ManualObservedGenerationCustomResource + extends CustomResource + implements Namespaced { +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/manualobservedgeneration/ManualObservedGenerationIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/manualobservedgeneration/ManualObservedGenerationIT.java new file mode 100644 index 0000000000..743f73742d --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/manualobservedgeneration/ManualObservedGenerationIT.java @@ -0,0 +1,51 @@ +package io.javaoperatorsdk.operator.baseapi.manualobservedgeneration; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public class ManualObservedGenerationIT { + + public static final String RESOURCE_NAME = "test1"; + @RegisterExtension + LocallyRunOperatorExtension extension = + LocallyRunOperatorExtension.builder().withReconciler(new ManualObservedGenerationReconciler()) + .build(); + + @Test + void observedGenerationUpdated() { + extension.create(testResource()); + + await().untilAsserted(() -> { + var r = extension.get(ManualObservedGenerationCustomResource.class, RESOURCE_NAME); + assertThat(r).isNotNull(); + assertThat(r.getStatus().getObservedGeneration()).isEqualTo(1); + assertThat(r.getStatus().getObservedGeneration()).isEqualTo(r.getMetadata().getGeneration()); + }); + + var changed = testResource(); + changed.getSpec().setValue("changed value"); + extension.replace(changed); + + await().untilAsserted(() -> { + var r = extension.get(ManualObservedGenerationCustomResource.class, RESOURCE_NAME); + assertThat(r.getStatus().getObservedGeneration()).isEqualTo(2); + assertThat(r.getStatus().getObservedGeneration()).isEqualTo(r.getMetadata().getGeneration()); + }); + } + + ManualObservedGenerationCustomResource testResource() { + var res = new ManualObservedGenerationCustomResource(); + res.setMetadata(new ObjectMetaBuilder() + .withName(RESOURCE_NAME) + .build()); + res.setSpec(new ManualObservedGenerationSpec()); + res.getSpec().setValue("Initial Value"); + return res; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/manualobservedgeneration/ManualObservedGenerationReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/manualobservedgeneration/ManualObservedGenerationReconciler.java new file mode 100644 index 0000000000..865d099766 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/manualobservedgeneration/ManualObservedGenerationReconciler.java @@ -0,0 +1,48 @@ +package io.javaoperatorsdk.operator.baseapi.manualobservedgeneration; + +import java.util.Objects; +import java.util.concurrent.atomic.AtomicInteger; + +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.api.reconciler.*; + +@ControllerConfiguration +public class ManualObservedGenerationReconciler + implements Reconciler { + + private final AtomicInteger numberOfExecutions = new AtomicInteger(0); + + @Override + public UpdateControl reconcile( + ManualObservedGenerationCustomResource resource, + Context context) { + numberOfExecutions.addAndGet(1); + var resourceForStatusPatch = resourceForStatusPatch(resource); + if (!Objects.equals(resource.getMetadata().getGeneration(), + resourceForStatusPatch.getStatus().getObservedGeneration())) { + resourceForStatusPatch.getStatus() + .setObservedGeneration(resource.getMetadata().getGeneration()); + return UpdateControl.patchStatus(resourceForStatusPatch); + } else { + return UpdateControl.noUpdate(); + } + } + + private ManualObservedGenerationCustomResource resourceForStatusPatch( + ManualObservedGenerationCustomResource original) { + var res = new ManualObservedGenerationCustomResource(); + res.setMetadata(new ObjectMetaBuilder() + .withName(original.getMetadata().getName()) + .withNamespace(original.getMetadata().getNamespace()) + .build()); + res.setStatus(original.getStatus()); + if (res.getStatus() == null) { + res.setStatus(new ManualObservedGenerationStatus()); + } + return res; + } + + public int getNumberOfExecutions() { + return numberOfExecutions.get(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/manualobservedgeneration/ManualObservedGenerationSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/manualobservedgeneration/ManualObservedGenerationSpec.java new file mode 100644 index 0000000000..4c7076efd1 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/manualobservedgeneration/ManualObservedGenerationSpec.java @@ -0,0 +1,14 @@ +package io.javaoperatorsdk.operator.baseapi.manualobservedgeneration; + +public class ManualObservedGenerationSpec { + + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/manualobservedgeneration/ManualObservedGenerationStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/manualobservedgeneration/ManualObservedGenerationStatus.java new file mode 100644 index 0000000000..b70a4f18da --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/manualobservedgeneration/ManualObservedGenerationStatus.java @@ -0,0 +1,14 @@ +package io.javaoperatorsdk.operator.baseapi.manualobservedgeneration; + +public class ManualObservedGenerationStatus { + + private long observedGeneration; + + public long getObservedGeneration() { + return observedGeneration; + } + + public void setObservedGeneration(long observedGeneration) { + this.observedGeneration = observedGeneration; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MaxIntervalIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/maxinterval/MaxIntervalIT.java similarity index 86% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/MaxIntervalIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/maxinterval/MaxIntervalIT.java index 35ae316f53..460b374071 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MaxIntervalIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/maxinterval/MaxIntervalIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.maxinterval; import java.util.concurrent.TimeUnit; @@ -7,8 +7,6 @@ import io.fabric8.kubernetes.api.model.ObjectMeta; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.maxinterval.MaxIntervalTestCustomResource; -import io.javaoperatorsdk.operator.sample.maxinterval.MaxIntervalTestReconciler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/maxinterval/MaxIntervalTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/maxinterval/MaxIntervalTestCustomResource.java similarity index 79% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/maxinterval/MaxIntervalTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/maxinterval/MaxIntervalTestCustomResource.java index 1c6cf81453..d9f7cb74ba 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/maxinterval/MaxIntervalTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/maxinterval/MaxIntervalTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.maxinterval; +package io.javaoperatorsdk.operator.baseapi.maxinterval; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; @@ -12,6 +12,6 @@ @Kind("MaxIntervalTestCustomResource") @ShortNames("mit") public class MaxIntervalTestCustomResource - extends CustomResource + extends CustomResource implements Namespaced { } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/maxinterval/MaxIntervalTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/maxinterval/MaxIntervalTestReconciler.java similarity index 95% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/maxinterval/MaxIntervalTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/maxinterval/MaxIntervalTestReconciler.java index de77a0220c..ce9197cff5 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/maxinterval/MaxIntervalTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/maxinterval/MaxIntervalTestReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.maxinterval; +package io.javaoperatorsdk.operator.baseapi.maxinterval; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MaxIntervalAfterRetryIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/maxintervalafterretry/MaxIntervalAfterRetryIT.java similarity index 84% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/MaxIntervalAfterRetryIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/maxintervalafterretry/MaxIntervalAfterRetryIT.java index 84814e127e..ce53c483cc 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MaxIntervalAfterRetryIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/maxintervalafterretry/MaxIntervalAfterRetryIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.maxintervalafterretry; import java.util.concurrent.TimeUnit; @@ -7,8 +7,6 @@ import io.fabric8.kubernetes.api.model.ObjectMeta; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.maxintervalafterretry.MaxIntervalAfterRetryTestCustomResource; -import io.javaoperatorsdk.operator.sample.maxintervalafterretry.MaxIntervalAfterRetryTestReconciler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/maxintervalafterretry/MaxIntervalAfterRetryTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/maxintervalafterretry/MaxIntervalAfterRetryTestCustomResource.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/maxintervalafterretry/MaxIntervalAfterRetryTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/maxintervalafterretry/MaxIntervalAfterRetryTestCustomResource.java index cc914f6c48..85328a26a3 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/maxintervalafterretry/MaxIntervalAfterRetryTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/maxintervalafterretry/MaxIntervalAfterRetryTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.maxintervalafterretry; +package io.javaoperatorsdk.operator.baseapi.maxintervalafterretry; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/maxintervalafterretry/MaxIntervalAfterRetryTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/maxintervalafterretry/MaxIntervalAfterRetryTestReconciler.java similarity index 95% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/maxintervalafterretry/MaxIntervalAfterRetryTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/maxintervalafterretry/MaxIntervalAfterRetryTestReconciler.java index 5608731a3e..cf9a42f0e2 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/maxintervalafterretry/MaxIntervalAfterRetryTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/maxintervalafterretry/MaxIntervalAfterRetryTestReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.maxintervalafterretry; +package io.javaoperatorsdk.operator.baseapi.maxintervalafterretry; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplereconcilersametype/MultipleReconcilerSameTypeCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplereconcilersametype/MultipleReconcilerSameTypeCustomResource.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplereconcilersametype/MultipleReconcilerSameTypeCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplereconcilersametype/MultipleReconcilerSameTypeCustomResource.java index 53c731e5e7..d7e3fa5c37 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplereconcilersametype/MultipleReconcilerSameTypeCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplereconcilersametype/MultipleReconcilerSameTypeCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multiplereconcilersametype; +package io.javaoperatorsdk.operator.baseapi.multiplereconcilersametype; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleReconcilerSameTypeIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplereconcilersametype/MultipleReconcilerSameTypeIT.java similarity index 85% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleReconcilerSameTypeIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplereconcilersametype/MultipleReconcilerSameTypeIT.java index b0be12bd91..57e4ad795b 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleReconcilerSameTypeIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplereconcilersametype/MultipleReconcilerSameTypeIT.java @@ -1,13 +1,10 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.multiplereconcilersametype; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.multiplereconcilersametype.MultipleReconcilerSameTypeCustomResource; -import io.javaoperatorsdk.operator.sample.multiplereconcilersametype.MultipleReconcilerSameTypeReconciler1; -import io.javaoperatorsdk.operator.sample.multiplereconcilersametype.MultipleReconcilerSameTypeReconciler2; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplereconcilersametype/MultipleReconcilerSameTypeReconciler1.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplereconcilersametype/MultipleReconcilerSameTypeReconciler1.java similarity index 80% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplereconcilersametype/MultipleReconcilerSameTypeReconciler1.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplereconcilersametype/MultipleReconcilerSameTypeReconciler1.java index e32a6ad7e2..a3ffd9667e 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplereconcilersametype/MultipleReconcilerSameTypeReconciler1.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplereconcilersametype/MultipleReconcilerSameTypeReconciler1.java @@ -1,11 +1,12 @@ -package io.javaoperatorsdk.operator.sample.multiplereconcilersametype; +package io.javaoperatorsdk.operator.baseapi.multiplereconcilersametype; import java.util.concurrent.atomic.AtomicInteger; +import io.javaoperatorsdk.operator.api.config.informer.Informer; import io.javaoperatorsdk.operator.api.reconciler.*; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -@ControllerConfiguration(labelSelector = "reconciler = 1") +@ControllerConfiguration(informer = @Informer(labelSelector = "reconciler = 1")) public class MultipleReconcilerSameTypeReconciler1 implements Reconciler, TestExecutionInfoProvider { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplereconcilersametype/MultipleReconcilerSameTypeReconciler2.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplereconcilersametype/MultipleReconcilerSameTypeReconciler2.java similarity index 83% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplereconcilersametype/MultipleReconcilerSameTypeReconciler2.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplereconcilersametype/MultipleReconcilerSameTypeReconciler2.java index 73b082f3b0..ee446a7cf4 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplereconcilersametype/MultipleReconcilerSameTypeReconciler2.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplereconcilersametype/MultipleReconcilerSameTypeReconciler2.java @@ -1,14 +1,15 @@ -package io.javaoperatorsdk.operator.sample.multiplereconcilersametype; +package io.javaoperatorsdk.operator.baseapi.multiplereconcilersametype; import java.util.concurrent.atomic.AtomicInteger; +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.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -@ControllerConfiguration(labelSelector = "reconciler != 1") +@ControllerConfiguration(informer = @Informer(labelSelector = "reconciler != 1")) public class MultipleReconcilerSameTypeReconciler2 implements Reconciler, TestExecutionInfoProvider { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplereconcilersametype/MultipleReconcilerSameTypeStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplereconcilersametype/MultipleReconcilerSameTypeStatus.java similarity index 77% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplereconcilersametype/MultipleReconcilerSameTypeStatus.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplereconcilersametype/MultipleReconcilerSameTypeStatus.java index 9335d89752..e14dd2ea6b 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplereconcilersametype/MultipleReconcilerSameTypeStatus.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplereconcilersametype/MultipleReconcilerSameTypeStatus.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multiplereconcilersametype; +package io.javaoperatorsdk.operator.baseapi.multiplereconcilersametype; public class MultipleReconcilerSameTypeStatus { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplesecondaryeventsource/MultipleSecondaryEventSourceCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplesecondaryeventsource/MultipleSecondaryEventSourceCustomResource.java similarity index 78% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplesecondaryeventsource/MultipleSecondaryEventSourceCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplesecondaryeventsource/MultipleSecondaryEventSourceCustomResource.java index 0d9f636531..d142f1f0d1 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplesecondaryeventsource/MultipleSecondaryEventSourceCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplesecondaryeventsource/MultipleSecondaryEventSourceCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multiplesecondaryeventsource; +package io.javaoperatorsdk.operator.baseapi.multiplesecondaryeventsource; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; @@ -12,6 +12,6 @@ @Kind("MultipleSecondaryEventSourceCustomResource") @ShortNames("mses") public class MultipleSecondaryEventSourceCustomResource - extends CustomResource + extends CustomResource implements Namespaced { } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleSecondaryEventSourceIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplesecondaryeventsource/MultipleSecondaryEventSourceIT.java similarity index 89% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleSecondaryEventSourceIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplesecondaryeventsource/MultipleSecondaryEventSourceIT.java index 85be323379..856f6d8a6f 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleSecondaryEventSourceIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplesecondaryeventsource/MultipleSecondaryEventSourceIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.multiplesecondaryeventsource; import java.time.Duration; @@ -8,8 +8,6 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.multiplesecondaryeventsource.MultipleSecondaryEventSourceCustomResource; -import io.javaoperatorsdk.operator.sample.multiplesecondaryeventsource.MultipleSecondaryEventSourceReconciler; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplesecondaryeventsource/MultipleSecondaryEventSourceReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplesecondaryeventsource/MultipleSecondaryEventSourceReconciler.java similarity index 74% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplesecondaryeventsource/MultipleSecondaryEventSourceReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplesecondaryeventsource/MultipleSecondaryEventSourceReconciler.java index 8f4ed834aa..77a3b245b0 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplesecondaryeventsource/MultipleSecondaryEventSourceReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiplesecondaryeventsource/MultipleSecondaryEventSourceReconciler.java @@ -1,14 +1,18 @@ -package io.javaoperatorsdk.operator.sample.multiplesecondaryeventsource; +package io.javaoperatorsdk.operator.baseapi.multiplesecondaryeventsource; import java.util.HashMap; -import java.util.Map; +import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMeta; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; -import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.javaoperatorsdk.operator.processing.event.ResourceID; import io.javaoperatorsdk.operator.processing.event.source.EventSource; import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; @@ -16,11 +20,18 @@ @ControllerConfiguration public class MultipleSecondaryEventSourceReconciler - implements Reconciler, TestExecutionInfoProvider, - EventSourceInitializer { + implements Reconciler, TestExecutionInfoProvider { private final AtomicInteger numberOfExecutions = new AtomicInteger(0); + public static String getName1(MultipleSecondaryEventSourceCustomResource resource) { + return resource.getMetadata().getName() + "1"; + } + + public static String getName2(MultipleSecondaryEventSourceCustomResource resource) { + return resource.getMetadata().getName() + "2"; + } + @Override public UpdateControl reconcile( MultipleSecondaryEventSourceCustomResource resource, @@ -49,26 +60,22 @@ public UpdateControl reconcile( return UpdateControl.noUpdate(); } - public static String getName1(MultipleSecondaryEventSourceCustomResource resource) { - return resource.getMetadata().getName() + "1"; - } - - public static String getName2(MultipleSecondaryEventSourceCustomResource resource) { - return resource.getMetadata().getName() + "2"; - } - public int getNumberOfExecutions() { return numberOfExecutions.get(); } @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { - - var config = InformerConfiguration.from(ConfigMap.class) - .withNamespaces(context.getControllerConfiguration().getNamespaces()) - .withLabelSelector("multisecondary") + var config = InformerEventSourceConfiguration + .from(ConfigMap.class, MultipleSecondaryEventSourceCustomResource.class) + .withInformerConfiguration(c -> c + // TODO: this shouldn't be needed since this should be the default behavior (tracking + // the controller's namespaces) + .withNamespaces( + context.getControllerConfiguration().getInformerConfig().getNamespaces()) + .withLabelSelector("multisecondary")) .withSecondaryToPrimaryMapper(s -> { var name = s.getMetadata().getName().subSequence(0, s.getMetadata().getName().length() - 1); @@ -76,7 +83,7 @@ public Map prepareEventSources( }).build(); InformerEventSource configMapEventSource = new InformerEventSource<>(config, context); - return EventSourceInitializer.nameEventSources(configMapEventSource); + return List.of(configMapEventSource); } ConfigMap configMap(String name, MultipleSecondaryEventSourceCustomResource resource) { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MultiVersionCRDIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDIT.java similarity index 91% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/MultiVersionCRDIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDIT.java index dbb393fec0..687ea3c581 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MultiVersionCRDIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.multiversioncrd; import java.time.Duration; import java.util.HashMap; @@ -15,12 +15,6 @@ import io.fabric8.kubernetes.client.utils.Serialization; import io.javaoperatorsdk.operator.api.config.InformerStoppedHandler; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.multiversioncrd.MultiVersionCRDTestCustomResource1; -import io.javaoperatorsdk.operator.sample.multiversioncrd.MultiVersionCRDTestCustomResource2; -import io.javaoperatorsdk.operator.sample.multiversioncrd.MultiVersionCRDTestCustomResourceSpec1; -import io.javaoperatorsdk.operator.sample.multiversioncrd.MultiVersionCRDTestCustomResourceSpec2; -import io.javaoperatorsdk.operator.sample.multiversioncrd.MultiVersionCRDTestReconciler1; -import io.javaoperatorsdk.operator.sample.multiversioncrd.MultiVersionCRDTestReconciler2; import com.fasterxml.jackson.core.JsonProcessingException; @@ -60,8 +54,7 @@ public void reset() { @Override @SuppressWarnings("rawtypes") public void onStop(SharedIndexInformer informer, Throwable ex) { - if (ex instanceof WatcherException) { - WatcherException watcherEx = (WatcherException) ex; + if (ex instanceof WatcherException watcherEx) { watcherEx.getRawWatchMessage().ifPresent(raw -> { try { // extract the resource at which the version is attempted to be created (i.e. the stored diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestCustomResource1.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestCustomResource1.java similarity index 91% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestCustomResource1.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestCustomResource1.java index e050ccfb35..cdc56026eb 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestCustomResource1.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestCustomResource1.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multiversioncrd; +package io.javaoperatorsdk.operator.baseapi.multiversioncrd; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestCustomResource2.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestCustomResource2.java similarity index 91% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestCustomResource2.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestCustomResource2.java index 5f29c88c51..ecf3f0c7e2 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestCustomResource2.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestCustomResource2.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multiversioncrd; +package io.javaoperatorsdk.operator.baseapi.multiversioncrd; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestCustomResourceSpec1.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestCustomResourceSpec1.java similarity index 80% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestCustomResourceSpec1.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestCustomResourceSpec1.java index 5c915179e2..da6b415cee 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestCustomResourceSpec1.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestCustomResourceSpec1.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multiversioncrd; +package io.javaoperatorsdk.operator.baseapi.multiversioncrd; public class MultiVersionCRDTestCustomResourceSpec1 { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestCustomResourceSpec2.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestCustomResourceSpec2.java similarity index 80% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestCustomResourceSpec2.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestCustomResourceSpec2.java index a4058dbd9f..2219acca36 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestCustomResourceSpec2.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestCustomResourceSpec2.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multiversioncrd; +package io.javaoperatorsdk.operator.baseapi.multiversioncrd; public class MultiVersionCRDTestCustomResourceSpec2 { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestCustomResourceStatus1.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestCustomResourceStatus1.java similarity index 90% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestCustomResourceStatus1.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestCustomResourceStatus1.java index 765766b1e2..17c0f00bab 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestCustomResourceStatus1.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestCustomResourceStatus1.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multiversioncrd; +package io.javaoperatorsdk.operator.baseapi.multiversioncrd; import java.util.ArrayList; import java.util.List; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestCustomResourceStatus2.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestCustomResourceStatus2.java similarity index 90% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestCustomResourceStatus2.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestCustomResourceStatus2.java index 5df57ef76d..5af2e55177 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestCustomResourceStatus2.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestCustomResourceStatus2.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multiversioncrd; +package io.javaoperatorsdk.operator.baseapi.multiversioncrd; import java.util.ArrayList; import java.util.List; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestReconciler1.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestReconciler1.java similarity index 86% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestReconciler1.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestReconciler1.java index bd564e3d07..a9b3af7586 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestReconciler1.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestReconciler1.java @@ -1,14 +1,15 @@ -package io.javaoperatorsdk.operator.sample.multiversioncrd; +package io.javaoperatorsdk.operator.baseapi.multiversioncrd; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +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(labelSelector = "!version") +@ControllerConfiguration(informer = @Informer(labelSelector = "!version")) public class MultiVersionCRDTestReconciler1 implements Reconciler { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestReconciler2.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestReconciler2.java similarity index 85% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestReconciler2.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestReconciler2.java index 28f556afc0..29d7e830fa 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiversioncrd/MultiVersionCRDTestReconciler2.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/multiversioncrd/MultiVersionCRDTestReconciler2.java @@ -1,14 +1,15 @@ -package io.javaoperatorsdk.operator.sample.multiversioncrd; +package io.javaoperatorsdk.operator.baseapi.multiversioncrd; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +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(labelSelector = "version in (v2)") +@ControllerConfiguration(informer = @Informer(labelSelector = "version in (v2)")) public class MultiVersionCRDTestReconciler2 implements Reconciler { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/indexdiscriminator/IndexDiscriminatorTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/nextreconciliationimminent/NextReconciliationImminentCustomResource.java similarity index 61% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/indexdiscriminator/IndexDiscriminatorTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/nextreconciliationimminent/NextReconciliationImminentCustomResource.java index 729b1d80eb..5a54443393 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/indexdiscriminator/IndexDiscriminatorTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/nextreconciliationimminent/NextReconciliationImminentCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.indexdiscriminator; +package io.javaoperatorsdk.operator.baseapi.nextreconciliationimminent; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; @@ -8,9 +8,11 @@ @Group("sample.javaoperatorsdk") @Version("v1") -@ShortNames("idt") -public class IndexDiscriminatorTestCustomResource - extends CustomResource +@ShortNames("nri") +public class NextReconciliationImminentCustomResource + extends CustomResource implements Namespaced { + + } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/nextreconciliationimminent/NextReconciliationImminentIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/nextreconciliationimminent/NextReconciliationImminentIT.java new file mode 100644 index 0000000000..5f7933610f --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/nextreconciliationimminent/NextReconciliationImminentIT.java @@ -0,0 +1,64 @@ +package io.javaoperatorsdk.operator.baseapi.nextreconciliationimminent; + +import java.time.Duration; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public class NextReconciliationImminentIT { + + private static final Logger log = + LoggerFactory.getLogger(NextReconciliationImminentIT.class); + + public static final int WAIT_FOR_EVENT = 300; + public static final String TEST_RESOURCE_NAME = "test1"; + + @RegisterExtension + LocallyRunOperatorExtension extension = + LocallyRunOperatorExtension.builder() + .withReconciler(new NextReconciliationImminentReconciler()) + .build(); + + @Test + void skippingStatusUpdateWithNextReconciliationImminent() throws InterruptedException { + var resource = extension.create(testResource()); + + var reconciler = extension.getReconcilerOfType(NextReconciliationImminentReconciler.class); + await().untilAsserted(() -> assertThat(reconciler.isReconciliationWaiting()).isTrue()); + Thread.sleep(WAIT_FOR_EVENT); + + resource.getMetadata().getAnnotations().put("trigger", "" + System.currentTimeMillis()); + extension.replace(resource); + Thread.sleep(WAIT_FOR_EVENT); + log.info("Made change to trigger event"); + + reconciler.allowReconciliationToProceed(); + Thread.sleep(WAIT_FOR_EVENT); + // second event arrived + await().untilAsserted(() -> assertThat(reconciler.isReconciliationWaiting()).isTrue()); + reconciler.allowReconciliationToProceed(); + + await().pollDelay(Duration.ofMillis(WAIT_FOR_EVENT)).untilAsserted(() -> { + assertThat(extension.get(NextReconciliationImminentCustomResource.class, TEST_RESOURCE_NAME) + .getStatus().getUpdateNumber()).isEqualTo(1); + }); + } + + + NextReconciliationImminentCustomResource testResource() { + var res = new NextReconciliationImminentCustomResource(); + res.setMetadata(new ObjectMetaBuilder() + .withName(TEST_RESOURCE_NAME) + .build()); + return res; + } + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/nextreconciliationimminent/NextReconciliationImminentReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/nextreconciliationimminent/NextReconciliationImminentReconciler.java new file mode 100644 index 0000000000..d3de766869 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/nextreconciliationimminent/NextReconciliationImminentReconciler.java @@ -0,0 +1,58 @@ +package io.javaoperatorsdk.operator.baseapi.nextreconciliationimminent; + +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +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(generationAwareEventProcessing = false) +public class NextReconciliationImminentReconciler + implements Reconciler { + + private static final Logger log = + LoggerFactory.getLogger(NextReconciliationImminentReconciler.class); + + private final SynchronousQueue queue = new SynchronousQueue<>(); + private volatile boolean reconciliationWaiting = false; + + @Override + public UpdateControl reconcile( + NextReconciliationImminentCustomResource resource, + Context context) throws InterruptedException { + log.info("started reconciliation"); + reconciliationWaiting = true; + // wait long enough to get manually allowed + queue.poll(120, TimeUnit.SECONDS); + log.info("Continue after wait"); + reconciliationWaiting = false; + + if (context.isNextReconciliationImminent()) { + return UpdateControl.noUpdate(); + } else { + if (resource.getStatus() == null) { + resource.setStatus(new NextReconciliationImminentStatus()); + } + resource.getStatus().setUpdateNumber(resource.getStatus().getUpdateNumber() + 1); + log.info("Patching status"); + return UpdateControl.patchStatus(resource); + } + } + + public void allowReconciliationToProceed() { + try { + queue.put(true); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + + public boolean isReconciliationWaiting() { + return reconciliationWaiting; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/nextreconciliationimminent/NextReconciliationImminentStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/nextreconciliationimminent/NextReconciliationImminentStatus.java new file mode 100644 index 0000000000..66aed10ba3 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/nextreconciliationimminent/NextReconciliationImminentStatus.java @@ -0,0 +1,14 @@ +package io.javaoperatorsdk.operator.baseapi.nextreconciliationimminent; + +public class NextReconciliationImminentStatus { + + private int updateNumber; + + public int getUpdateNumber() { + return updateNumber; + } + + public void setUpdateNumber(int updateNumber) { + this.updateNumber = updateNumber; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourceandstatusnossa/PatchResourceAndStatusNoSSACustomResource.java similarity index 66% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourceandstatusnossa/PatchResourceAndStatusNoSSACustomResource.java index 11c543e388..45f5543024 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourceandstatusnossa/PatchResourceAndStatusNoSSACustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.doubleupdate; +package io.javaoperatorsdk.operator.baseapi.patchresourceandstatusnossa; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; @@ -11,7 +11,7 @@ @Version("v1") @Kind("DoubleUpdateSample") @ShortNames("du") -public class DoubleUpdateTestCustomResource - extends CustomResource +public class PatchResourceAndStatusNoSSACustomResource + extends CustomResource implements Namespaced { } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/UpdatingResAndSubResIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourceandstatusnossa/PatchResourceAndStatusNoSSAIT.java similarity index 54% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/UpdatingResAndSubResIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourceandstatusnossa/PatchResourceAndStatusNoSSAIT.java index 3d7d27b4c3..de4ba09b23 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/UpdatingResAndSubResIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourceandstatusnossa/PatchResourceAndStatusNoSSAIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.patchresourceandstatusnossa; import java.util.concurrent.TimeUnit; @@ -7,44 +7,43 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.doubleupdate.DoubleUpdateTestCustomReconciler; -import io.javaoperatorsdk.operator.sample.doubleupdate.DoubleUpdateTestCustomResource; -import io.javaoperatorsdk.operator.sample.doubleupdate.DoubleUpdateTestCustomResourceSpec; -import io.javaoperatorsdk.operator.sample.doubleupdate.DoubleUpdateTestCustomResourceStatus; import io.javaoperatorsdk.operator.support.TestUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; -class UpdatingResAndSubResIT { +class PatchResourceAndStatusNoSSAIT { @RegisterExtension LocallyRunOperatorExtension operator = - LocallyRunOperatorExtension.builder().withReconciler(DoubleUpdateTestCustomReconciler.class) + + LocallyRunOperatorExtension.builder() + .withConfigurationService(o -> o.withUseSSAToPatchPrimaryResource(false)) + .withReconciler(PatchResourceAndStatusNoSSAReconciler.class) .build(); @Test void updatesSubResourceStatus() { - DoubleUpdateTestCustomResource resource = createTestCustomResource("1"); + PatchResourceAndStatusNoSSACustomResource resource = createTestCustomResource("1"); operator.create(resource); awaitStatusUpdated(resource.getMetadata().getName()); // wait for sure, there are no more events TestUtils.waitXms(300); - DoubleUpdateTestCustomResource customResource = + PatchResourceAndStatusNoSSACustomResource customResource = operator - .get(DoubleUpdateTestCustomResource.class, + .get(PatchResourceAndStatusNoSSACustomResource.class, resource.getMetadata().getName()); assertThat(TestUtils.getNumberOfExecutions(operator)) .isEqualTo(1); assertThat(customResource.getStatus().getState()) - .isEqualTo(DoubleUpdateTestCustomResourceStatus.State.SUCCESS); + .isEqualTo(PatchResourceAndStatusNoSSAStatus.State.SUCCESS); assertThat( customResource .getMetadata() .getAnnotations() - .get(DoubleUpdateTestCustomReconciler.TEST_ANNOTATION)) + .get(PatchResourceAndStatusNoSSAReconciler.TEST_ANNOTATION)) .isNotNull(); } @@ -53,21 +52,22 @@ void awaitStatusUpdated(String name) { .atMost(5, TimeUnit.SECONDS) .untilAsserted( () -> { - DoubleUpdateTestCustomResource cr = - operator.get(DoubleUpdateTestCustomResource.class, name); + PatchResourceAndStatusNoSSACustomResource cr = + operator.get(PatchResourceAndStatusNoSSACustomResource.class, name); assertThat(cr) .isNotNull(); assertThat(cr.getStatus()) .isNotNull(); assertThat(cr.getStatus().getState()) - .isEqualTo(DoubleUpdateTestCustomResourceStatus.State.SUCCESS); + .isEqualTo(PatchResourceAndStatusNoSSAStatus.State.SUCCESS); }); } - public DoubleUpdateTestCustomResource createTestCustomResource(String id) { - DoubleUpdateTestCustomResource resource = new DoubleUpdateTestCustomResource(); + public PatchResourceAndStatusNoSSACustomResource createTestCustomResource(String id) { + PatchResourceAndStatusNoSSACustomResource resource = + new PatchResourceAndStatusNoSSACustomResource(); resource.setMetadata(new ObjectMetaBuilder().withName("doubleupdateresource-" + id).build()); - resource.setSpec(new DoubleUpdateTestCustomResourceSpec()); + resource.setSpec(new PatchResourceAndStatusNoSSASpec()); resource.getSpec().setValue(id); return resource; } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourceandstatusnossa/PatchResourceAndStatusNoSSAReconciler.java similarity index 58% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourceandstatusnossa/PatchResourceAndStatusNoSSAReconciler.java index 11f0a54f3e..a104ca4185 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourceandstatusnossa/PatchResourceAndStatusNoSSAReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.doubleupdate; +package io.javaoperatorsdk.operator.baseapi.patchresourceandstatusnossa; import java.util.HashMap; import java.util.concurrent.atomic.AtomicInteger; @@ -13,18 +13,19 @@ import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; @ControllerConfiguration -public class DoubleUpdateTestCustomReconciler - implements Reconciler, TestExecutionInfoProvider { +public class PatchResourceAndStatusNoSSAReconciler + implements Reconciler, TestExecutionInfoProvider { private static final Logger log = - LoggerFactory.getLogger(DoubleUpdateTestCustomReconciler.class); + LoggerFactory.getLogger(PatchResourceAndStatusNoSSAReconciler.class); public static final String TEST_ANNOTATION = "TestAnnotation"; public static final String TEST_ANNOTATION_VALUE = "TestAnnotationValue"; private final AtomicInteger numberOfExecutions = new AtomicInteger(0); @Override - public UpdateControl reconcile( - DoubleUpdateTestCustomResource resource, Context context) { + public UpdateControl reconcile( + PatchResourceAndStatusNoSSACustomResource resource, + Context context) { numberOfExecutions.addAndGet(1); log.info("Value: " + resource.getSpec().getValue()); @@ -32,15 +33,15 @@ public UpdateControl reconcile( resource.getMetadata().setAnnotations(new HashMap<>()); resource.getMetadata().getAnnotations().put(TEST_ANNOTATION, TEST_ANNOTATION_VALUE); ensureStatusExists(resource); - resource.getStatus().setState(DoubleUpdateTestCustomResourceStatus.State.SUCCESS); + resource.getStatus().setState(PatchResourceAndStatusNoSSAStatus.State.SUCCESS); - return UpdateControl.updateResourceAndStatus(resource); + return UpdateControl.patchResourceAndStatus(resource); } - private void ensureStatusExists(DoubleUpdateTestCustomResource resource) { - DoubleUpdateTestCustomResourceStatus status = resource.getStatus(); + private void ensureStatusExists(PatchResourceAndStatusNoSSACustomResource resource) { + PatchResourceAndStatusNoSSAStatus status = resource.getStatus(); if (status == null) { - status = new DoubleUpdateTestCustomResourceStatus(); + status = new PatchResourceAndStatusNoSSAStatus(); resource.setStatus(status); } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourceandstatusnossa/PatchResourceAndStatusNoSSASpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourceandstatusnossa/PatchResourceAndStatusNoSSASpec.java new file mode 100644 index 0000000000..aa8aeca39c --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourceandstatusnossa/PatchResourceAndStatusNoSSASpec.java @@ -0,0 +1,15 @@ +package io.javaoperatorsdk.operator.baseapi.patchresourceandstatusnossa; + +public class PatchResourceAndStatusNoSSASpec { + + private String value; + + public String getValue() { + return value; + } + + public PatchResourceAndStatusNoSSASpec setValue(String value) { + this.value = value; + return this; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourceandstatusnossa/PatchResourceAndStatusNoSSAStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourceandstatusnossa/PatchResourceAndStatusNoSSAStatus.java new file mode 100644 index 0000000000..bad4568700 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourceandstatusnossa/PatchResourceAndStatusNoSSAStatus.java @@ -0,0 +1,19 @@ +package io.javaoperatorsdk.operator.baseapi.patchresourceandstatusnossa; + +public class PatchResourceAndStatusNoSSAStatus { + + private State state; + + public State getState() { + return state; + } + + public PatchResourceAndStatusNoSSAStatus setState(State state) { + this.state = state; + return this; + } + + public enum State { + SUCCESS, ERROR + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceAndStatusWithSSAIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceAndStatusWithSSAIT.java new file mode 100644 index 0000000000..b8746dda3f --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceAndStatusWithSSAIT.java @@ -0,0 +1,12 @@ +package io.javaoperatorsdk.operator.baseapi.patchresourcewithssa; + +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; + +public class PatchResourceAndStatusWithSSAIT extends PatchWithSSAITBase { + + @Override + protected Reconciler reconciler() { + return new PatchResourceAndStatusWithSSAReconciler(); + } + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceAndStatusWithSSAReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceAndStatusWithSSAReconciler.java new file mode 100644 index 0000000000..2d599a9039 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceAndStatusWithSSAReconciler.java @@ -0,0 +1,37 @@ +package io.javaoperatorsdk.operator.baseapi.patchresourcewithssa; + +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.api.reconciler.*; + +@ControllerConfiguration +public class PatchResourceAndStatusWithSSAReconciler + implements Reconciler, + Cleaner { + + public static final String ADDED_VALUE = "Added Value"; + + @Override + public UpdateControl reconcile( + PatchResourceWithSSACustomResource resource, + Context context) { + + var res = new PatchResourceWithSSACustomResource(); + res.setMetadata(new ObjectMetaBuilder() + .withName(resource.getMetadata().getName()) + .withNamespace(resource.getMetadata().getNamespace()) + .build()); + + res.setSpec(new PatchResourceWithSSASpec()); + res.getSpec().setControllerManagedValue(ADDED_VALUE); + res.setStatus(new PatchResourceWithSSAStatus()); + res.getStatus().setSuccessfullyReconciled(true); + + return UpdateControl.patchResourceAndStatus(res); + } + + @Override + public DeleteControl cleanup(PatchResourceWithSSACustomResource resource, + Context context) { + return DeleteControl.defaultDelete(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceWithSSACustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceWithSSACustomResource.java new file mode 100644 index 0000000000..0c789127ac --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceWithSSACustomResource.java @@ -0,0 +1,16 @@ +package io.javaoperatorsdk.operator.baseapi.patchresourcewithssa; + +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("sample.javaoperatorsdk") +@Version("v1") +@ShortNames("prs") +public class PatchResourceWithSSACustomResource + extends CustomResource + implements Namespaced { + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceWithSSAIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceWithSSAIT.java new file mode 100644 index 0000000000..6ceaea2867 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceWithSSAIT.java @@ -0,0 +1,14 @@ +package io.javaoperatorsdk.operator.baseapi.patchresourcewithssa; + + +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; + + +public class PatchResourceWithSSAIT extends PatchWithSSAITBase { + + @Override + protected Reconciler reconciler() { + return new PatchResourceWithSSAReconciler(); + } + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceWithSSAReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceWithSSAReconciler.java new file mode 100644 index 0000000000..f5f53ee6c5 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceWithSSAReconciler.java @@ -0,0 +1,41 @@ +package io.javaoperatorsdk.operator.baseapi.patchresourcewithssa; + +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.api.reconciler.*; + +@ControllerConfiguration +public class PatchResourceWithSSAReconciler + implements Reconciler, + Cleaner { + + public static final String ADDED_VALUE = "Added Value"; + + @Override + public UpdateControl reconcile( + PatchResourceWithSSACustomResource resource, + Context context) { + + var res = new PatchResourceWithSSACustomResource(); + res.setMetadata(new ObjectMetaBuilder() + .withName(resource.getMetadata().getName()) + .withNamespace(resource.getMetadata().getNamespace()) + .build()); + + // first update the spec with missing value, then status in next reconciliation + if (resource.getSpec().getControllerManagedValue() == null) { + res.setSpec(new PatchResourceWithSSASpec()); + res.getSpec().setControllerManagedValue(ADDED_VALUE); + return UpdateControl.patchResource(res); + } else { + res.setStatus(new PatchResourceWithSSAStatus()); + res.getStatus().setSuccessfullyReconciled(true); + return UpdateControl.patchStatus(res); + } + } + + @Override + public DeleteControl cleanup(PatchResourceWithSSACustomResource resource, + Context context) { + return DeleteControl.defaultDelete(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceWithSSASpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceWithSSASpec.java new file mode 100644 index 0000000000..253625af56 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceWithSSASpec.java @@ -0,0 +1,23 @@ +package io.javaoperatorsdk.operator.baseapi.patchresourcewithssa; + +public class PatchResourceWithSSASpec { + + private String initValue; + private String controllerManagedValue; + + public String getInitValue() { + return initValue; + } + + public void setInitValue(String initValue) { + this.initValue = initValue; + } + + public String getControllerManagedValue() { + return controllerManagedValue; + } + + public void setControllerManagedValue(String controllerManagedValue) { + this.controllerManagedValue = controllerManagedValue; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceWithSSAStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceWithSSAStatus.java new file mode 100644 index 0000000000..f3d5f7806c --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchResourceWithSSAStatus.java @@ -0,0 +1,14 @@ +package io.javaoperatorsdk.operator.baseapi.patchresourcewithssa; + +public class PatchResourceWithSSAStatus { + + private boolean successfullyReconciled; + + public boolean isSuccessfullyReconciled() { + return successfullyReconciled; + } + + public void setSuccessfullyReconciled(boolean successfullyReconciled) { + this.successfullyReconciled = successfullyReconciled; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchWithSSAITBase.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchWithSSAITBase.java new file mode 100644 index 0000000000..50b005fef7 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/patchresourcewithssa/PatchWithSSAITBase.java @@ -0,0 +1,56 @@ +package io.javaoperatorsdk.operator.baseapi.patchresourcewithssa; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public abstract class PatchWithSSAITBase { + + public static final String RESOURCE_NAME = "test1"; + public static final String INIT_VALUE = "init value"; + + @RegisterExtension + LocallyRunOperatorExtension extension = + LocallyRunOperatorExtension.builder() + .withReconciler(reconciler()) + .build(); + + @Test + void reconcilerPatchesResourceWithSSA() { + extension.create(testResource()); + + await().untilAsserted(() -> { + var actualResource = extension.get(PatchResourceWithSSACustomResource.class, RESOURCE_NAME); + + assertThat(actualResource.getSpec().getInitValue()).isEqualTo(INIT_VALUE); + assertThat(actualResource.getSpec().getControllerManagedValue()) + .isEqualTo(PatchResourceWithSSAReconciler.ADDED_VALUE); + // finalizer is added to the SSA patch in the background by the framework + assertThat(actualResource.getMetadata().getFinalizers()).isNotEmpty(); + assertThat(actualResource.getStatus().isSuccessfullyReconciled()).isTrue(); + // one for resource, one for subresource + assertThat(actualResource.getMetadata().getManagedFields().stream() + .filter(mf -> mf.getManager() + .equals(reconciler().getClass().getSimpleName().toLowerCase())) + .toList()).hasSize(2); + }); + } + + protected abstract Reconciler reconciler(); + + PatchResourceWithSSACustomResource testResource() { + var res = new PatchResourceWithSSACustomResource(); + res.setMetadata(new ObjectMetaBuilder() + .withName(RESOURCE_NAME) + .build()); + res.setSpec(new PatchResourceWithSSASpec()); + res.getSpec().setInitValue(INIT_VALUE); + return res; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/perresourceeventsource/PerResourceEventSourceCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/perresourceeventsource/PerResourceEventSourceCustomResource.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/perresourceeventsource/PerResourceEventSourceCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/perresourceeventsource/PerResourceEventSourceCustomResource.java index 381e324aae..74817da86d 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/perresourceeventsource/PerResourceEventSourceCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/perresourceeventsource/PerResourceEventSourceCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.perresourceeventsource; +package io.javaoperatorsdk.operator.baseapi.perresourceeventsource; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/PerResourcePollingEventSourceIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/perresourceeventsource/PerResourcePollingEventSourceIT.java similarity index 79% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/PerResourcePollingEventSourceIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/perresourceeventsource/PerResourcePollingEventSourceIT.java index a4b850b9d4..299109bdd1 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/PerResourcePollingEventSourceIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/perresourceeventsource/PerResourcePollingEventSourceIT.java @@ -1,12 +1,10 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.perresourceeventsource; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.perresourceeventsource.PerResourceEventSourceCustomResource; -import io.javaoperatorsdk.operator.sample.perresourceeventsource.PerResourcePollingEventSourceTestReconciler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; @@ -28,8 +26,8 @@ class PerResourcePollingEventSourceIT { **/ @Test void fetchedAndReconciledMultipleTimes() { - operator.create(PerResourceEventSourceCustomResource.class, resource(NAME_1)); - operator.create(PerResourceEventSourceCustomResource.class, resource(NAME_2)); + operator.create(resource(NAME_1)); + operator.create(resource(NAME_2)); var reconciler = operator.getReconcilerOfType(PerResourcePollingEventSourceTestReconciler.class); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/perresourceeventsource/PerResourcePollingEventSourceTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/perresourceeventsource/PerResourcePollingEventSourceTestReconciler.java similarity index 53% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/perresourceeventsource/PerResourcePollingEventSourceTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/perresourceeventsource/PerResourcePollingEventSourceTestReconciler.java index 81d8773986..8d1cbcc37f 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/perresourceeventsource/PerResourcePollingEventSourceTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/perresourceeventsource/PerResourcePollingEventSourceTestReconciler.java @@ -1,19 +1,24 @@ -package io.javaoperatorsdk.operator.sample.perresourceeventsource; +package io.javaoperatorsdk.operator.baseapi.perresourceeventsource; import java.time.Duration; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; -import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.javaoperatorsdk.operator.processing.event.source.EventSource; +import io.javaoperatorsdk.operator.processing.event.source.polling.PerResourcePollingConfigurationBuilder; import io.javaoperatorsdk.operator.processing.event.source.polling.PerResourcePollingEventSource; @ControllerConfiguration public class PerResourcePollingEventSourceTestReconciler - implements Reconciler, - EventSourceInitializer { + implements Reconciler { public static final int POLL_PERIOD = 100; private final Map numberOfExecutions = new ConcurrentHashMap<>(); @@ -29,16 +34,18 @@ public UpdateControl reconcile( } @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { PerResourcePollingEventSource eventSource = - new PerResourcePollingEventSource<>(resource -> { - numberOfFetchExecutions.putIfAbsent(resource.getMetadata().getName(), 0); - numberOfFetchExecutions.compute(resource.getMetadata().getName(), (s, v) -> v + 1); - return Set.of(UUID.randomUUID().toString()); - }, - context, Duration.ofMillis(POLL_PERIOD), String.class); - return EventSourceInitializer.nameEventSources(eventSource); + new PerResourcePollingEventSource<>(String.class, context, + new PerResourcePollingConfigurationBuilder<>( + (PerResourceEventSourceCustomResource resource) -> { + numberOfFetchExecutions.putIfAbsent(resource.getMetadata().getName(), 0); + numberOfFetchExecutions.compute(resource.getMetadata().getName(), + (s, v) -> v + 1); + return Set.of(UUID.randomUUID().toString()); + }, Duration.ofMillis(POLL_PERIOD)).build()); + return List.of(eventSource); } public int getNumberOfExecutions(String name) { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primaryindexer/AbstractPrimaryIndexerTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primaryindexer/AbstractPrimaryIndexerTestReconciler.java similarity index 91% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primaryindexer/AbstractPrimaryIndexerTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primaryindexer/AbstractPrimaryIndexerTestReconciler.java index 3b8fc43bfb..ac2e7e1534 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primaryindexer/AbstractPrimaryIndexerTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primaryindexer/AbstractPrimaryIndexerTestReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.primaryindexer; +package io.javaoperatorsdk.operator.baseapi.primaryindexer; import java.util.List; import java.util.Map; @@ -15,6 +15,8 @@ public class AbstractPrimaryIndexerTestReconciler implements Reconciler { + public static final String CONFIG_MAP_NAME = "common-config-map"; + private final Map numberOfExecutions = new ConcurrentHashMap<>(); protected static final String CONFIG_MAP_RELATION_INDEXER = "cm-indexer"; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/PrimaryIndexerIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primaryindexer/PrimaryIndexerIT.java similarity index 82% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/PrimaryIndexerIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primaryindexer/PrimaryIndexerIT.java index 16f223ce38..cb810dcd35 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/PrimaryIndexerIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primaryindexer/PrimaryIndexerIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.primaryindexer; import java.time.Duration; @@ -8,17 +8,13 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.primaryindexer.AbstractPrimaryIndexerTestReconciler; -import io.javaoperatorsdk.operator.sample.primaryindexer.PrimaryIndexerTestCustomResource; -import io.javaoperatorsdk.operator.sample.primaryindexer.PrimaryIndexerTestCustomResourceSpec; -import io.javaoperatorsdk.operator.sample.primaryindexer.PrimaryIndexerTestReconciler; +import static io.javaoperatorsdk.operator.baseapi.primaryindexer.AbstractPrimaryIndexerTestReconciler.CONFIG_MAP_NAME; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; -class PrimaryIndexerIT { +public class PrimaryIndexerIT { - public static final String CONFIG_MAP_NAME = "common-config-map"; public static final String RESOURCE_NAME1 = "test1"; public static final String RESOURCE_NAME2 = "test2"; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primaryindexer/PrimaryIndexerTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primaryindexer/PrimaryIndexerTestCustomResource.java similarity index 91% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primaryindexer/PrimaryIndexerTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primaryindexer/PrimaryIndexerTestCustomResource.java index 65a6fb3c43..f670a4be64 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primaryindexer/PrimaryIndexerTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primaryindexer/PrimaryIndexerTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.primaryindexer; +package io.javaoperatorsdk.operator.baseapi.primaryindexer; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primaryindexer/PrimaryIndexerTestCustomResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primaryindexer/PrimaryIndexerTestCustomResourceSpec.java similarity index 83% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primaryindexer/PrimaryIndexerTestCustomResourceSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primaryindexer/PrimaryIndexerTestCustomResourceSpec.java index 4e1430701c..65cbf68d80 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primaryindexer/PrimaryIndexerTestCustomResourceSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primaryindexer/PrimaryIndexerTestCustomResourceSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.primaryindexer; +package io.javaoperatorsdk.operator.baseapi.primaryindexer; public class PrimaryIndexerTestCustomResourceSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primaryindexer/PrimaryIndexerTestCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primaryindexer/PrimaryIndexerTestCustomResourceStatus.java similarity index 50% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primaryindexer/PrimaryIndexerTestCustomResourceStatus.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primaryindexer/PrimaryIndexerTestCustomResourceStatus.java index c52b3bce1e..ebcfe347e5 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primaryindexer/PrimaryIndexerTestCustomResourceStatus.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primaryindexer/PrimaryIndexerTestCustomResourceStatus.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.primaryindexer; +package io.javaoperatorsdk.operator.baseapi.primaryindexer; public class PrimaryIndexerTestCustomResourceStatus { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primaryindexer/PrimaryIndexerTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primaryindexer/PrimaryIndexerTestReconciler.java similarity index 66% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primaryindexer/PrimaryIndexerTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primaryindexer/PrimaryIndexerTestReconciler.java index 6890a3c8c4..d03cc0fcb0 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primaryindexer/PrimaryIndexerTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primaryindexer/PrimaryIndexerTestReconciler.java @@ -1,30 +1,29 @@ -package io.javaoperatorsdk.operator.sample.primaryindexer; +package io.javaoperatorsdk.operator.baseapi.primaryindexer; -import java.util.Map; +import java.util.List; import java.util.stream.Collectors; import io.fabric8.kubernetes.api.model.ConfigMap; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; -import io.javaoperatorsdk.operator.api.reconciler.EventSourceInitializer; import io.javaoperatorsdk.operator.processing.event.ResourceID; import io.javaoperatorsdk.operator.processing.event.source.EventSource; import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; @ControllerConfiguration public class PrimaryIndexerTestReconciler - extends AbstractPrimaryIndexerTestReconciler implements - EventSourceInitializer { + extends AbstractPrimaryIndexerTestReconciler { @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { context.getPrimaryCache().addIndexer(CONFIG_MAP_RELATION_INDEXER, indexer); var informerConfiguration = - InformerConfiguration.from(ConfigMap.class) + InformerEventSourceConfiguration + .from(ConfigMap.class, PrimaryIndexerTestCustomResource.class) .withSecondaryToPrimaryMapper( (ConfigMap secondaryResource) -> context .getPrimaryCache() @@ -36,7 +35,6 @@ public Map prepareEventSources( .collect(Collectors.toSet())) .build(); - return EventSourceInitializer - .nameEventSources(new InformerEventSource<>(informerConfiguration, context)); + return List.of(new InformerEventSource<>(informerConfiguration, context)); } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondary/Cluster.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primarytosecondary/Cluster.java similarity index 77% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondary/Cluster.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primarytosecondary/Cluster.java index ffc43141a4..18190ae1fa 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondary/Cluster.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primarytosecondary/Cluster.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.primarytosecondary; +package io.javaoperatorsdk.operator.baseapi.primarytosecondary; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; @@ -10,6 +10,6 @@ @Version("v1") @ShortNames("clu") public class Cluster - extends CustomResource + extends CustomResource implements Namespaced { } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondary/Job.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primarytosecondary/Job.java similarity index 77% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondary/Job.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primarytosecondary/Job.java index 5a3d43de79..3215fd8538 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondary/Job.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primarytosecondary/Job.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.primarytosecondary; +package io.javaoperatorsdk.operator.baseapi.primarytosecondary; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; @@ -10,6 +10,6 @@ @Version("v1") @ShortNames("cjo") public class Job - extends CustomResource + extends CustomResource implements Namespaced { } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondary/JobReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primarytosecondary/JobReconciler.java similarity index 83% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondary/JobReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primarytosecondary/JobReconciler.java index ace158360a..b0f369817e 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondary/JobReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primarytosecondary/JobReconciler.java @@ -1,12 +1,12 @@ -package io.javaoperatorsdk.operator.sample.primarytosecondary; +package io.javaoperatorsdk.operator.baseapi.primarytosecondary; import java.util.List; -import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; import io.javaoperatorsdk.operator.api.reconciler.*; import io.javaoperatorsdk.operator.processing.event.ResourceID; import io.javaoperatorsdk.operator.processing.event.source.EventSource; @@ -20,7 +20,7 @@ */ @ControllerConfiguration() public class JobReconciler - implements Reconciler, EventSourceInitializer, ErrorStatusHandler { + implements Reconciler { private static final String JOB_CLUSTER_INDEX = "job-cluster-index"; @@ -49,7 +49,7 @@ public UpdateControl reconcile( } else { // reading the resource from cache as alternative, works without primary to secondary mapper var informerEventSource = (InformerEventSource) context.eventSourceRetriever() - .getResourceEventSourceFor(Cluster.class); + .getEventSourceFor(Cluster.class); informerEventSource .get(new ResourceID(resource.getSpec().getClusterName(), resource.getMetadata().getNamespace())) @@ -61,17 +61,18 @@ public UpdateControl reconcile( } @Override - public Map prepareEventSources(EventSourceContext context) { + public List> prepareEventSources(EventSourceContext context) { context.getPrimaryCache().addIndexer(JOB_CLUSTER_INDEX, (job -> List .of(indexKey(job.getSpec().getClusterName(), job.getMetadata().getNamespace())))); - InformerConfiguration.InformerConfigurationBuilder informerConfiguration = - InformerConfiguration.from(Cluster.class, context) + InformerEventSourceConfiguration.Builder informerConfiguration = + InformerEventSourceConfiguration.from(Cluster.class, Job.class) .withSecondaryToPrimaryMapper(cluster -> context.getPrimaryCache() .byIndex(JOB_CLUSTER_INDEX, indexKey(cluster.getMetadata().getName(), cluster.getMetadata().getNamespace())) .stream().map(ResourceID::fromResource).collect(Collectors.toSet())) - .withNamespacesInheritedFromController(context); + .withInformerConfiguration( + InformerConfiguration.Builder::withNamespacesInheritedFromController); if (addPrimaryToSecondaryMapper) { informerConfiguration = informerConfiguration.withPrimaryToSecondaryMapper( @@ -79,8 +80,7 @@ public Map prepareEventSources(EventSourceContext cont primary.getSpec().getClusterName(), primary.getMetadata().getNamespace()))); } - return EventSourceInitializer - .nameEventSources(new InformerEventSource<>(informerConfiguration.build(), context)); + return List.of(new InformerEventSource<>(informerConfiguration.build(), context)); } private String indexKey(String clusterName, String namespace) { @@ -102,6 +102,7 @@ public boolean isErrorOccurred() { return errorOccurred; } + @SuppressWarnings("UnusedReturnValue") public JobReconciler setGetResourceDirectlyFromCache(boolean getResourceDirectlyFromCache) { this.getResourceDirectlyFromCache = getResourceDirectlyFromCache; return this; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondary/JobSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primarytosecondary/JobSpec.java similarity index 78% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondary/JobSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primarytosecondary/JobSpec.java index c7546dea71..c450129627 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondary/JobSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primarytosecondary/JobSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.primarytosecondary; +package io.javaoperatorsdk.operator.baseapi.primarytosecondary; public class JobSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/PrimaryToSecondaryIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primarytosecondary/PrimaryToSecondaryIT.java similarity index 82% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/PrimaryToSecondaryIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primarytosecondary/PrimaryToSecondaryIT.java index 720683a8cc..cfcb2854bb 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/PrimaryToSecondaryIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primarytosecondary/PrimaryToSecondaryIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.primarytosecondary; import java.time.Duration; @@ -7,10 +7,6 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.primarytosecondary.Cluster; -import io.javaoperatorsdk.operator.sample.primarytosecondary.Job; -import io.javaoperatorsdk.operator.sample.primarytosecondary.JobReconciler; -import io.javaoperatorsdk.operator.sample.primarytosecondary.JobSpec; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/PrimaryToSecondaryMissingIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primarytosecondary/PrimaryToSecondaryMissingIT.java similarity index 83% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/PrimaryToSecondaryMissingIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primarytosecondary/PrimaryToSecondaryMissingIT.java index 3105ab04ff..4e1908f282 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/PrimaryToSecondaryMissingIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/primarytosecondary/PrimaryToSecondaryMissingIT.java @@ -1,14 +1,12 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.primarytosecondary; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.primarytosecondary.Cluster; -import io.javaoperatorsdk.operator.sample.primarytosecondary.JobReconciler; -import static io.javaoperatorsdk.operator.PrimaryToSecondaryIT.cluster; -import static io.javaoperatorsdk.operator.PrimaryToSecondaryIT.job; +import static io.javaoperatorsdk.operator.baseapi.primarytosecondary.PrimaryToSecondaryIT.cluster; +import static io.javaoperatorsdk.operator.baseapi.primarytosecondary.PrimaryToSecondaryIT.job; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ratelimit/RateLimitCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/ratelimit/RateLimitCustomResource.java similarity index 74% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ratelimit/RateLimitCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/ratelimit/RateLimitCustomResource.java index 60456e6a4d..79732a199b 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ratelimit/RateLimitCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/ratelimit/RateLimitCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.ratelimit; +package io.javaoperatorsdk.operator.baseapi.ratelimit; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; @@ -10,7 +10,7 @@ @Version("v1") @ShortNames("rlc") public class RateLimitCustomResource - extends CustomResource + extends CustomResource implements Namespaced { } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ratelimit/RateLimitCustomResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/ratelimit/RateLimitCustomResourceSpec.java similarity index 80% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ratelimit/RateLimitCustomResourceSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/ratelimit/RateLimitCustomResourceSpec.java index 7dbee7f75a..ef9f747c20 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ratelimit/RateLimitCustomResourceSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/ratelimit/RateLimitCustomResourceSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.ratelimit; +package io.javaoperatorsdk.operator.baseapi.ratelimit; public class RateLimitCustomResourceSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/ratelimit/RateLimitCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/ratelimit/RateLimitCustomResourceStatus.java new file mode 100644 index 0000000000..a33142805b --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/ratelimit/RateLimitCustomResourceStatus.java @@ -0,0 +1,5 @@ +package io.javaoperatorsdk.operator.baseapi.ratelimit; + +public class RateLimitCustomResourceStatus { + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/RateLimitIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/ratelimit/RateLimitIT.java similarity index 83% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/RateLimitIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/ratelimit/RateLimitIT.java index f1d5bed6f1..1f09b75b59 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/RateLimitIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/ratelimit/RateLimitIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.ratelimit; import java.time.Duration; import java.util.stream.IntStream; @@ -10,11 +10,8 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.ratelimit.RateLimitCustomResource; -import io.javaoperatorsdk.operator.sample.ratelimit.RateLimitCustomResourceSpec; -import io.javaoperatorsdk.operator.sample.ratelimit.RateLimitReconciler; -import static io.javaoperatorsdk.operator.sample.ratelimit.RateLimitReconciler.REFRESH_PERIOD; +import static io.javaoperatorsdk.operator.baseapi.ratelimit.RateLimitReconciler.REFRESH_PERIOD; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ratelimit/RateLimitReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/ratelimit/RateLimitReconciler.java similarity index 95% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ratelimit/RateLimitReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/ratelimit/RateLimitReconciler.java index 19a63952ef..75a70f94d1 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ratelimit/RateLimitReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/ratelimit/RateLimitReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.ratelimit; +package io.javaoperatorsdk.operator.baseapi.ratelimit; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/RetryIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/retry/RetryIT.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/RetryIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/retry/RetryIT.java index a54e24dc70..e1610dc000 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/RetryIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/retry/RetryIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.retry; import java.util.concurrent.TimeUnit; @@ -8,10 +8,6 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; import io.javaoperatorsdk.operator.processing.retry.GenericRetry; -import io.javaoperatorsdk.operator.sample.retry.RetryTestCustomReconciler; -import io.javaoperatorsdk.operator.sample.retry.RetryTestCustomResource; -import io.javaoperatorsdk.operator.sample.retry.RetryTestCustomResourceSpec; -import io.javaoperatorsdk.operator.sample.retry.RetryTestCustomResourceStatus; import io.javaoperatorsdk.operator.support.TestUtils; import static org.assertj.core.api.Assertions.assertThat; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/RetryMaxAttemptIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/retry/RetryMaxAttemptIT.java similarity index 81% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/RetryMaxAttemptIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/retry/RetryMaxAttemptIT.java index d09b14c4a9..bedfd5cff5 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/RetryMaxAttemptIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/retry/RetryMaxAttemptIT.java @@ -1,14 +1,12 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.retry; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; import io.javaoperatorsdk.operator.processing.retry.GenericRetry; -import io.javaoperatorsdk.operator.sample.retry.RetryTestCustomReconciler; -import io.javaoperatorsdk.operator.sample.retry.RetryTestCustomResource; -import static io.javaoperatorsdk.operator.RetryIT.createTestCustomResource; +import static io.javaoperatorsdk.operator.baseapi.retry.RetryIT.createTestCustomResource; import static org.assertj.core.api.Assertions.assertThat; class RetryMaxAttemptIT { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/retry/RetryTestCustomReconciler.java similarity index 97% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/retry/RetryTestCustomReconciler.java index 29d658fc7b..b9fee4769a 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/retry/RetryTestCustomReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.retry; +package io.javaoperatorsdk.operator.baseapi.retry; import java.util.concurrent.atomic.AtomicInteger; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/retry/RetryTestCustomResource.java similarity index 91% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/retry/RetryTestCustomResource.java index 093bdbc6d8..0b3e1244b6 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/retry/RetryTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.retry; +package io.javaoperatorsdk.operator.baseapi.retry; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/retry/RetryTestCustomResourceSpec.java similarity index 81% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomResourceSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/retry/RetryTestCustomResourceSpec.java index ec34d11df8..169233e7d4 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomResourceSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/retry/RetryTestCustomResourceSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.retry; +package io.javaoperatorsdk.operator.baseapi.retry; public class RetryTestCustomResourceSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/retry/RetryTestCustomResourceStatus.java similarity index 84% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomResourceStatus.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/retry/RetryTestCustomResourceStatus.java index d83b611f65..b2d8f3ba56 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomResourceStatus.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/retry/RetryTestCustomResourceStatus.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.retry; +package io.javaoperatorsdk.operator.baseapi.retry; public class RetryTestCustomResourceStatus { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ReconcilerExecutorIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/simple/ReconcilerExecutorIT.java similarity index 92% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/ReconcilerExecutorIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/simple/ReconcilerExecutorIT.java index 07a022adb1..727930d8e6 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ReconcilerExecutorIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/simple/ReconcilerExecutorIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.simple; import java.time.Duration; import java.util.concurrent.TimeUnit; @@ -8,8 +8,6 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; -import io.javaoperatorsdk.operator.sample.simple.TestReconciler; import io.javaoperatorsdk.operator.support.TestUtils; import static org.assertj.core.api.Assertions.assertThat; @@ -35,7 +33,6 @@ void configMapGetsCreatedForTestCustomResource() { @Test void patchesStatusForTestCustomResource() { - operator.getReconcilerOfType(TestReconciler.class).setPatchStatus(true); operator.getReconcilerOfType(TestReconciler.class).setUpdateStatus(true); TestCustomResource resource = TestUtils.testCustomResource(); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/simple/TestCustomResource.java similarity index 91% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/simple/TestCustomResource.java index c72b0533d9..5728746573 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/simple/TestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.simple; +package io.javaoperatorsdk.operator.baseapi.simple; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/simple/TestCustomResourceSpec.java similarity index 93% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/simple/TestCustomResourceSpec.java index 5fd9f49084..eda3c477b2 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/simple/TestCustomResourceSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.simple; +package io.javaoperatorsdk.operator.baseapi.simple; public class TestCustomResourceSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/simple/TestCustomResourceStatus.java similarity index 88% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceStatus.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/simple/TestCustomResourceStatus.java index 620bbaabd8..75fadc8e5e 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceStatus.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/simple/TestCustomResourceStatus.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.simple; +package io.javaoperatorsdk.operator.baseapi.simple; public class TestCustomResourceStatus { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/simple/TestReconciler.java similarity index 88% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/simple/TestReconciler.java index fea06bba93..50cfd334bf 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/simple/TestReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.simple; +package io.javaoperatorsdk.operator.baseapi.simple; import java.util.HashMap; import java.util.Map; @@ -27,20 +27,10 @@ public class TestReconciler private final AtomicInteger numberOfExecutions = new AtomicInteger(0); private final AtomicInteger numberOfCleanupExecutions = new AtomicInteger(0); private volatile boolean updateStatus; - private volatile boolean patchStatus; - public TestReconciler(boolean updateStatus) { - this(updateStatus, false); - } - public TestReconciler(boolean updateStatus, boolean patchStatus) { + public TestReconciler(boolean updateStatus) { this.updateStatus = updateStatus; - this.patchStatus = patchStatus; - } - - public TestReconciler setPatchStatus(boolean patchStatus) { - this.patchStatus = patchStatus; - return this; } public void setUpdateStatus(boolean updateStatus) { @@ -114,16 +104,16 @@ public UpdateControl reconcile( .createOrReplace(); } if (updateStatus) { - if (resource.getStatus() == null) { - resource.setStatus(new TestCustomResourceStatus()); - } + var statusUpdateResource = new TestCustomResource(); + statusUpdateResource.setMetadata(new ObjectMetaBuilder() + .withName(resource.getMetadata().getName()) + .withNamespace(resource.getMetadata().getNamespace()) + .build()); + resource.setStatus(new TestCustomResourceStatus()); resource.getStatus().setConfigMapStatus("ConfigMap Ready"); - } - if (patchStatus) { return UpdateControl.patchStatus(resource); - } else { - return UpdateControl.updateStatus(resource); } + return UpdateControl.noUpdate(); } private Map configMapData(TestCustomResource resource) { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statuspatchnonlocking/StatusPatchLockingCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchnonlocking/StatusPatchLockingCustomResource.java similarity index 73% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statuspatchnonlocking/StatusPatchLockingCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchnonlocking/StatusPatchLockingCustomResource.java index 4d77259999..61d4c7f1ac 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statuspatchnonlocking/StatusPatchLockingCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchnonlocking/StatusPatchLockingCustomResource.java @@ -1,16 +1,14 @@ -package io.javaoperatorsdk.operator.sample.statuspatchnonlocking; +package io.javaoperatorsdk.operator.baseapi.statuspatchnonlocking; 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.Kind; import io.fabric8.kubernetes.model.annotation.ShortNames; import io.fabric8.kubernetes.model.annotation.Version; @Group("sample.javaoperatorsdk") @Version("v1") -@Kind("StatusUpdateLockingCustomResource") -@ShortNames("sul") +@ShortNames("spl") public class StatusPatchLockingCustomResource extends CustomResource diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statuspatchnonlocking/StatusPatchLockingCustomResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchnonlocking/StatusPatchLockingCustomResourceSpec.java similarity index 83% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statuspatchnonlocking/StatusPatchLockingCustomResourceSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchnonlocking/StatusPatchLockingCustomResourceSpec.java index 3f0a59843e..298896a8b5 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statuspatchnonlocking/StatusPatchLockingCustomResourceSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchnonlocking/StatusPatchLockingCustomResourceSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.statuspatchnonlocking; +package io.javaoperatorsdk.operator.baseapi.statuspatchnonlocking; public class StatusPatchLockingCustomResourceSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statuspatchnonlocking/StatusPatchLockingCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchnonlocking/StatusPatchLockingCustomResourceStatus.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statuspatchnonlocking/StatusPatchLockingCustomResourceStatus.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchnonlocking/StatusPatchLockingCustomResourceStatus.java index 1ab7abb4d0..b4629b8207 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statuspatchnonlocking/StatusPatchLockingCustomResourceStatus.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchnonlocking/StatusPatchLockingCustomResourceStatus.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.statuspatchnonlocking; +package io.javaoperatorsdk.operator.baseapi.statuspatchnonlocking; public class StatusPatchLockingCustomResourceStatus { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statuspatchnonlocking/StatusPatchLockingReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchnonlocking/StatusPatchLockingReconciler.java similarity index 95% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statuspatchnonlocking/StatusPatchLockingReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchnonlocking/StatusPatchLockingReconciler.java index 21f83fc53f..9cafaa26ec 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statuspatchnonlocking/StatusPatchLockingReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchnonlocking/StatusPatchLockingReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.statuspatchnonlocking; +package io.javaoperatorsdk.operator.baseapi.statuspatchnonlocking; import java.util.concurrent.atomic.AtomicInteger; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/StatusPatchNotLockingIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchnonlocking/StatusPatchNotLockingIT.java similarity index 80% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/StatusPatchNotLockingIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchnonlocking/StatusPatchNotLockingIT.java index 1746e5737d..24ce2d1047 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/StatusPatchNotLockingIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchnonlocking/StatusPatchNotLockingIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.statuspatchnonlocking; import java.time.Duration; import java.util.Map; @@ -8,12 +8,9 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.statuspatchnonlocking.StatusPatchLockingCustomResource; -import io.javaoperatorsdk.operator.sample.statuspatchnonlocking.StatusPatchLockingCustomResourceSpec; -import io.javaoperatorsdk.operator.sample.statuspatchnonlocking.StatusPatchLockingReconciler; -import static io.javaoperatorsdk.operator.sample.statuspatchnonlocking.StatusPatchLockingReconciler.MESSAGE; -import static io.javaoperatorsdk.operator.sample.statusupdatelocking.StatusUpdateLockingReconciler.WAIT_TIME; +import static io.javaoperatorsdk.operator.baseapi.statuspatchnonlocking.StatusPatchLockingReconciler.MESSAGE; +import static io.javaoperatorsdk.operator.baseapi.statusupdatelocking.StatusUpdateLockingReconciler.WAIT_TIME; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; @@ -58,10 +55,12 @@ void valuesAreDeletedIfSetToNull() { assertThat(actual.getStatus().getMessage()).isEqualTo(MESSAGE); }); + // resource needs to be read again to we don't replace the with wrong managed fields + resource = operator.get(StatusPatchLockingCustomResource.class, TEST_RESOURCE_NAME); resource.getSpec().setMessageInStatus(false); operator.replace(resource); - await().untilAsserted(() -> { + await().timeout(Duration.ofMinutes(3)).untilAsserted(() -> { var actual = operator.get(StatusPatchLockingCustomResource.class, TEST_RESOURCE_NAME); assertThat(actual.getStatus()).isNotNull(); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchnonlocking/StatusPatchSSAMigrationIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchnonlocking/StatusPatchSSAMigrationIT.java new file mode 100644 index 0000000000..0a5c947c21 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statuspatchnonlocking/StatusPatchSSAMigrationIT.java @@ -0,0 +1,153 @@ +package io.javaoperatorsdk.operator.baseapi.statuspatchnonlocking; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; + +import io.fabric8.kubernetes.api.model.Namespace; +import io.fabric8.kubernetes.api.model.NamespaceBuilder; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClientBuilder; +import io.fabric8.kubernetes.client.utils.KubernetesResourceUtil; +import io.javaoperatorsdk.operator.Operator; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public class StatusPatchSSAMigrationIT { + + public static final String TEST_RESOURCE_NAME = "test"; + + private final KubernetesClient client = new KubernetesClientBuilder().build(); + private String testNamespace; + + @BeforeEach + void beforeEach(TestInfo testInfo) { + LocallyRunOperatorExtension.applyCrd(StatusPatchLockingCustomResource.class, + client); + testInfo.getTestMethod() + .ifPresent(method -> testNamespace = KubernetesResourceUtil.sanitizeName(method.getName())); + client.namespaces().resource(testNamespace(testNamespace)).create(); + } + + @AfterEach + void afterEach() { + client.namespaces().withName(testNamespace).delete(); + await().untilAsserted(() -> { + var ns = client.namespaces().withName(testNamespace).get(); + assertThat(ns).isNull(); + }); + client.close(); + } + + + @Test + void testMigratingToSSA() { + var operator = startOperator(false); + var testResource = client.resource(testResource()).create(); + + await().untilAsserted(() -> { + var res = client.resource(testResource).get(); + assertThat(res.getStatus()).isNotNull(); + assertThat(res.getStatus().getMessage()).isEqualTo(StatusPatchLockingReconciler.MESSAGE); + assertThat(res.getStatus().getValue()).isEqualTo(1); + }); + operator.stop(); + + // start operator with SSA + operator = startOperator(true); + await().untilAsserted(() -> { + var res = client.resource(testResource).get(); + assertThat(res.getStatus()).isNotNull(); + assertThat(res.getStatus().getMessage()).isEqualTo(StatusPatchLockingReconciler.MESSAGE); + assertThat(res.getStatus().getValue()).isEqualTo(2); + }); + + var actualResource = client.resource(testResource()).get(); + actualResource.getSpec().setMessageInStatus(false); + client.resource(actualResource).update(); + + await().untilAsserted(() -> { + var res = client.resource(testResource).get(); + assertThat(res.getStatus()).isNotNull(); + // !!! This is wrong, the message should be null, + // see issue in Kubernetes: https://github.com/kubernetes/kubernetes/issues/99003 + assertThat(res.getStatus().getMessage()).isNotNull(); + assertThat(res.getStatus().getValue()).isEqualTo(3); + }); + + client.resource(testResource()).delete(); + operator.stop(); + } + + @Test + void workaroundMigratingFromToSSA() { + var operator = startOperator(false); + var testResource = client.resource(testResource()).create(); + + await().untilAsserted(() -> { + var res = client.resource(testResource).get(); + assertThat(res.getStatus()).isNotNull(); + assertThat(res.getStatus().getMessage()).isEqualTo(StatusPatchLockingReconciler.MESSAGE); + assertThat(res.getStatus().getValue()).isEqualTo(1); + }); + operator.stop(); + + // start operator with SSA + operator = startOperator(true); + await().untilAsserted(() -> { + var res = client.resource(testResource).get(); + assertThat(res.getStatus()).isNotNull(); + assertThat(res.getStatus().getMessage()).isEqualTo(StatusPatchLockingReconciler.MESSAGE); + assertThat(res.getStatus().getValue()).isEqualTo(2); + }); + + var actualResource = client.resource(testResource()).get(); + actualResource.getSpec().setMessageInStatus(false); + // removing the managed field entry for former method works + actualResource.getMetadata().setManagedFields(actualResource.getMetadata().getManagedFields() + .stream().filter(r -> !r.getOperation().equals("Update") && r.getSubresource() != null) + .toList()); + client.resource(actualResource).update(); + + await().untilAsserted(() -> { + var res = client.resource(testResource).get(); + assertThat(res.getStatus()).isNotNull(); + assertThat(res.getStatus().getMessage()).isNull(); + assertThat(res.getStatus().getValue()).isEqualTo(3); + }); + + client.resource(testResource()).delete(); + operator.stop(); + } + + + private Operator startOperator(boolean patchStatusWithSSA) { + var operator = new Operator(o -> o.withCloseClientOnStop(false) + .withUseSSAToPatchPrimaryResource(patchStatusWithSSA)); + operator.register(new StatusPatchLockingReconciler(), + o -> o.settingNamespaces(testNamespace)); + + operator.start(); + return operator; + } + + StatusPatchLockingCustomResource testResource() { + StatusPatchLockingCustomResource res = new StatusPatchLockingCustomResource(); + res.setSpec(new StatusPatchLockingCustomResourceSpec()); + res.setMetadata(new ObjectMetaBuilder() + .withName(TEST_RESOURCE_NAME) + .withNamespace(testNamespace) + .build()); + return res; + } + + private Namespace testNamespace(String name) { + return new NamespaceBuilder().withMetadata(new ObjectMetaBuilder() + .withName(name) + .build()).build(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statusupdatelocking/StatusUpdateLockingCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statusupdatelocking/StatusUpdateLockingCustomResource.java similarity index 74% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statusupdatelocking/StatusUpdateLockingCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statusupdatelocking/StatusUpdateLockingCustomResource.java index df832aaed0..fb638ef5a0 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statusupdatelocking/StatusUpdateLockingCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statusupdatelocking/StatusUpdateLockingCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.statusupdatelocking; +package io.javaoperatorsdk.operator.baseapi.statusupdatelocking; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; @@ -15,8 +15,4 @@ public class StatusUpdateLockingCustomResource extends CustomResource implements Namespaced { - @Override - protected StatusUpdateLockingCustomResourceStatus initStatus() { - return new StatusUpdateLockingCustomResourceStatus(); - } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statusupdatelocking/StatusUpdateLockingCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statusupdatelocking/StatusUpdateLockingCustomResourceStatus.java similarity index 80% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statusupdatelocking/StatusUpdateLockingCustomResourceStatus.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statusupdatelocking/StatusUpdateLockingCustomResourceStatus.java index 859624d70e..81d6c8f123 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statusupdatelocking/StatusUpdateLockingCustomResourceStatus.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statusupdatelocking/StatusUpdateLockingCustomResourceStatus.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.statusupdatelocking; +package io.javaoperatorsdk.operator.baseapi.statusupdatelocking; public class StatusUpdateLockingCustomResourceStatus { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/StatusUpdateLockingIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statusupdatelocking/StatusUpdateLockingIT.java similarity index 52% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/StatusUpdateLockingIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statusupdatelocking/StatusUpdateLockingIT.java index 147c0403c3..881b0b01fc 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/StatusUpdateLockingIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statusupdatelocking/StatusUpdateLockingIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.statusupdatelocking; import java.time.Duration; import java.util.Map; @@ -8,10 +8,8 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.statusupdatelocking.StatusUpdateLockingCustomResource; -import io.javaoperatorsdk.operator.sample.statusupdatelocking.StatusUpdateLockingReconciler; -import static io.javaoperatorsdk.operator.sample.statusupdatelocking.StatusUpdateLockingReconciler.WAIT_TIME; +import static io.javaoperatorsdk.operator.baseapi.statusupdatelocking.StatusUpdateLockingReconciler.WAIT_TIME; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; @@ -21,23 +19,27 @@ class StatusUpdateLockingIT { @RegisterExtension LocallyRunOperatorExtension operator = - LocallyRunOperatorExtension.builder().withReconciler(StatusUpdateLockingReconciler.class) + LocallyRunOperatorExtension.builder() + .withConfigurationService(o -> o.withUseSSAToPatchPrimaryResource(false)) + .withReconciler(StatusUpdateLockingReconciler.class) .build(); @Test - void optimisticLockingDoneOnStatusUpdate() throws InterruptedException { + void noOptimisticLockingDoneOnStatusPatch() throws InterruptedException { var resource = operator.create(createResource()); Thread.sleep(WAIT_TIME / 2); resource.getMetadata().setAnnotations(Map.of("key", "value")); operator.replace(resource); - await().pollDelay(Duration.ofMillis(WAIT_TIME)).untilAsserted(() -> { - assertThat( - operator.getReconcilerOfType(StatusUpdateLockingReconciler.class).getNumberOfExecutions()) - .isEqualTo(2); - assertThat(operator.get(StatusUpdateLockingCustomResource.class, TEST_RESOURCE_NAME) - .getStatus().getValue()).isEqualTo(1); - }); + await().pollDelay(Duration.ofMillis(WAIT_TIME)).timeout(Duration.ofSeconds(460)) + .untilAsserted(() -> { + assertThat( + operator.getReconcilerOfType(StatusUpdateLockingReconciler.class) + .getNumberOfExecutions()) + .isEqualTo(1); + assertThat(operator.get(StatusUpdateLockingCustomResource.class, TEST_RESOURCE_NAME) + .getStatus().getValue()).isEqualTo(1); + }); } StatusUpdateLockingCustomResource createResource() { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statusupdatelocking/StatusUpdateLockingReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statusupdatelocking/StatusUpdateLockingReconciler.java similarity index 81% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statusupdatelocking/StatusUpdateLockingReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statusupdatelocking/StatusUpdateLockingReconciler.java index e21897cf38..31dc727dde 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statusupdatelocking/StatusUpdateLockingReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/statusupdatelocking/StatusUpdateLockingReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.statusupdatelocking; +package io.javaoperatorsdk.operator.baseapi.statusupdatelocking; import java.util.concurrent.atomic.AtomicInteger; @@ -18,8 +18,9 @@ public UpdateControl reconcile( throws InterruptedException { numberOfExecutions.addAndGet(1); Thread.sleep(WAIT_TIME); + resource.setStatus(new StatusUpdateLockingCustomResourceStatus()); resource.getStatus().setValue(resource.getStatus().getValue() + 1); - return UpdateControl.updateStatus(resource); + return UpdateControl.patchStatus(resource); } public int getNumberOfExecutions() { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/subresource/SubResourceTestCustomReconciler.java similarity index 94% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/subresource/SubResourceTestCustomReconciler.java index 1e76681f25..51ae9e9330 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/subresource/SubResourceTestCustomReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.subresource; +package io.javaoperatorsdk.operator.baseapi.subresource; import java.util.concurrent.atomic.AtomicInteger; @@ -33,7 +33,7 @@ public UpdateControl reconcile( ensureStatusExists(resource); resource.getStatus().setState(SubResourceTestCustomResourceStatus.State.SUCCESS); waitXms(RECONCILER_MIN_EXEC_TIME); - return UpdateControl.updateStatus(resource); + return UpdateControl.patchStatus(resource); } private void ensureStatusExists(SubResourceTestCustomResource resource) { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/subresource/SubResourceTestCustomResource.java similarity index 92% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/subresource/SubResourceTestCustomResource.java index 5b96483729..976af2c97f 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/subresource/SubResourceTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.subresource; +package io.javaoperatorsdk.operator.baseapi.subresource; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/subresource/SubResourceTestCustomResourceSpec.java similarity index 81% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomResourceSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/subresource/SubResourceTestCustomResourceSpec.java index 21b8e2bc84..9b6c4f8060 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomResourceSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/subresource/SubResourceTestCustomResourceSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.subresource; +package io.javaoperatorsdk.operator.baseapi.subresource; public class SubResourceTestCustomResourceSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/subresource/SubResourceTestCustomResourceStatus.java similarity index 83% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomResourceStatus.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/subresource/SubResourceTestCustomResourceStatus.java index c1c9d708c0..46080b784e 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomResourceStatus.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/subresource/SubResourceTestCustomResourceStatus.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.subresource; +package io.javaoperatorsdk.operator.baseapi.subresource; public class SubResourceTestCustomResourceStatus { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/SubResourceUpdateIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/subresource/SubResourceUpdateIT.java similarity index 91% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/SubResourceUpdateIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/subresource/SubResourceUpdateIT.java index ee6fc8e422..8a73cadf3f 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/SubResourceUpdateIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/subresource/SubResourceUpdateIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.subresource; import java.util.Collections; import java.util.concurrent.TimeUnit; @@ -8,12 +8,9 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.subresource.SubResourceTestCustomReconciler; -import io.javaoperatorsdk.operator.sample.subresource.SubResourceTestCustomResource; -import io.javaoperatorsdk.operator.sample.subresource.SubResourceTestCustomResourceSpec; import io.javaoperatorsdk.operator.support.TestUtils; -import static io.javaoperatorsdk.operator.sample.subresource.SubResourceTestCustomResourceStatus.State.SUCCESS; +import static io.javaoperatorsdk.operator.baseapi.subresource.SubResourceTestCustomResourceStatus.State.SUCCESS; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/unmodifiabledependentpart/UnmodifiableDependentPartCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/unmodifiabledependentpart/UnmodifiableDependentPartCustomResource.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/unmodifiabledependentpart/UnmodifiableDependentPartCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/unmodifiabledependentpart/UnmodifiableDependentPartCustomResource.java index 013fd62503..7b0d757f82 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/unmodifiabledependentpart/UnmodifiableDependentPartCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/unmodifiabledependentpart/UnmodifiableDependentPartCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.unmodifiabledependentpart; +package io.javaoperatorsdk.operator.baseapi.unmodifiabledependentpart; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/UnmodifiableDependentPartIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/unmodifiabledependentpart/UnmodifiableDependentPartIT.java similarity index 75% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/UnmodifiableDependentPartIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/unmodifiabledependentpart/UnmodifiableDependentPartIT.java index bc0e951d8a..a80905c23a 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/UnmodifiableDependentPartIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/unmodifiabledependentpart/UnmodifiableDependentPartIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.unmodifiabledependentpart; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -6,12 +6,9 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.unmodifiabledependentpart.UnmodifiableDependentPartCustomResource; -import io.javaoperatorsdk.operator.sample.unmodifiabledependentpart.UnmodifiableDependentPartReconciler; -import io.javaoperatorsdk.operator.sample.unmodifiabledependentpart.UnmodifiableDependentPartSpec; -import static io.javaoperatorsdk.operator.sample.unmodifiabledependentpart.UnmodifiablePartConfigMapDependent.ACTUAL_DATA_KEY; -import static io.javaoperatorsdk.operator.sample.unmodifiabledependentpart.UnmodifiablePartConfigMapDependent.UNMODIFIABLE_INITIAL_DATA_KEY; +import static io.javaoperatorsdk.operator.baseapi.unmodifiabledependentpart.UnmodifiablePartConfigMapDependent.ACTUAL_DATA_KEY; +import static io.javaoperatorsdk.operator.baseapi.unmodifiabledependentpart.UnmodifiablePartConfigMapDependent.UNMODIFIABLE_INITIAL_DATA_KEY; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/unmodifiabledependentpart/UnmodifiableDependentPartReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/unmodifiabledependentpart/UnmodifiableDependentPartReconciler.java similarity index 62% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/unmodifiabledependentpart/UnmodifiableDependentPartReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/unmodifiabledependentpart/UnmodifiableDependentPartReconciler.java index fd63a2cb12..9c7f6fb9c1 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/unmodifiabledependentpart/UnmodifiableDependentPartReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/unmodifiabledependentpart/UnmodifiableDependentPartReconciler.java @@ -1,14 +1,12 @@ -package io.javaoperatorsdk.operator.sample.unmodifiabledependentpart; +package io.javaoperatorsdk.operator.baseapi.unmodifiabledependentpart; import java.util.concurrent.atomic.AtomicInteger; -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.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; -@ControllerConfiguration(dependents = {@Dependent(type = UnmodifiablePartConfigMapDependent.class)}) +@Workflow(dependents = {@Dependent(type = UnmodifiablePartConfigMapDependent.class)}) +@ControllerConfiguration public class UnmodifiableDependentPartReconciler implements Reconciler { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/unmodifiabledependentpart/UnmodifiableDependentPartSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/unmodifiabledependentpart/UnmodifiableDependentPartSpec.java similarity index 76% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/unmodifiabledependentpart/UnmodifiableDependentPartSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/unmodifiabledependentpart/UnmodifiableDependentPartSpec.java index 3f9c9b3460..1c896c75c3 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/unmodifiabledependentpart/UnmodifiableDependentPartSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/unmodifiabledependentpart/UnmodifiableDependentPartSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.unmodifiabledependentpart; +package io.javaoperatorsdk.operator.baseapi.unmodifiabledependentpart; public class UnmodifiableDependentPartSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/unmodifiabledependentpart/UnmodifiablePartConfigMapDependent.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/unmodifiabledependentpart/UnmodifiablePartConfigMapDependent.java similarity index 91% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/unmodifiabledependentpart/UnmodifiablePartConfigMapDependent.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/unmodifiabledependentpart/UnmodifiablePartConfigMapDependent.java index a103e53162..d913c0cecd 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/unmodifiabledependentpart/UnmodifiablePartConfigMapDependent.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/unmodifiabledependentpart/UnmodifiablePartConfigMapDependent.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.unmodifiabledependentpart; +package io.javaoperatorsdk.operator.baseapi.unmodifiabledependentpart; import java.util.Map; @@ -21,7 +21,7 @@ public UnmodifiablePartConfigMapDependent() { @Override protected ConfigMap desired(UnmodifiableDependentPartCustomResource primary, Context context) { - var actual = getSecondaryResource(primary, context); + var actual = context.getSecondaryResource(ConfigMap.class); ConfigMap res = new ConfigMapBuilder() .withMetadata(new ObjectMetaBuilder() .withName(primary.getMetadata().getName()) diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleCustomResource.java similarity index 86% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleCustomResource.java index 9c6365e5d0..de877ceb90 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.updatestatusincleanupandreschedule; +package io.javaoperatorsdk.operator.baseapi.updatestatusincleanupandreschedule; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleCustomStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleCustomStatus.java similarity index 80% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleCustomStatus.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleCustomStatus.java index 17e4067a44..dcd9d7dd6c 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleCustomStatus.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleCustomStatus.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.updatestatusincleanupandreschedule; +package io.javaoperatorsdk.operator.baseapi.updatestatusincleanupandreschedule; public class UpdateStatusInCleanupAndRescheduleCustomStatus { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/UpdateStatusInCleanupAndRescheduleIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleIT.java similarity index 84% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/UpdateStatusInCleanupAndRescheduleIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleIT.java index 798ea4eac5..81dc6dd448 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/UpdateStatusInCleanupAndRescheduleIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleIT.java @@ -1,12 +1,10 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.baseapi.updatestatusincleanupandreschedule; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.updatestatusincleanupandreschedule.UpdateStatusInCleanupAndRescheduleCustomResource; -import io.javaoperatorsdk.operator.sample.updatestatusincleanupandreschedule.UpdateStatusInCleanupAndRescheduleReconciler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleReconciler.java similarity index 74% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleReconciler.java index 9fcceca851..ed38df7172 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/baseapi/updatestatusincleanupandreschedule/UpdateStatusInCleanupAndRescheduleReconciler.java @@ -1,9 +1,14 @@ -package io.javaoperatorsdk.operator.sample.updatestatusincleanupandreschedule; +package io.javaoperatorsdk.operator.baseapi.updatestatusincleanupandreschedule; import java.time.LocalTime; import java.time.temporal.ChronoUnit; -import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.reconciler.Cleaner; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.DeleteControl; +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; @ControllerConfiguration public class UpdateStatusInCleanupAndRescheduleReconciler @@ -38,14 +43,10 @@ public DeleteControl cleanup(UpdateStatusInCleanupAndRescheduleCustomResource re resource.getStatus().setCleanupAttempt(currentAttempt + 1); if (!Boolean.FALSE.equals(rescheduleDelayWorked)) { var diff = ChronoUnit.MILLIS.between(lastCleanupExecution, LocalTime.now()); - if (diff < DELAY) { - rescheduleDelayWorked = false; - } else { - rescheduleDelayWorked = true; - } + rescheduleDelayWorked = diff >= DELAY; } } - var res = context.getClient().resource(resource).updateStatus(); + context.getClient().resource(resource).updateStatus(); if (resource.getStatus().getCleanupAttempt() > 5) { return DeleteControl.defaultDelete(); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/BaseConfigurationServiceTest.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/BaseConfigurationServiceTest.java index 0b89da68db..d239122314 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/BaseConfigurationServiceTest.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/BaseConfigurationServiceTest.java @@ -7,32 +7,36 @@ import java.time.Duration; import java.util.List; import java.util.Optional; -import java.util.Set; import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.Service; -import io.javaoperatorsdk.operator.OperatorException; +import io.javaoperatorsdk.operator.ReconcilerUtils; import io.javaoperatorsdk.operator.api.config.AnnotationConfigurable; import io.javaoperatorsdk.operator.api.config.BaseConfigurationService; import io.javaoperatorsdk.operator.api.config.dependent.ConfigurationConverter; import io.javaoperatorsdk.operator.api.config.dependent.Configured; -import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceConfigurationResolver; import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceSpec; +import io.javaoperatorsdk.operator.api.config.informer.Informer; +import io.javaoperatorsdk.operator.api.reconciler.Constants; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; import io.javaoperatorsdk.operator.api.reconciler.MaxReconciliationInterval; 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.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; import io.javaoperatorsdk.operator.api.reconciler.dependent.ReconcileResult; -import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.DependentResourceConfigurator; +import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.ConfiguredDependentResource; +import io.javaoperatorsdk.operator.dependent.dependentssa.DependentSSAReconciler; +import io.javaoperatorsdk.operator.dependent.readonly.ConfigMapReader; +import io.javaoperatorsdk.operator.dependent.readonly.ReadOnlyDependent; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.BooleanWithUndefined; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResourceConfig; @@ -42,17 +46,10 @@ import io.javaoperatorsdk.operator.processing.retry.GradualRetry; import io.javaoperatorsdk.operator.processing.retry.Retry; import io.javaoperatorsdk.operator.processing.retry.RetryExecution; -import io.javaoperatorsdk.operator.sample.dependentssa.DependentSSAReconciler; -import io.javaoperatorsdk.operator.sample.readonly.ConfigMapReader; -import io.javaoperatorsdk.operator.sample.readonly.ReadOnlyDependent; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; + +import static io.javaoperatorsdk.operator.api.reconciler.MaxReconciliationInterval.DEFAULT_INTERVAL; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; class BaseConfigurationServiceTest { @@ -74,64 +71,67 @@ private

io.javaoperatorsdk.operator.api.config.Controlle return configurationService.configFor(reconciler); } - @Test - void defaultValuesShouldBeConsistent() { - final var configuration = configFor(new SelectorReconciler()); - final var annotated = extractDependentKubernetesResourceConfig(configuration, 1); - final var unannotated = extractDependentKubernetesResourceConfig(configuration, 0); - - assertNull(annotated.labelSelector()); - assertNull(unannotated.labelSelector()); - } - - @SuppressWarnings("rawtypes") - private KubernetesDependentResourceConfig extractDependentKubernetesResourceConfig( + @SuppressWarnings({"rawtypes", "unchecked"}) + private static KubernetesDependentResourceConfig extractDependentKubernetesResourceConfig( io.javaoperatorsdk.operator.api.config.ControllerConfiguration configuration, int index) { - final var spec = configuration.getDependentResources().get(index); - return (KubernetesDependentResourceConfig) DependentResourceConfigurationResolver - .configurationFor(spec, configuration); + final var spec = + configuration.getWorkflowSpec().orElseThrow().getDependentResourceSpecs().get(index); + return (KubernetesDependentResourceConfig) configuration.getConfigurationFor(spec); } @Test - @SuppressWarnings("rawtypes") + @SuppressWarnings({"rawtypes", "unchecked"}) void getDependentResources() { var configuration = configFor(new NoDepReconciler()); - var dependents = configuration.getDependentResources(); - assertTrue(dependents.isEmpty()); + + var workflowSpec = configuration.getWorkflowSpec(); + assertTrue(workflowSpec.isEmpty()); configuration = configFor(new OneDepReconciler()); - dependents = configuration.getDependentResources(); + var dependents = configuration.getWorkflowSpec().orElseThrow().getDependentResourceSpecs(); assertFalse(dependents.isEmpty()); assertEquals(1, dependents.size()); final var dependentResourceName = DependentResource.defaultNameFor(ReadOnlyDependent.class); assertTrue(dependents.stream().anyMatch(d -> d.getName().equals(dependentResourceName))); var dependentSpec = findByName(dependents, dependentResourceName); assertEquals(ReadOnlyDependent.class, dependentSpec.getDependentResourceClass()); - var maybeConfig = - DependentResourceConfigurationResolver.configurationFor(dependentSpec, configuration); + var maybeConfig = extractDependentKubernetesResourceConfig(configuration, 0); assertNotNull(maybeConfig); assertInstanceOf(KubernetesDependentResourceConfig.class, maybeConfig); final var config = (KubernetesDependentResourceConfig) maybeConfig; - // check that the DependentResource inherits the controller's configuration if applicable - assertEquals(1, config.namespaces().size()); - assertEquals(Set.of(OneDepReconciler.CONFIGURED_NS), config.namespaces()); configuration = configFor(new NamedDepReconciler()); - dependents = configuration.getDependentResources(); + dependents = configuration.getWorkflowSpec().orElseThrow().getDependentResourceSpecs(); assertFalse(dependents.isEmpty()); assertEquals(1, dependents.size()); dependentSpec = findByName(dependents, NamedDepReconciler.NAME); assertEquals(ReadOnlyDependent.class, dependentSpec.getDependentResourceClass()); - maybeConfig = DependentResourceConfigurationResolver.configurationFor(dependentSpec, - configuration); + maybeConfig = extractDependentKubernetesResourceConfig(configuration, 0); assertNotNull(maybeConfig); assertInstanceOf(KubernetesDependentResourceConfig.class, maybeConfig); } @Test - void missingAnnotationThrowsException() { + void missingAnnotationCreatesDefaultConfig() { final var reconciler = new MissingAnnotationReconciler(); - Assertions.assertThrows(OperatorException.class, () -> configFor(reconciler)); + var config = configFor(reconciler); + + assertThat(config.getName()).isEqualTo(ReconcilerUtils.getNameFor(reconciler)); + assertThat(config.getRetry()).isInstanceOf(GenericRetry.class); + assertThat(config.getRateLimiter()).isInstanceOf(LinearRateLimiter.class); + assertThat(config.maxReconciliationInterval()).hasValue(Duration.ofHours(DEFAULT_INTERVAL)); + assertThat(config.fieldManager()).isEqualTo(config.getName()); + assertThat(config.getFinalizerName()) + .isEqualTo(ReconcilerUtils.getDefaultFinalizerName(config.getResourceClass())); + + final var informerConfig = config.getInformerConfig(); + assertThat(informerConfig.getLabelSelector()).isNull(); + assertNull(informerConfig.getInformerListLimit()); + assertNull(informerConfig.getOnAddFilter()); + assertNull(informerConfig.getOnUpdateFilter()); + assertNull(informerConfig.getGenericFilter()); + assertNull(informerConfig.getItemStore()); + assertThat(informerConfig.getNamespaces()).isEqualTo(Constants.DEFAULT_NAMESPACES_SET); } @SuppressWarnings("rawtypes") @@ -156,7 +156,7 @@ void tryingToAddDuplicatedDependentsWithoutNameShouldFail() { @Test void addingDuplicatedDependentsWithNameShouldWork() { var config = configFor(new NamedDuplicatedDepReconciler()); - var dependents = config.getDependentResources(); + var dependents = config.getWorkflowSpec().orElseThrow().getDependentResourceSpecs(); assertEquals(2, dependents.size()); assertTrue(findByNameOptional(dependents, NamedDuplicatedDepReconciler.NAME).isPresent() && findByNameOptional(dependents, DependentResource.defaultNameFor(ReadOnlyDependent.class)) @@ -247,7 +247,6 @@ void excludedResourceClassesShouldNotUseSSAByDefault() { final var kubernetesDependentResourceConfig = extractDependentKubernetesResourceConfig(config, 1); assertNotNull(kubernetesDependentResourceConfig); - assertTrue(kubernetesDependentResourceConfig.useSSA().isEmpty()); assertFalse(configurationService.shouldUseSSA(ReadOnlyDependent.class, ConfigMap.class, kubernetesDependentResourceConfig)); } @@ -261,8 +260,7 @@ void excludedResourceClassesShouldUseSSAIfAnnotatedToDoSo() { final var kubernetesDependentResourceConfig = extractDependentKubernetesResourceConfig(config, 0); assertNotNull(kubernetesDependentResourceConfig); - assertFalse(kubernetesDependentResourceConfig.useSSA().isEmpty()); - assertTrue((Boolean) kubernetesDependentResourceConfig.useSSA().get()); + assertTrue(kubernetesDependentResourceConfig.useSSA()); assertTrue(configurationService.shouldUseSSA(SelectorReconciler.WithAnnotation.class, ConfigMap.class, kubernetesDependentResourceConfig)); } @@ -274,15 +272,13 @@ void dependentsShouldUseSSAByDefaultIfNotExcluded() { var kubernetesDependentResourceConfig = extractDependentKubernetesResourceConfig(config, 0); assertNotNull(kubernetesDependentResourceConfig); - assertTrue(kubernetesDependentResourceConfig.useSSA().isEmpty()); assertTrue(configurationService.shouldUseSSA( DefaultSSAForDependentsReconciler.DefaultDependent.class, ConfigMapReader.class, kubernetesDependentResourceConfig)); kubernetesDependentResourceConfig = extractDependentKubernetesResourceConfig(config, 1); assertNotNull(kubernetesDependentResourceConfig); - assertTrue(kubernetesDependentResourceConfig.useSSA().isPresent()); - assertFalse((Boolean) kubernetesDependentResourceConfig.useSSA().get()); + assertFalse(kubernetesDependentResourceConfig.useSSA()); assertFalse(configurationService .shouldUseSSA(DefaultSSAForDependentsReconciler.NonSSADependent.class, Service.class, kubernetesDependentResourceConfig)); @@ -299,11 +295,12 @@ void shouldUseSSAShouldAlsoWorkWithManualConfiguration() { configurationService.shouldUseSSA(reconciler.getSsaConfigMapDependent())); } + @SuppressWarnings("unchecked") private static int getValue( io.javaoperatorsdk.operator.api.config.ControllerConfiguration configuration, int index) { - return ((CustomConfig) DependentResourceConfigurationResolver - .configurationFor(configuration.getDependentResources().get(index), configuration)) - .getValue(); + final var spec = + configuration.getWorkflowSpec().orElseThrow().getDependentResourceSpecs().get(index); + return ((CustomConfig) configuration.getConfigurationFor(spec)).value(); } @ControllerConfiguration( @@ -317,8 +314,9 @@ public UpdateControl reconcile(ConfigMap resource, Context } } - @ControllerConfiguration(namespaces = OneDepReconciler.CONFIGURED_NS, - dependents = @Dependent(type = ReadOnlyDependent.class)) + @Workflow(dependents = @Dependent(type = ReadOnlyDependent.class)) + @ControllerConfiguration( + informer = @Informer(namespaces = OneDepReconciler.CONFIGURED_NS)) private static class OneDepReconciler implements Reconciler { private static final String CONFIGURED_NS = "foo"; @@ -330,8 +328,8 @@ public UpdateControl reconcile(ConfigMapReader resource, } } - @ControllerConfiguration( - dependents = @Dependent(type = ReadOnlyDependent.class, name = NamedDepReconciler.NAME)) + @Workflow(dependents = @Dependent(type = ReadOnlyDependent.class, name = NamedDepReconciler.NAME)) + @ControllerConfiguration private static class NamedDepReconciler implements Reconciler { private static final String NAME = "foo"; @@ -343,11 +341,11 @@ public UpdateControl reconcile(ConfigMapReader resource, } } - @ControllerConfiguration( - dependents = { - @Dependent(type = ReadOnlyDependent.class), - @Dependent(type = ReadOnlyDependent.class) - }) + @Workflow(dependents = { + @Dependent(type = ReadOnlyDependent.class), + @Dependent(type = ReadOnlyDependent.class) + }) + @ControllerConfiguration private static class DuplicatedDepReconciler implements Reconciler { @Override @@ -357,11 +355,11 @@ public UpdateControl reconcile(ConfigMapReader resource, } } - @ControllerConfiguration( - dependents = { - @Dependent(type = ReadOnlyDependent.class, name = NamedDuplicatedDepReconciler.NAME), - @Dependent(type = ReadOnlyDependent.class) - }) + @Workflow(dependents = { + @Dependent(type = ReadOnlyDependent.class, name = NamedDuplicatedDepReconciler.NAME), + @Dependent(type = ReadOnlyDependent.class) + }) + @ControllerConfiguration private static class NamedDuplicatedDepReconciler implements Reconciler { private static final String NAME = "duplicated"; @@ -383,11 +381,12 @@ public UpdateControl reconcile(ConfigMapReader resource, } } - @ControllerConfiguration(dependents = { + @Workflow(dependents = { @Dependent(type = SelectorReconciler.WithAnnotation.class), @Dependent(type = ReadOnlyDependent.class) }) - private static class SelectorReconciler implements Reconciler { + @ControllerConfiguration + public static class SelectorReconciler implements Reconciler { @Override public UpdateControl reconcile(ConfigMapReader resource, @@ -396,8 +395,8 @@ public UpdateControl reconcile(ConfigMapReader resource, } @KubernetesDependent(useSSA = BooleanWithUndefined.TRUE) - private static class WithAnnotation - extends KubernetesDependentResource { + public static class WithAnnotation + extends CRUDKubernetesDependentResource { public WithAnnotation() { super(ConfigMap.class); @@ -405,7 +404,7 @@ public WithAnnotation() { } } - private static class MissingAnnotationReconciler implements Reconciler { + public static class MissingAnnotationReconciler implements Reconciler { @Override public UpdateControl reconcile(ConfigMap resource, Context context) { @@ -413,10 +412,11 @@ public UpdateControl reconcile(ConfigMap resource, Context } } - @ControllerConfiguration(dependents = { - @Dependent(type = DefaultSSAForDependentsReconciler.DefaultDependent.class), - @Dependent(type = DefaultSSAForDependentsReconciler.NonSSADependent.class) - }) + @Workflow( + dependents = { + @Dependent(type = DefaultSSAForDependentsReconciler.DefaultDependent.class), + @Dependent(type = DefaultSSAForDependentsReconciler.NonSSADependent.class) + }) private static class DefaultSSAForDependentsReconciler implements Reconciler { @Override @@ -532,10 +532,11 @@ public UpdateControl reconcile(ConfigMap resource, Context } } - @ControllerConfiguration(dependents = { + @Workflow(dependents = { @Dependent(type = CustomAnnotatedDep.class), @Dependent(type = ChildCustomAnnotatedDep.class) }) + @ControllerConfiguration() private static class CustomAnnotationReconciler implements Reconciler { @Override @@ -548,7 +549,7 @@ public UpdateControl reconcile(ConfigMap resource, Context @Configured(by = CustomAnnotation.class, with = CustomConfig.class, converter = CustomConfigConverter.class) private static class CustomAnnotatedDep implements DependentResource, - DependentResourceConfigurator { + ConfiguredDependentResource { public static final int PROVIDED_VALUE = 42; private CustomConfig config; @@ -584,28 +585,17 @@ private static class ChildCustomAnnotatedDep extends CustomAnnotatedDep { int value(); } - private static class CustomConfig { - - private final int value; - - private CustomConfig(int value) { - this.value = value; - } - - public int getValue() { - return value; - } - } + private record CustomConfig(int value) {} private static class CustomConfigConverter - implements ConfigurationConverter { + implements ConfigurationConverter { static final int CONVERTER_PROVIDED_DEFAULT = 7; @Override public CustomConfig configFrom(CustomAnnotation configAnnotation, - io.javaoperatorsdk.operator.api.config.ControllerConfiguration parentConfiguration, - Class originatingClass) { + DependentResourceSpec spec, + io.javaoperatorsdk.operator.api.config.ControllerConfiguration parentConfiguration) { if (configAnnotation == null) { return new CustomConfig(CONVERTER_PROVIDED_DEFAULT); } else { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/runtime/ControllerConfigurationAnnotationProcessorTest.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/runtime/ControllerConfigurationAnnotationProcessorTest.java index ce9637af9e..a7365c19b9 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/runtime/ControllerConfigurationAnnotationProcessorTest.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/runtime/ControllerConfigurationAnnotationProcessorTest.java @@ -33,7 +33,7 @@ public void generateCorrectDoneableClassIfThereIsAbstractBaseController() { } @Test - public void generateDoneableClasswithMultilevelHierarchy() { + public void generateDoneableClassWithMultilevelHierarchy() { Compilation compilation = Compiler.javac() .withProcessors(new ControllerConfigurationAnnotationProcessor()) diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent/BulkDependentDeleterIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/BulkDependentDeleterIT.java similarity index 66% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent/BulkDependentDeleterIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/BulkDependentDeleterIT.java index a934bdd1f3..be7365951e 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent/BulkDependentDeleterIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/BulkDependentDeleterIT.java @@ -1,9 +1,9 @@ -package io.javaoperatorsdk.operator.bulkdependent; +package io.javaoperatorsdk.operator.dependent.bulkdependent; import org.junit.jupiter.api.extension.RegisterExtension; +import io.javaoperatorsdk.operator.dependent.bulkdependent.managed.ManagedDeleterBulkReconciler; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.bulkdependent.ManagedDeleterBulkReconciler; public class BulkDependentDeleterIT extends BulkDependentTestBase { @@ -13,7 +13,7 @@ public class BulkDependentDeleterIT extends BulkDependentTestBase { .build(); @Override - LocallyRunOperatorExtension extension() { + public LocallyRunOperatorExtension extension() { return extension; } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent/BulkDependentTestBase.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/BulkDependentTestBase.java similarity index 86% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent/BulkDependentTestBase.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/BulkDependentTestBase.java index 605731623c..0441e31205 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent/BulkDependentTestBase.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/BulkDependentTestBase.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.bulkdependent; +package io.javaoperatorsdk.operator.dependent.bulkdependent; import java.time.Duration; @@ -6,12 +6,9 @@ import io.fabric8.kubernetes.api.model.ObjectMeta; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.bulkdependent.BulkDependentTestCustomResource; -import io.javaoperatorsdk.operator.sample.bulkdependent.BulkDependentTestSpec; -import io.javaoperatorsdk.operator.sample.bulkdependent.ConfigMapDeleterBulkDependentResource; -import static io.javaoperatorsdk.operator.sample.bulkdependent.ConfigMapDeleterBulkDependentResource.LABEL_KEY; -import static io.javaoperatorsdk.operator.sample.bulkdependent.ConfigMapDeleterBulkDependentResource.LABEL_VALUE; +import static io.javaoperatorsdk.operator.dependent.bulkdependent.ConfigMapDeleterBulkDependentResource.LABEL_KEY; +import static io.javaoperatorsdk.operator.dependent.bulkdependent.ConfigMapDeleterBulkDependentResource.LABEL_VALUE; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; @@ -110,5 +107,5 @@ public static void updateSpecWithNumber(LocallyRunOperatorExtension extension, i extension.replace(resource); } - abstract LocallyRunOperatorExtension extension(); + public abstract LocallyRunOperatorExtension extension(); } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/BulkDependentTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/BulkDependentTestCustomResource.java similarity index 88% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/BulkDependentTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/BulkDependentTestCustomResource.java index a0af65d0d3..f7451e06d6 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/BulkDependentTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/BulkDependentTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.bulkdependent; +package io.javaoperatorsdk.operator.dependent.bulkdependent; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/BulkDependentTestSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/BulkDependentTestSpec.java similarity index 89% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/BulkDependentTestSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/BulkDependentTestSpec.java index 5266950b41..b6cd2b136b 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/BulkDependentTestSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/BulkDependentTestSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.bulkdependent; +package io.javaoperatorsdk.operator.dependent.bulkdependent; public class BulkDependentTestSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/BulkDependentTestStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/BulkDependentTestStatus.java similarity index 78% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/BulkDependentTestStatus.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/BulkDependentTestStatus.java index cd16280ce9..38bf94bf0c 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/BulkDependentTestStatus.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/BulkDependentTestStatus.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.bulkdependent; +package io.javaoperatorsdk.operator.dependent.bulkdependent; public class BulkDependentTestStatus { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/CRUDConfigMapBulkDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/CRUDConfigMapBulkDependentResource.java similarity index 79% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/CRUDConfigMapBulkDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/CRUDConfigMapBulkDependentResource.java index 83cec0bb69..236118c2c7 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/CRUDConfigMapBulkDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/CRUDConfigMapBulkDependentResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.bulkdependent; +package io.javaoperatorsdk.operator.dependent.bulkdependent; import io.javaoperatorsdk.operator.api.reconciler.dependent.GarbageCollected; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/ConfigMapDeleterBulkDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/ConfigMapDeleterBulkDependentResource.java similarity index 77% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/ConfigMapDeleterBulkDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/ConfigMapDeleterBulkDependentResource.java index 29a9af89e7..cba3db3835 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/ConfigMapDeleterBulkDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/ConfigMapDeleterBulkDependentResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.bulkdependent; +package io.javaoperatorsdk.operator.dependent.bulkdependent; import java.util.HashMap; import java.util.Map; @@ -8,10 +8,7 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.api.reconciler.dependent.Deleter; -import io.javaoperatorsdk.operator.processing.dependent.BulkDependentResource; -import io.javaoperatorsdk.operator.processing.dependent.Creator; -import io.javaoperatorsdk.operator.processing.dependent.Updater; +import io.javaoperatorsdk.operator.processing.dependent.*; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; /** @@ -20,10 +17,7 @@ public class ConfigMapDeleterBulkDependentResource extends KubernetesDependentResource - implements Creator, - Updater, - Deleter, - BulkDependentResource { + implements CRUDBulkDependentResource { public static final String LABEL_KEY = "bulk"; public static final String LABEL_VALUE = "true"; @@ -41,13 +35,12 @@ public Map desiredResources(BulkDependentTestCustomResource p Map res = new HashMap<>(); for (int i = 0; i < number; i++) { var key = Integer.toString(i); - res.put(key, desired(primary, key, context)); + res.put(key, desired(primary, key)); } return res; } - public ConfigMap desired(BulkDependentTestCustomResource primary, String key, - Context context) { + public ConfigMap desired(BulkDependentTestCustomResource primary, String key) { ConfigMap configMap = new ConfigMap(); configMap.setMetadata(new ObjectMetaBuilder() .withName(primary.getMetadata().getName() + INDEX_DELIMITER + key) diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent/BulkDependentWithConditionIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/condition/BulkDependentWithConditionIT.java similarity index 63% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent/BulkDependentWithConditionIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/condition/BulkDependentWithConditionIT.java index b922bb73b4..d4b857bf0c 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent/BulkDependentWithConditionIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/condition/BulkDependentWithConditionIT.java @@ -1,16 +1,15 @@ -package io.javaoperatorsdk.operator.bulkdependent; +package io.javaoperatorsdk.operator.dependent.bulkdependent.condition; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; +import io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestCustomResource; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.bulkdependent.BulkDependentTestCustomResource; -import io.javaoperatorsdk.operator.sample.bulkdependent.ManagedBulkDependentWithReadyConditionReconciler; -import static io.javaoperatorsdk.operator.bulkdependent.BulkDependentTestBase.INITIAL_NUMBER_OF_CONFIG_MAPS; -import static io.javaoperatorsdk.operator.bulkdependent.BulkDependentTestBase.testResource; -import static io.javaoperatorsdk.operator.sample.bulkdependent.ConfigMapDeleterBulkDependentResource.LABEL_KEY; -import static io.javaoperatorsdk.operator.sample.bulkdependent.ConfigMapDeleterBulkDependentResource.LABEL_VALUE; +import static io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestBase.INITIAL_NUMBER_OF_CONFIG_MAPS; +import static io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestBase.testResource; +import static io.javaoperatorsdk.operator.dependent.bulkdependent.ConfigMapDeleterBulkDependentResource.LABEL_KEY; +import static io.javaoperatorsdk.operator.dependent.bulkdependent.ConfigMapDeleterBulkDependentResource.LABEL_VALUE; import static org.assertj.core.api.Assertions.*; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/ManagedBulkDependentWithReadyConditionReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/condition/ManagedBulkDependentWithReadyConditionReconciler.java similarity index 55% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/ManagedBulkDependentWithReadyConditionReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/condition/ManagedBulkDependentWithReadyConditionReconciler.java index aca78d5d25..331d064b80 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/ManagedBulkDependentWithReadyConditionReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/condition/ManagedBulkDependentWithReadyConditionReconciler.java @@ -1,16 +1,16 @@ -package io.javaoperatorsdk.operator.sample.bulkdependent; +package io.javaoperatorsdk.operator.dependent.bulkdependent.condition; import java.util.concurrent.atomic.AtomicInteger; -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.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; -import io.javaoperatorsdk.operator.processing.dependent.workflow.WorkflowReconcileResult; +import io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestCustomResource; +import io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestStatus; +import io.javaoperatorsdk.operator.dependent.bulkdependent.CRUDConfigMapBulkDependentResource; -@ControllerConfiguration(dependents = @Dependent(readyPostcondition = SampleBulkCondition.class, +@Workflow(dependents = @Dependent(readyPostcondition = SampleBulkCondition.class, type = CRUDConfigMapBulkDependentResource.class)) +@ControllerConfiguration() public class ManagedBulkDependentWithReadyConditionReconciler implements Reconciler { @@ -22,8 +22,9 @@ public UpdateControl reconcile( Context context) throws Exception { numberOfExecutions.incrementAndGet(); - var ready = context.managedDependentResourceContext().getWorkflowReconcileResult() - .map(WorkflowReconcileResult::allDependentResourcesReady).orElseThrow(); + var ready = context.managedWorkflowAndDependentResourceContext().getWorkflowReconcileResult() + .allDependentResourcesReady(); + resource.setStatus(new BulkDependentTestStatus()); resource.getStatus().setReady(ready); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/SampleBulkCondition.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/condition/SampleBulkCondition.java similarity index 80% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/SampleBulkCondition.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/condition/SampleBulkCondition.java index 74048e7b54..c6e64b7413 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/SampleBulkCondition.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/condition/SampleBulkCondition.java @@ -1,8 +1,10 @@ -package io.javaoperatorsdk.operator.sample.bulkdependent; +package io.javaoperatorsdk.operator.dependent.bulkdependent.condition; import io.fabric8.kubernetes.api.model.ConfigMap; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; +import io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestCustomResource; +import io.javaoperatorsdk.operator.dependent.bulkdependent.CRUDConfigMapBulkDependentResource; import io.javaoperatorsdk.operator.processing.dependent.workflow.Condition; public class SampleBulkCondition diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent/BulkExternalDependentIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/external/BulkExternalDependentIT.java similarity index 83% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent/BulkExternalDependentIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/external/BulkExternalDependentIT.java index 29f66e8205..d25f92d2be 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent/BulkExternalDependentIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/external/BulkExternalDependentIT.java @@ -1,13 +1,11 @@ -package io.javaoperatorsdk.operator.bulkdependent; +package io.javaoperatorsdk.operator.dependent.bulkdependent.external; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.bulkdependent.external.ExternalBulkResourceReconciler; -import io.javaoperatorsdk.operator.sample.bulkdependent.external.ExternalServiceMock; -import static io.javaoperatorsdk.operator.bulkdependent.BulkDependentTestBase.*; +import static io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestBase.*; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/external/ExternalBulkDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/external/ExternalBulkDependentResource.java similarity index 90% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/external/ExternalBulkDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/external/ExternalBulkDependentResource.java index dbad6dcfb8..5112b09be1 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/external/ExternalBulkDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/external/ExternalBulkDependentResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.bulkdependent.external; +package io.javaoperatorsdk.operator.dependent.bulkdependent.external; import java.util.HashMap; import java.util.HashSet; @@ -7,15 +7,19 @@ import java.util.stream.Collectors; import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.dependent.Deleter; +import io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestCustomResource; import io.javaoperatorsdk.operator.processing.dependent.BulkDependentResource; import io.javaoperatorsdk.operator.processing.dependent.BulkUpdater; +import io.javaoperatorsdk.operator.processing.dependent.Creator; import io.javaoperatorsdk.operator.processing.dependent.external.PollingDependentResource; import io.javaoperatorsdk.operator.processing.event.ResourceID; -import io.javaoperatorsdk.operator.sample.bulkdependent.BulkDependentTestCustomResource; public class ExternalBulkDependentResource extends PollingDependentResource implements BulkDependentResource, + Creator, + Deleter, BulkUpdater { public static final String EXTERNAL_RESOURCE_NAME_DELIMITER = "#"; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/external/ExternalBulkResourceReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/external/ExternalBulkResourceReconciler.java new file mode 100644 index 0000000000..1668a1b5d9 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/external/ExternalBulkResourceReconciler.java @@ -0,0 +1,17 @@ +package io.javaoperatorsdk.operator.dependent.bulkdependent.external; + +import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; +import io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestCustomResource; + +@Workflow(dependents = @Dependent(type = ExternalBulkDependentResource.class)) +@ControllerConfiguration() +public class ExternalBulkResourceReconciler implements Reconciler { + + @Override + public UpdateControl reconcile( + BulkDependentTestCustomResource resource, Context context) + throws Exception { + return UpdateControl.noUpdate(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/external/ExternalResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/external/ExternalResource.java similarity index 90% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/external/ExternalResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/external/ExternalResource.java index ef101a8ca2..dfe8468fff 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/external/ExternalResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/external/ExternalResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.bulkdependent.external; +package io.javaoperatorsdk.operator.dependent.bulkdependent.external; import java.util.Objects; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/external/ExternalServiceMock.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/external/ExternalServiceMock.java similarity index 93% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/external/ExternalServiceMock.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/external/ExternalServiceMock.java index 4ae0cbccfa..16008be9ff 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/external/ExternalServiceMock.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/external/ExternalServiceMock.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.bulkdependent.external; +package io.javaoperatorsdk.operator.dependent.bulkdependent.external; import java.util.ArrayList; import java.util.List; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent/ManagedBulkDependentIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/managed/ManagedBulkDependentIT.java similarity index 56% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent/ManagedBulkDependentIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/managed/ManagedBulkDependentIT.java index 7f074ac8f5..9f3d763f1b 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent/ManagedBulkDependentIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/managed/ManagedBulkDependentIT.java @@ -1,11 +1,11 @@ -package io.javaoperatorsdk.operator.bulkdependent; +package io.javaoperatorsdk.operator.dependent.bulkdependent.managed; import org.junit.jupiter.api.extension.RegisterExtension; +import io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestBase; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.bulkdependent.ManagedBulkDependentReconciler; -class ManagedBulkDependentIT extends BulkDependentTestBase { +public class ManagedBulkDependentIT extends BulkDependentTestBase { @RegisterExtension LocallyRunOperatorExtension extension = @@ -14,7 +14,7 @@ class ManagedBulkDependentIT extends BulkDependentTestBase { @Override - LocallyRunOperatorExtension extension() { + public LocallyRunOperatorExtension extension() { return extension; } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/ManagedBulkDependentReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/managed/ManagedBulkDependentReconciler.java similarity index 58% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/ManagedBulkDependentReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/managed/ManagedBulkDependentReconciler.java index 3b2acd942e..be323949aa 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/ManagedBulkDependentReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/managed/ManagedBulkDependentReconciler.java @@ -1,14 +1,14 @@ -package io.javaoperatorsdk.operator.sample.bulkdependent; +package io.javaoperatorsdk.operator.dependent.bulkdependent.managed; import java.util.concurrent.atomic.AtomicInteger; -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.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; +import io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestCustomResource; +import io.javaoperatorsdk.operator.dependent.bulkdependent.CRUDConfigMapBulkDependentResource; -@ControllerConfiguration(dependents = @Dependent(type = CRUDConfigMapBulkDependentResource.class)) +@Workflow(dependents = @Dependent(type = CRUDConfigMapBulkDependentResource.class)) +@ControllerConfiguration public class ManagedBulkDependentReconciler implements Reconciler { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/managed/ManagedDeleterBulkReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/managed/ManagedDeleterBulkReconciler.java new file mode 100644 index 0000000000..7de2b3898f --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/managed/ManagedDeleterBulkReconciler.java @@ -0,0 +1,19 @@ +package io.javaoperatorsdk.operator.dependent.bulkdependent.managed; + +import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; +import io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestCustomResource; +import io.javaoperatorsdk.operator.dependent.bulkdependent.ConfigMapDeleterBulkDependentResource; + +@Workflow(dependents = @Dependent(type = ConfigMapDeleterBulkDependentResource.class)) +@ControllerConfiguration +public class ManagedDeleterBulkReconciler implements Reconciler { + @Override + public UpdateControl reconcile( + BulkDependentTestCustomResource resource, + Context context) + throws Exception { + + return UpdateControl.noUpdate(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/readonly/ReadOnlyBulkDependentIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/readonly/ReadOnlyBulkDependentIT.java new file mode 100644 index 0000000000..c84ad38de0 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/readonly/ReadOnlyBulkDependentIT.java @@ -0,0 +1,71 @@ +package io.javaoperatorsdk.operator.dependent.bulkdependent.readonly; + +import java.time.Duration; + +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.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestCustomResource; +import io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestSpec; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public class ReadOnlyBulkDependentIT { + + public static final int EXPECTED_NUMBER_OF_RESOURCES = 2; + public static final String TEST = "test"; + + @RegisterExtension + LocallyRunOperatorExtension extension = + LocallyRunOperatorExtension.builder() + .withReconciler(new ReadOnlyBulkReconciler()) + .build(); + + @Test + void readOnlyBulkDependent() { + var primary = extension.create(testCustomResource()); + + await().pollDelay(Duration.ofMillis(150)).untilAsserted(() -> { + var actualPrimary = extension.get(BulkDependentTestCustomResource.class, TEST); + + assertThat(actualPrimary.getStatus()).isNotNull(); + assertThat(actualPrimary.getStatus().getReady()).isFalse(); + }); + + var configMap1 = createConfigMap(1, primary); + extension.create(configMap1); + var configMap2 = createConfigMap(2, primary); + extension.create(configMap2); + + await().untilAsserted(() -> { + var actualPrimary = extension.get(BulkDependentTestCustomResource.class, TEST); + assertThat(actualPrimary.getStatus().getReady()).isTrue(); + }); + } + + private ConfigMap createConfigMap(int i, BulkDependentTestCustomResource primary) { + ConfigMap configMap = new ConfigMap(); + configMap.setMetadata(new ObjectMetaBuilder() + .withName(TEST + ReadOnlyBulkDependentResource.INDEX_DELIMITER + i) + .withNamespace(primary.getMetadata().getNamespace()) + .build()); + configMap.addOwnerReference(primary); + return configMap; + } + + BulkDependentTestCustomResource testCustomResource() { + BulkDependentTestCustomResource customResource = new BulkDependentTestCustomResource(); + customResource.setMetadata(new ObjectMetaBuilder() + .withName(TEST) + .build()); + customResource.setSpec(new BulkDependentTestSpec()); + customResource.getSpec().setNumberOfResources(EXPECTED_NUMBER_OF_RESOURCES); + + return customResource; + } + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/readonly/ReadOnlyBulkDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/readonly/ReadOnlyBulkDependentResource.java new file mode 100644 index 0000000000..e655d96d6e --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/readonly/ReadOnlyBulkDependentResource.java @@ -0,0 +1,52 @@ +package io.javaoperatorsdk.operator.dependent.bulkdependent.readonly; + +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestCustomResource; +import io.javaoperatorsdk.operator.processing.dependent.BulkDependentResource; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; +import io.javaoperatorsdk.operator.processing.event.ResourceID; +import io.javaoperatorsdk.operator.processing.event.source.SecondaryToPrimaryMapper; +import io.javaoperatorsdk.operator.processing.event.source.informer.Mappers; + + +@KubernetesDependent +public class ReadOnlyBulkDependentResource + extends + KubernetesDependentResource + implements BulkDependentResource, + SecondaryToPrimaryMapper { + + public static final String INDEX_DELIMITER = "-"; + + public ReadOnlyBulkDependentResource() { + super(ConfigMap.class); + } + + @Override + public Map getSecondaryResources(BulkDependentTestCustomResource primary, + Context context) { + return context.getSecondaryResourcesAsStream(ConfigMap.class) + .filter(cm -> getName(cm).startsWith(primary.getMetadata().getName())) + .collect(Collectors.toMap( + cm -> getName(cm).substring(getName(cm).lastIndexOf(INDEX_DELIMITER) + 1), + Function.identity())); + } + + private static String getName(ConfigMap cm) { + return cm.getMetadata().getName(); + } + + @Override + public Set toPrimaryResourceIDs(ConfigMap resource) { + return Mappers.fromOwnerReferences(BulkDependentTestCustomResource.class, false) + .toPrimaryResourceIDs(resource); + } + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/readonly/ReadOnlyBulkReadyPostCondition.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/readonly/ReadOnlyBulkReadyPostCondition.java new file mode 100644 index 0000000000..9be51eb1f6 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/readonly/ReadOnlyBulkReadyPostCondition.java @@ -0,0 +1,23 @@ +package io.javaoperatorsdk.operator.dependent.bulkdependent.readonly; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; +import io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestCustomResource; +import io.javaoperatorsdk.operator.processing.dependent.BulkDependentResource; +import io.javaoperatorsdk.operator.processing.dependent.workflow.Condition; + +public class ReadOnlyBulkReadyPostCondition + implements Condition { + @Override + public boolean isMet( + DependentResource dependentResource, + BulkDependentTestCustomResource primary, Context context) { + var minResourceNumber = primary.getSpec().getNumberOfResources(); + @SuppressWarnings("unchecked") + var secondaryResources = + ((BulkDependentResource) dependentResource) + .getSecondaryResources(primary, context); + return minResourceNumber <= secondaryResources.size(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/readonly/ReadOnlyBulkReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/readonly/ReadOnlyBulkReconciler.java new file mode 100644 index 0000000000..5a78f94be7 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/readonly/ReadOnlyBulkReconciler.java @@ -0,0 +1,33 @@ +package io.javaoperatorsdk.operator.dependent.bulkdependent.readonly; + +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; +import io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestCustomResource; +import io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestStatus; + +@Workflow(dependents = @Dependent(type = ReadOnlyBulkDependentResource.class, + readyPostcondition = ReadOnlyBulkReadyPostCondition.class)) +@ControllerConfiguration +public class ReadOnlyBulkReconciler implements Reconciler { + @Override + public UpdateControl reconcile( + BulkDependentTestCustomResource resource, Context context) { + + var nonReadyDependents = + context.managedWorkflowAndDependentResourceContext().getWorkflowReconcileResult() + .getNotReadyDependents(); + + + BulkDependentTestCustomResource customResource = new BulkDependentTestCustomResource(); + customResource.setMetadata(new ObjectMetaBuilder() + .withName(resource.getMetadata().getName()) + .withNamespace(resource.getMetadata().getNamespace()) + .build()); + var status = new BulkDependentTestStatus(); + status.setReady(nonReadyDependents.isEmpty()); + customResource.setStatus(status); + + return UpdateControl.patchStatus(customResource); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent/StandaloneBulkDependentIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/standalone/StandaloneBulkDependentIT.java similarity index 67% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent/StandaloneBulkDependentIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/standalone/StandaloneBulkDependentIT.java index 683cc1662b..5e0ded6100 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/bulkdependent/StandaloneBulkDependentIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/standalone/StandaloneBulkDependentIT.java @@ -1,9 +1,9 @@ -package io.javaoperatorsdk.operator.bulkdependent; +package io.javaoperatorsdk.operator.dependent.bulkdependent.standalone; import org.junit.jupiter.api.extension.RegisterExtension; +import io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestBase; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.bulkdependent.StandaloneBulkDependentReconciler; class StandaloneBulkDependentIT extends BulkDependentTestBase { @@ -13,7 +13,7 @@ class StandaloneBulkDependentIT extends BulkDependentTestBase { .build(); @Override - LocallyRunOperatorExtension extension() { + public LocallyRunOperatorExtension extension() { return extension; } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/StandaloneBulkDependentReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/standalone/StandaloneBulkDependentReconciler.java similarity index 67% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/StandaloneBulkDependentReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/standalone/StandaloneBulkDependentReconciler.java index 6af93232b4..ab74c41906 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/StandaloneBulkDependentReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/bulkdependent/standalone/StandaloneBulkDependentReconciler.java @@ -1,16 +1,18 @@ -package io.javaoperatorsdk.operator.sample.bulkdependent; +package io.javaoperatorsdk.operator.dependent.bulkdependent.standalone; -import java.util.Map; +import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.dependent.bulkdependent.BulkDependentTestCustomResource; +import io.javaoperatorsdk.operator.dependent.bulkdependent.CRUDConfigMapBulkDependentResource; +import io.javaoperatorsdk.operator.dependent.bulkdependent.ConfigMapDeleterBulkDependentResource; import io.javaoperatorsdk.operator.processing.event.source.EventSource; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; @ControllerConfiguration public class StandaloneBulkDependentReconciler - implements Reconciler, TestExecutionInfoProvider, - EventSourceInitializer { + implements Reconciler, TestExecutionInfoProvider { private final AtomicInteger numberOfExecutions = new AtomicInteger(0); @@ -36,9 +38,8 @@ public int getNumberOfExecutions() { } @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { - return EventSourceInitializer - .nameEventSources(dependent.initEventSource(context)); + return List.of(dependent.initEventSource(context)); } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanermanageddependent/CleanerForManagedDependentCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/cleanermanageddependent/CleanerForManagedDependentCustomResource.java similarity index 88% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanermanageddependent/CleanerForManagedDependentCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/cleanermanageddependent/CleanerForManagedDependentCustomResource.java index 9e18e657aa..c5cd602ba5 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanermanageddependent/CleanerForManagedDependentCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/cleanermanageddependent/CleanerForManagedDependentCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.cleanermanageddependent; +package io.javaoperatorsdk.operator.dependent.cleanermanageddependent; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DeleterForManagedDependentResourcesOnlyIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/cleanermanageddependent/CleanerForManagedDependentResourcesOnlyIT.java similarity index 80% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/DeleterForManagedDependentResourcesOnlyIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/cleanermanageddependent/CleanerForManagedDependentResourcesOnlyIT.java index 66db8ecb5e..000fe2b28e 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DeleterForManagedDependentResourcesOnlyIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/cleanermanageddependent/CleanerForManagedDependentResourcesOnlyIT.java @@ -1,18 +1,15 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.cleanermanageddependent; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.cleanermanageddependent.CleanerForManagedDependentCustomResource; -import io.javaoperatorsdk.operator.sample.cleanermanageddependent.CleanerForManagedDependentTestReconciler; -import io.javaoperatorsdk.operator.sample.cleanermanageddependent.ConfigMapDependentResource; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; -class DeleterForManagedDependentResourcesOnlyIT { +class CleanerForManagedDependentResourcesOnlyIT { public static final String TEST_RESOURCE_NAME = "cleaner-for-reconciler-test1"; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanermanageddependent/CleanerForManagedDependentTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/cleanermanageddependent/CleanerForManagedDependentTestReconciler.java similarity index 83% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanermanageddependent/CleanerForManagedDependentTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/cleanermanageddependent/CleanerForManagedDependentTestReconciler.java index 6be29c5092..bf9a45e29e 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanermanageddependent/CleanerForManagedDependentTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/cleanermanageddependent/CleanerForManagedDependentTestReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.cleanermanageddependent; +package io.javaoperatorsdk.operator.dependent.cleanermanageddependent; import java.util.concurrent.atomic.AtomicInteger; @@ -6,7 +6,8 @@ import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -@ControllerConfiguration(dependents = {@Dependent(type = ConfigMapDependentResource.class)}) +@Workflow(dependents = {@Dependent(type = ConfigMapDependentResource.class)}) +@ControllerConfiguration public class CleanerForManagedDependentTestReconciler implements Reconciler, TestExecutionInfoProvider { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanermanageddependent/ConfigMapDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/cleanermanageddependent/ConfigMapDependentResource.java similarity index 96% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanermanageddependent/ConfigMapDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/cleanermanageddependent/ConfigMapDependentResource.java index 9941779784..fbb964f196 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/cleanermanageddependent/ConfigMapDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/cleanermanageddependent/ConfigMapDependentResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.cleanermanageddependent; +package io.javaoperatorsdk.operator.dependent.cleanermanageddependent; import java.util.HashMap; import java.util.concurrent.atomic.AtomicInteger; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createonlyifnotexistsdependentwithssa/ConfigMapDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/createonlyifnotexistsdependentwithssa/ConfigMapDependentResource.java similarity index 92% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createonlyifnotexistsdependentwithssa/ConfigMapDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/createonlyifnotexistsdependentwithssa/ConfigMapDependentResource.java index d6947c2834..7d7c62e6b4 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createonlyifnotexistsdependentwithssa/ConfigMapDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/createonlyifnotexistsdependentwithssa/ConfigMapDependentResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.createonlyifnotexistsdependentwithssa; +package io.javaoperatorsdk.operator.dependent.createonlyifnotexistsdependentwithssa; import java.util.Map; @@ -26,5 +26,3 @@ protected ConfigMap desired(CreateOnlyIfNotExistingDependentWithSSACustomResourc return configMap; } } - - diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createonlyifnotexistsdependentwithssa/CreateOnlyIfNotExistingDependentWithSSACustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/createonlyifnotexistsdependentwithssa/CreateOnlyIfNotExistingDependentWithSSACustomResource.java similarity index 82% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createonlyifnotexistsdependentwithssa/CreateOnlyIfNotExistingDependentWithSSACustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/createonlyifnotexistsdependentwithssa/CreateOnlyIfNotExistingDependentWithSSACustomResource.java index 23f06c365f..3e53f422bd 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createonlyifnotexistsdependentwithssa/CreateOnlyIfNotExistingDependentWithSSACustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/createonlyifnotexistsdependentwithssa/CreateOnlyIfNotExistingDependentWithSSACustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.createonlyifnotexistsdependentwithssa; +package io.javaoperatorsdk.operator.dependent.createonlyifnotexistsdependentwithssa; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/CreateOnlyIfNotExistingDependentWithSSA.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/createonlyifnotexistsdependentwithssa/CreateOnlyIfNotExistingDependentWithSSAIT.java similarity index 81% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/CreateOnlyIfNotExistingDependentWithSSA.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/createonlyifnotexistsdependentwithssa/CreateOnlyIfNotExistingDependentWithSSAIT.java index 8a347f632e..82e41c4a1d 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/CreateOnlyIfNotExistingDependentWithSSA.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/createonlyifnotexistsdependentwithssa/CreateOnlyIfNotExistingDependentWithSSAIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.createonlyifnotexistsdependentwithssa; import java.time.Duration; import java.util.Map; @@ -10,13 +10,11 @@ import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.createonlyifnotexistsdependentwithssa.CreateOnlyIfNotExistingDependentWithSSACustomResource; -import io.javaoperatorsdk.operator.sample.createonlyifnotexistsdependentwithssa.CreateOnlyIfNotExistingDependentWithSSAReconciler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; -class CreateOnlyIfNotExistingDependentWithSSA { +class CreateOnlyIfNotExistingDependentWithSSAIT { public static final String TEST_RESOURCE_NAME = "test1"; public static final String KEY = "key"; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createonlyifnotexistsdependentwithssa/CreateOnlyIfNotExistingDependentWithSSAReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/createonlyifnotexistsdependentwithssa/CreateOnlyIfNotExistingDependentWithSSAReconciler.java similarity index 68% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createonlyifnotexistsdependentwithssa/CreateOnlyIfNotExistingDependentWithSSAReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/createonlyifnotexistsdependentwithssa/CreateOnlyIfNotExistingDependentWithSSAReconciler.java index 884b5a859d..3699cd1a78 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createonlyifnotexistsdependentwithssa/CreateOnlyIfNotExistingDependentWithSSAReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/createonlyifnotexistsdependentwithssa/CreateOnlyIfNotExistingDependentWithSSAReconciler.java @@ -1,15 +1,13 @@ -package io.javaoperatorsdk.operator.sample.createonlyifnotexistsdependentwithssa; +package io.javaoperatorsdk.operator.dependent.createonlyifnotexistsdependentwithssa; import java.util.concurrent.atomic.AtomicInteger; -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.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; -@ControllerConfiguration(dependents = { +@Workflow(dependents = { @Dependent(type = ConfigMapDependentResource.class)}) +@ControllerConfiguration() public class CreateOnlyIfNotExistingDependentWithSSAReconciler implements Reconciler { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentAnnotationSecondaryMapperIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentannotationsecondarymapper/DependentAnnotationSecondaryMapperIT.java similarity index 88% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentAnnotationSecondaryMapperIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentannotationsecondarymapper/DependentAnnotationSecondaryMapperIT.java index b5b01e1530..8f2f966a22 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentAnnotationSecondaryMapperIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentannotationsecondarymapper/DependentAnnotationSecondaryMapperIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.dependentannotationsecondarymapper; import java.time.Duration; @@ -8,8 +8,6 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.dependentannotationsecondarymapper.DependentAnnotationSecondaryMapperReconciler; -import io.javaoperatorsdk.operator.sample.dependentannotationsecondarymapper.DependentAnnotationSecondaryMapperResource; import static io.javaoperatorsdk.operator.processing.event.source.informer.Mappers.DEFAULT_ANNOTATION_FOR_NAME; import static io.javaoperatorsdk.operator.processing.event.source.informer.Mappers.DEFAULT_ANNOTATION_FOR_NAMESPACE; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentannotationsecondarymapper/DependentAnnotationSecondaryMapperReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentannotationsecondarymapper/DependentAnnotationSecondaryMapperReconciler.java similarity index 94% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentannotationsecondarymapper/DependentAnnotationSecondaryMapperReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentannotationsecondarymapper/DependentAnnotationSecondaryMapperReconciler.java index ec4a2c86b9..7dc17b5695 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentannotationsecondarymapper/DependentAnnotationSecondaryMapperReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentannotationsecondarymapper/DependentAnnotationSecondaryMapperReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentannotationsecondarymapper; +package io.javaoperatorsdk.operator.dependent.dependentannotationsecondarymapper; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; @@ -13,8 +13,9 @@ import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -@ControllerConfiguration(dependents = @Dependent( +@Workflow(dependents = @Dependent( type = DependentAnnotationSecondaryMapperReconciler.ConfigMapDependentResource.class)) +@ControllerConfiguration public class DependentAnnotationSecondaryMapperReconciler implements Reconciler, TestExecutionInfoProvider { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentannotationsecondarymapper/DependentAnnotationSecondaryMapperResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentannotationsecondarymapper/DependentAnnotationSecondaryMapperResource.java similarity index 76% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentannotationsecondarymapper/DependentAnnotationSecondaryMapperResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentannotationsecondarymapper/DependentAnnotationSecondaryMapperResource.java index 22ff6256ae..f41f92d0ef 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentannotationsecondarymapper/DependentAnnotationSecondaryMapperResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentannotationsecondarymapper/DependentAnnotationSecondaryMapperResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentannotationsecondarymapper; +package io.javaoperatorsdk.operator.dependent.dependentannotationsecondarymapper; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; @@ -12,6 +12,6 @@ @Kind("MaxIntervalTestCustomResource") @ShortNames("mit") public class DependentAnnotationSecondaryMapperResource - extends CustomResource + extends CustomResource implements Namespaced { } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentcustommappingannotation/CustomMappingConfigMapDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentcustommappingannotation/CustomMappingConfigMapDependentResource.java similarity index 80% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentcustommappingannotation/CustomMappingConfigMapDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentcustommappingannotation/CustomMappingConfigMapDependentResource.java index 123d360068..ad8639f6cf 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentcustommappingannotation/CustomMappingConfigMapDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentcustommappingannotation/CustomMappingConfigMapDependentResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentcustommappingannotation; +package io.javaoperatorsdk.operator.dependent.dependentcustommappingannotation; import java.util.Map; import java.util.Set; @@ -8,20 +8,24 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDNoGCKubernetesDependentResource; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; import io.javaoperatorsdk.operator.processing.event.ResourceID; import io.javaoperatorsdk.operator.processing.event.source.SecondaryToPrimaryMapper; import io.javaoperatorsdk.operator.processing.event.source.informer.Mappers; +@KubernetesDependent public class CustomMappingConfigMapDependentResource extends CRUDNoGCKubernetesDependentResource implements SecondaryToPrimaryMapper { public static final String CUSTOM_NAME_KEY = "customNameKey"; public static final String CUSTOM_NAMESPACE_KEY = "customNamespaceKey"; + public static final String CUSTOM_TYPE_KEY = "customTypeKey"; public static final String KEY = "key"; - private SecondaryToPrimaryMapper mapper = - Mappers.fromAnnotation(CUSTOM_NAME_KEY, CUSTOM_NAMESPACE_KEY); + private static final SecondaryToPrimaryMapper mapper = + Mappers.fromAnnotation(CUSTOM_NAME_KEY, CUSTOM_NAMESPACE_KEY, CUSTOM_TYPE_KEY, + DependentCustomMappingCustomResource.class); public CustomMappingConfigMapDependentResource() { super(ConfigMap.class); @@ -40,13 +44,17 @@ protected ConfigMap desired(DependentCustomMappingCustomResource primary, } @Override - public Set toPrimaryResourceIDs(ConfigMap resource) { - return mapper.toPrimaryResourceIDs(resource); + protected void addSecondaryToPrimaryMapperAnnotations(ConfigMap desired, + DependentCustomMappingCustomResource primary) { + addSecondaryToPrimaryMapperAnnotations(desired, primary, CUSTOM_NAME_KEY, CUSTOM_NAMESPACE_KEY, + CUSTOM_TYPE_KEY); } + @Override - protected void addSecondaryToPrimaryMapperAnnotations(ConfigMap desired, - DependentCustomMappingCustomResource primary) { - addSecondaryToPrimaryMapperAnnotations(desired, primary, CUSTOM_NAME_KEY, CUSTOM_NAMESPACE_KEY); + public Set toPrimaryResourceIDs(ConfigMap resource) { + return mapper.toPrimaryResourceIDs(resource); } + + } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentCustomMappingAnnotationIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentcustommappingannotation/DependentCustomMappingAnnotationIT.java similarity index 72% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentCustomMappingAnnotationIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentcustommappingannotation/DependentCustomMappingAnnotationIT.java index 8a7d168b26..3d754fc395 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentCustomMappingAnnotationIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentcustommappingannotation/DependentCustomMappingAnnotationIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.dependentcustommappingannotation; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -6,13 +6,9 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.dependentcustommappingannotation.CustomMappingConfigMapDependentResource; -import io.javaoperatorsdk.operator.sample.dependentcustommappingannotation.DependentCustomMappingCustomResource; -import io.javaoperatorsdk.operator.sample.dependentcustommappingannotation.DependentCustomMappingReconciler; -import io.javaoperatorsdk.operator.sample.dependentcustommappingannotation.DependentCustomMappingSpec; -import static io.javaoperatorsdk.operator.sample.dependentcustommappingannotation.CustomMappingConfigMapDependentResource.CUSTOM_NAMESPACE_KEY; -import static io.javaoperatorsdk.operator.sample.dependentcustommappingannotation.CustomMappingConfigMapDependentResource.CUSTOM_NAME_KEY; +import static io.javaoperatorsdk.operator.dependent.dependentcustommappingannotation.CustomMappingConfigMapDependentResource.CUSTOM_NAMESPACE_KEY; +import static io.javaoperatorsdk.operator.dependent.dependentcustommappingannotation.CustomMappingConfigMapDependentResource.CUSTOM_NAME_KEY; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentcustommappingannotation/DependentCustomMappingCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentcustommappingannotation/DependentCustomMappingCustomResource.java similarity index 83% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentcustommappingannotation/DependentCustomMappingCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentcustommappingannotation/DependentCustomMappingCustomResource.java index 47776ed1e7..124a8d1108 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentcustommappingannotation/DependentCustomMappingCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentcustommappingannotation/DependentCustomMappingCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentcustommappingannotation; +package io.javaoperatorsdk.operator.dependent.dependentcustommappingannotation; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentcustommappingannotation/DependentCustomMappingReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentcustommappingannotation/DependentCustomMappingReconciler.java similarity index 71% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentcustommappingannotation/DependentCustomMappingReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentcustommappingannotation/DependentCustomMappingReconciler.java index 8c14f829ff..e8b5d581b1 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentcustommappingannotation/DependentCustomMappingReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentcustommappingannotation/DependentCustomMappingReconciler.java @@ -1,10 +1,10 @@ -package io.javaoperatorsdk.operator.sample.dependentcustommappingannotation; +package io.javaoperatorsdk.operator.dependent.dependentcustommappingannotation; import io.javaoperatorsdk.operator.api.reconciler.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; -@ControllerConfiguration( - dependents = {@Dependent(type = CustomMappingConfigMapDependentResource.class)}) +@Workflow(dependents = {@Dependent(type = CustomMappingConfigMapDependentResource.class)}) +@ControllerConfiguration public class DependentCustomMappingReconciler implements Reconciler { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentcustommappingannotation/DependentCustomMappingSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentcustommappingannotation/DependentCustomMappingSpec.java similarity index 74% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentcustommappingannotation/DependentCustomMappingSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentcustommappingannotation/DependentCustomMappingSpec.java index bc5b92901f..84b34a9491 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentcustommappingannotation/DependentCustomMappingSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentcustommappingannotation/DependentCustomMappingSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentcustommappingannotation; +package io.javaoperatorsdk.operator.dependent.dependentcustommappingannotation; public class DependentCustomMappingSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentdifferentnamespace/ConfigMapDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentdifferentnamespace/ConfigMapDependentResource.java similarity index 93% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentdifferentnamespace/ConfigMapDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentdifferentnamespace/ConfigMapDependentResource.java index ca0d28e934..6bbe6a814e 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentdifferentnamespace/ConfigMapDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentdifferentnamespace/ConfigMapDependentResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentdifferentnamespace; +package io.javaoperatorsdk.operator.dependent.dependentdifferentnamespace; import java.util.HashMap; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentdifferentnamespace/DependentDifferentNamespaceCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentdifferentnamespace/DependentDifferentNamespaceCustomResource.java similarity index 86% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentdifferentnamespace/DependentDifferentNamespaceCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentdifferentnamespace/DependentDifferentNamespaceCustomResource.java index 629fdca1f1..020d147ba9 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentdifferentnamespace/DependentDifferentNamespaceCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentdifferentnamespace/DependentDifferentNamespaceCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentdifferentnamespace; +package io.javaoperatorsdk.operator.dependent.dependentdifferentnamespace; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentDifferentNamespaceIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentdifferentnamespace/DependentDifferentNamespaceIT.java similarity index 78% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentDifferentNamespaceIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentdifferentnamespace/DependentDifferentNamespaceIT.java index 452de53930..b9abf05cad 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentDifferentNamespaceIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentdifferentnamespace/DependentDifferentNamespaceIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.dependentdifferentnamespace; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -6,12 +6,8 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.dependentdifferentnamespace.ConfigMapDependentResource; -import io.javaoperatorsdk.operator.sample.dependentdifferentnamespace.DependentDifferentNamespaceCustomResource; -import io.javaoperatorsdk.operator.sample.dependentdifferentnamespace.DependentDifferentNamespaceReconciler; -import io.javaoperatorsdk.operator.sample.dependentdifferentnamespace.DependentDifferentNamespaceSpec; -import static io.javaoperatorsdk.operator.sample.dependentdifferentnamespace.ConfigMapDependentResource.KEY; +import static io.javaoperatorsdk.operator.dependent.dependentdifferentnamespace.ConfigMapDependentResource.KEY; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentdifferentnamespace/DependentDifferentNamespaceReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentdifferentnamespace/DependentDifferentNamespaceReconciler.java similarity index 82% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentdifferentnamespace/DependentDifferentNamespaceReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentdifferentnamespace/DependentDifferentNamespaceReconciler.java index de9ea20f4a..d4ae1c5e0a 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentdifferentnamespace/DependentDifferentNamespaceReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentdifferentnamespace/DependentDifferentNamespaceReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentdifferentnamespace; +package io.javaoperatorsdk.operator.dependent.dependentdifferentnamespace; import java.util.concurrent.atomic.AtomicInteger; @@ -6,10 +6,10 @@ import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -@ControllerConfiguration( - dependents = { - @Dependent(type = ConfigMapDependentResource.class), - }) +@Workflow(dependents = { + @Dependent(type = ConfigMapDependentResource.class), +}) +@ControllerConfiguration public class DependentDifferentNamespaceReconciler implements Reconciler, TestExecutionInfoProvider { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentdifferentnamespace/DependentDifferentNamespaceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentdifferentnamespace/DependentDifferentNamespaceSpec.java similarity index 76% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentdifferentnamespace/DependentDifferentNamespaceSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentdifferentnamespace/DependentDifferentNamespaceSpec.java index a568ca4885..4c6961fda6 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentdifferentnamespace/DependentDifferentNamespaceSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentdifferentnamespace/DependentDifferentNamespaceSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentdifferentnamespace; +package io.javaoperatorsdk.operator.dependent.dependentdifferentnamespace; public class DependentDifferentNamespaceSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentFilterIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentfilter/DependentFilterIT.java similarity index 76% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentFilterIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentfilter/DependentFilterIT.java index 19d6678a59..328a4a0544 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentFilterIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentfilter/DependentFilterIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.dependentfilter; import java.time.Duration; import java.util.Map; @@ -9,12 +9,9 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.dependentfilter.DependentFilterTestCustomResource; -import io.javaoperatorsdk.operator.sample.dependentfilter.DependentFilterTestReconciler; -import io.javaoperatorsdk.operator.sample.dependentfilter.DependentFilterTestResourceSpec; -import static io.javaoperatorsdk.operator.sample.dependentfilter.DependentFilterTestReconciler.CM_VALUE_KEY; -import static io.javaoperatorsdk.operator.sample.dependentfilter.DependentFilterTestReconciler.CONFIG_MAP_FILTER_VALUE; +import static io.javaoperatorsdk.operator.dependent.dependentfilter.DependentFilterTestReconciler.CM_VALUE_KEY; +import static io.javaoperatorsdk.operator.dependent.dependentfilter.DependentFilterTestReconciler.CONFIG_MAP_FILTER_VALUE; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentfilter/DependentFilterTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentfilter/DependentFilterTestCustomResource.java similarity index 76% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentfilter/DependentFilterTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentfilter/DependentFilterTestCustomResource.java index 0930c29774..43822aafb8 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentfilter/DependentFilterTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentfilter/DependentFilterTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentfilter; +package io.javaoperatorsdk.operator.dependent.dependentfilter; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; @@ -10,7 +10,7 @@ @Version("v1") @ShortNames("dft") public class DependentFilterTestCustomResource - extends CustomResource + extends CustomResource implements Namespaced { public String getConfigMapName(int id) { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentfilter/DependentFilterTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentfilter/DependentFilterTestReconciler.java similarity index 74% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentfilter/DependentFilterTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentfilter/DependentFilterTestReconciler.java index 114491d9b9..2351512046 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentfilter/DependentFilterTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentfilter/DependentFilterTestReconciler.java @@ -1,12 +1,13 @@ -package io.javaoperatorsdk.operator.sample.dependentfilter; +package io.javaoperatorsdk.operator.dependent.dependentfilter; import java.util.concurrent.atomic.AtomicInteger; +import io.javaoperatorsdk.operator.api.config.informer.Informer; import io.javaoperatorsdk.operator.api.reconciler.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; -@ControllerConfiguration(onUpdateFilter = UpdateFilter.class, - dependents = {@Dependent(type = FilteredDependentConfigMap.class)}) +@Workflow(dependents = {@Dependent(type = FilteredDependentConfigMap.class)}) +@ControllerConfiguration(informer = @Informer(onUpdateFilter = UpdateFilter.class)) public class DependentFilterTestReconciler implements Reconciler { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentfilter/DependentFilterTestResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentfilter/DependentFilterTestResourceSpec.java similarity index 79% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentfilter/DependentFilterTestResourceSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentfilter/DependentFilterTestResourceSpec.java index cf6b02e936..a09d68b503 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentfilter/DependentFilterTestResourceSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentfilter/DependentFilterTestResourceSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentfilter; +package io.javaoperatorsdk.operator.dependent.dependentfilter; public class DependentFilterTestResourceSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentfilter/FilteredDependentConfigMap.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentfilter/FilteredDependentConfigMap.java similarity index 76% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentfilter/FilteredDependentConfigMap.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentfilter/FilteredDependentConfigMap.java index ee4bd4cde7..7cbb60c583 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentfilter/FilteredDependentConfigMap.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentfilter/FilteredDependentConfigMap.java @@ -1,16 +1,17 @@ -package io.javaoperatorsdk.operator.sample.dependentfilter; +package io.javaoperatorsdk.operator.dependent.dependentfilter; import java.util.Map; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.api.config.informer.Informer; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; -import static io.javaoperatorsdk.operator.sample.dependentfilter.DependentFilterTestReconciler.CM_VALUE_KEY; +import static io.javaoperatorsdk.operator.dependent.dependentfilter.DependentFilterTestReconciler.CM_VALUE_KEY; -@KubernetesDependent(onUpdateFilter = UpdateFilter.class) +@KubernetesDependent(informer = @Informer(onUpdateFilter = UpdateFilter.class)) public class FilteredDependentConfigMap extends CRUDKubernetesDependentResource { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentfilter/UpdateFilter.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentfilter/UpdateFilter.java similarity index 55% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentfilter/UpdateFilter.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentfilter/UpdateFilter.java index 72e6b1f737..2dd4c8bf99 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentfilter/UpdateFilter.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentfilter/UpdateFilter.java @@ -1,10 +1,10 @@ -package io.javaoperatorsdk.operator.sample.dependentfilter; +package io.javaoperatorsdk.operator.dependent.dependentfilter; import io.fabric8.kubernetes.api.model.ConfigMap; import io.javaoperatorsdk.operator.processing.event.source.filter.OnUpdateFilter; -import static io.javaoperatorsdk.operator.sample.dependentfilter.DependentFilterTestReconciler.CM_VALUE_KEY; -import static io.javaoperatorsdk.operator.sample.dependentfilter.DependentFilterTestReconciler.CONFIG_MAP_FILTER_VALUE; +import static io.javaoperatorsdk.operator.dependent.dependentfilter.DependentFilterTestReconciler.CM_VALUE_KEY; +import static io.javaoperatorsdk.operator.dependent.dependentfilter.DependentFilterTestReconciler.CONFIG_MAP_FILTER_VALUE; public class UpdateFilter implements OnUpdateFilter { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentoperationeventfiltering/ConfigMapDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentoperationeventfiltering/ConfigMapDependentResource.java similarity index 93% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentoperationeventfiltering/ConfigMapDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentoperationeventfiltering/ConfigMapDependentResource.java index 34fbd21c50..3f0ce9a073 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentoperationeventfiltering/ConfigMapDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentoperationeventfiltering/ConfigMapDependentResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentoperationeventfiltering; +package io.javaoperatorsdk.operator.dependent.dependentoperationeventfiltering; import java.util.HashMap; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentoperationeventfiltering/DependentOperationEventFilterCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentoperationeventfiltering/DependentOperationEventFilterCustomResource.java similarity index 88% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentoperationeventfiltering/DependentOperationEventFilterCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentoperationeventfiltering/DependentOperationEventFilterCustomResource.java index f0eaf24353..021c984ec3 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentoperationeventfiltering/DependentOperationEventFilterCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentoperationeventfiltering/DependentOperationEventFilterCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentoperationeventfiltering; +package io.javaoperatorsdk.operator.dependent.dependentoperationeventfiltering; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentoperationeventfiltering/DependentOperationEventFilterCustomResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentoperationeventfiltering/DependentOperationEventFilterCustomResourceSpec.java similarity index 77% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentoperationeventfiltering/DependentOperationEventFilterCustomResourceSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentoperationeventfiltering/DependentOperationEventFilterCustomResourceSpec.java index 205b016907..ba131f75b0 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentoperationeventfiltering/DependentOperationEventFilterCustomResourceSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentoperationeventfiltering/DependentOperationEventFilterCustomResourceSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentoperationeventfiltering; +package io.javaoperatorsdk.operator.dependent.dependentoperationeventfiltering; public class DependentOperationEventFilterCustomResourceSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentoperationeventfiltering/DependentOperationEventFilterCustomResourceTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentoperationeventfiltering/DependentOperationEventFilterCustomResourceTestReconciler.java similarity index 74% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentoperationeventfiltering/DependentOperationEventFilterCustomResourceTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentoperationeventfiltering/DependentOperationEventFilterCustomResourceTestReconciler.java index 4ce74c75eb..3149d1c6d0 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentoperationeventfiltering/DependentOperationEventFilterCustomResourceTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentoperationeventfiltering/DependentOperationEventFilterCustomResourceTestReconciler.java @@ -1,16 +1,17 @@ -package io.javaoperatorsdk.operator.sample.dependentoperationeventfiltering; +package io.javaoperatorsdk.operator.dependent.dependentoperationeventfiltering; import java.util.concurrent.atomic.AtomicInteger; +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.support.TestExecutionInfoProvider; +@Workflow(dependents = { + @Dependent(type = ConfigMapDependentResource.class) +}) @ControllerConfiguration( - namespaces = Constants.WATCH_CURRENT_NAMESPACE, - dependents = { - @Dependent(type = ConfigMapDependentResource.class), - }) + informer = @Informer(namespaces = Constants.WATCH_CURRENT_NAMESPACE)) public class DependentOperationEventFilterCustomResourceTestReconciler implements Reconciler, TestExecutionInfoProvider { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentOperationEventFilterIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentoperationeventfiltering/DependentOperationEventFilterIT.java similarity index 81% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentOperationEventFilterIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentoperationeventfiltering/DependentOperationEventFilterIT.java index eb354bf96d..12413cd4b4 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentOperationEventFilterIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentoperationeventfiltering/DependentOperationEventFilterIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.dependentoperationeventfiltering; import java.time.Duration; @@ -8,10 +8,6 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.dependentoperationeventfiltering.ConfigMapDependentResource; -import io.javaoperatorsdk.operator.sample.dependentoperationeventfiltering.DependentOperationEventFilterCustomResource; -import io.javaoperatorsdk.operator.sample.dependentoperationeventfiltering.DependentOperationEventFilterCustomResourceSpec; -import io.javaoperatorsdk.operator.sample.dependentoperationeventfiltering.DependentOperationEventFilterCustomResourceTestReconciler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentreinitialization/ConfigMapDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentreinitialization/ConfigMapDependentResource.java similarity index 93% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentreinitialization/ConfigMapDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentreinitialization/ConfigMapDependentResource.java index a102060c10..9f80a90f0d 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentreinitialization/ConfigMapDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentreinitialization/ConfigMapDependentResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentreinitialization; +package io.javaoperatorsdk.operator.dependent.dependentreinitialization; import java.util.Map; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentreinitialization/DependentReInitializationCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentreinitialization/DependentReInitializationCustomResource.java similarity index 84% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentreinitialization/DependentReInitializationCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentreinitialization/DependentReInitializationCustomResource.java index ce30463965..a3c4e9f20b 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentreinitialization/DependentReInitializationCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentreinitialization/DependentReInitializationCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentreinitialization; +package io.javaoperatorsdk.operator.dependent.dependentreinitialization; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentReInitializationIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentreinitialization/DependentReInitializationIT.java similarity index 75% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentReInitializationIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentreinitialization/DependentReInitializationIT.java index 73b7bd20d9..c215d82da2 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentReInitializationIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentreinitialization/DependentReInitializationIT.java @@ -1,13 +1,11 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.dependentreinitialization; import org.junit.jupiter.api.Test; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.KubernetesClientBuilder; +import io.javaoperatorsdk.operator.Operator; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.dependentreinitialization.ConfigMapDependentResource; -import io.javaoperatorsdk.operator.sample.dependentreinitialization.DependentReInitializationCustomResource; -import io.javaoperatorsdk.operator.sample.dependentreinitialization.DependentReInitializationReconciler; class DependentReInitializationIT { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentreinitialization/DependentReInitializationReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentreinitialization/DependentReInitializationReconciler.java similarity index 76% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentreinitialization/DependentReInitializationReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentreinitialization/DependentReInitializationReconciler.java index a8e6a48e6b..7f6072665f 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentreinitialization/DependentReInitializationReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentreinitialization/DependentReInitializationReconciler.java @@ -1,14 +1,13 @@ -package io.javaoperatorsdk.operator.sample.dependentreinitialization; +package io.javaoperatorsdk.operator.dependent.dependentreinitialization; -import java.util.Map; +import java.util.List; import io.javaoperatorsdk.operator.api.reconciler.*; import io.javaoperatorsdk.operator.processing.event.source.EventSource; @ControllerConfiguration public class DependentReInitializationReconciler - implements Reconciler, - EventSourceInitializer { + implements Reconciler { private final ConfigMapDependentResource configMapDependentResource; @@ -25,9 +24,9 @@ public UpdateControl reconcile( } @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { - return EventSourceInitializer.nameEventSourcesFromDependentResource(context, + return EventSourceUtils.dependentEventSources(context, configMapDependentResource); } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentResourceCrossRefIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentresourcecrossref/DependentResourceCrossRefIT.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentResourceCrossRefIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentresourcecrossref/DependentResourceCrossRefIT.java index deaa3c7493..0530934dba 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentResourceCrossRefIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentresourcecrossref/DependentResourceCrossRefIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.dependentresourcecrossref; import java.time.Duration; @@ -9,8 +9,6 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.api.model.Secret; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.dependentresourcecrossref.DependentResourceCrossRefReconciler; -import io.javaoperatorsdk.operator.sample.dependentresourcecrossref.DependentResourceCrossRefResource; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentresourcecrossref/DependentResourceCrossRefReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentresourcecrossref/DependentResourceCrossRefReconciler.java similarity index 90% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentresourcecrossref/DependentResourceCrossRefReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentresourcecrossref/DependentResourceCrossRefReconciler.java index bb319741b3..4464c02906 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentresourcecrossref/DependentResourceCrossRefReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentresourcecrossref/DependentResourceCrossRefReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentresourcecrossref; +package io.javaoperatorsdk.operator.dependent.dependentresourcecrossref; import java.util.ArrayList; import java.util.Base64; @@ -12,16 +12,16 @@ import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; -import static io.javaoperatorsdk.operator.sample.dependentresourcecrossref.DependentResourceCrossRefReconciler.SECRET_NAME; +import static io.javaoperatorsdk.operator.dependent.dependentresourcecrossref.DependentResourceCrossRefReconciler.SECRET_NAME; -@ControllerConfiguration(dependents = { +@Workflow(dependents = { @Dependent(name = SECRET_NAME, type = DependentResourceCrossRefReconciler.SecretDependentResource.class), @Dependent(type = DependentResourceCrossRefReconciler.ConfigMapDependentResource.class, dependsOn = SECRET_NAME)}) +@ControllerConfiguration public class DependentResourceCrossRefReconciler - implements Reconciler, - ErrorStatusHandler { + implements Reconciler { public static final String SECRET_NAME = "secret"; private final AtomicInteger numberOfExecutions = new AtomicInteger(0); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentresourcecrossref/DependentResourceCrossRefResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentresourcecrossref/DependentResourceCrossRefResource.java similarity index 70% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentresourcecrossref/DependentResourceCrossRefResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentresourcecrossref/DependentResourceCrossRefResource.java index 1cea1df01e..fd89f7fa70 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentresourcecrossref/DependentResourceCrossRefResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentresourcecrossref/DependentResourceCrossRefResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentresourcecrossref; +package io.javaoperatorsdk.operator.dependent.dependentresourcecrossref; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; @@ -8,6 +8,6 @@ @Group("sample.javaoperatorsdk") @Version("v1") public class DependentResourceCrossRefResource - extends CustomResource + extends CustomResource implements Namespaced { } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentssa/DependentSSACustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentssa/DependentSSACustomResource.java similarity index 88% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentssa/DependentSSACustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentssa/DependentSSACustomResource.java index ca8ea4afc7..ed71a9db64 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentssa/DependentSSACustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentssa/DependentSSACustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentssa; +package io.javaoperatorsdk.operator.dependent.dependentssa; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentSSAMatchingIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentssa/DependentSSAMatchingIT.java similarity index 91% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentSSAMatchingIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentssa/DependentSSAMatchingIT.java index fe6dca887e..ec02dd7f5c 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentSSAMatchingIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentssa/DependentSSAMatchingIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.dependentssa; import java.time.Duration; import java.util.Map; @@ -12,10 +12,6 @@ import io.fabric8.kubernetes.client.dsl.base.PatchContext; import io.fabric8.kubernetes.client.dsl.base.PatchType; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.dependentssa.DependentSSACustomResource; -import io.javaoperatorsdk.operator.sample.dependentssa.DependentSSAReconciler; -import io.javaoperatorsdk.operator.sample.dependentssa.DependentSSASpec; -import io.javaoperatorsdk.operator.sample.dependentssa.SSAConfigMapDependent; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentSSAMigrationIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentssa/DependentSSAMigrationIT.java similarity index 94% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentSSAMigrationIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentssa/DependentSSAMigrationIT.java index 06a32f9b23..bd3aedb5f9 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentSSAMigrationIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentssa/DependentSSAMigrationIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.dependentssa; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -11,11 +11,8 @@ import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.KubernetesClientBuilder; import io.fabric8.kubernetes.client.utils.KubernetesResourceUtil; +import io.javaoperatorsdk.operator.Operator; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.dependentssa.DependentSSACustomResource; -import io.javaoperatorsdk.operator.sample.dependentssa.DependentSSAReconciler; -import io.javaoperatorsdk.operator.sample.dependentssa.DependentSSASpec; -import io.javaoperatorsdk.operator.sample.dependentssa.SSAConfigMapDependent; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentssa/DependentSSAReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentssa/DependentSSAReconciler.java similarity index 71% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentssa/DependentSSAReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentssa/DependentSSAReconciler.java index 9b52dee28d..8825f4007e 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentssa/DependentSSAReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentssa/DependentSSAReconciler.java @@ -1,18 +1,22 @@ -package io.javaoperatorsdk.operator.sample.dependentssa; +package io.javaoperatorsdk.operator.dependent.dependentssa; -import java.util.Map; +import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import io.fabric8.kubernetes.api.model.ConfigMap; -import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceUtils; +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResourceConfigBuilder; import io.javaoperatorsdk.operator.processing.event.source.EventSource; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; @ControllerConfiguration public class DependentSSAReconciler - implements Reconciler, TestExecutionInfoProvider, - EventSourceInitializer { + implements Reconciler, TestExecutionInfoProvider { private final AtomicInteger numberOfExecutions = new AtomicInteger(0); @@ -53,9 +57,9 @@ public int getNumberOfExecutions() { } @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { - return EventSourceInitializer.nameEventSourcesFromDependentResource(context, + return EventSourceUtils.dependentEventSources(context, ssaConfigMapDependent); } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentssa/DependentSSASpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentssa/DependentSSASpec.java similarity index 77% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentssa/DependentSSASpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentssa/DependentSSASpec.java index c7b4dd0053..df4684dce5 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentssa/DependentSSASpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentssa/DependentSSASpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentssa; +package io.javaoperatorsdk.operator.dependent.dependentssa; public class DependentSSASpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentssa/SSAConfigMapDependent.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentssa/SSAConfigMapDependent.java similarity index 95% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentssa/SSAConfigMapDependent.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentssa/SSAConfigMapDependent.java index dbeb9864e2..a912bfcd03 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentssa/SSAConfigMapDependent.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/dependentssa/SSAConfigMapDependent.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.dependentssa; +package io.javaoperatorsdk.operator.dependent.dependentssa; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/ExternalStateCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateCustomResource.java similarity index 88% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/ExternalStateCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateCustomResource.java index 70a51ecc72..353e86d2f9 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/ExternalStateCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.externalstate; +package io.javaoperatorsdk.operator.dependent.externalstate; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ExternalStateDependentIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateDependentIT.java similarity index 60% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/ExternalStateDependentIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateDependentIT.java index fd7132bd2a..adfe1f31a1 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ExternalStateDependentIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateDependentIT.java @@ -1,11 +1,10 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.externalstate; import org.junit.jupiter.api.extension.RegisterExtension; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.externalstate.ExternalStateDependentReconciler; -class ExternalStateDependentIT extends ExternalStateTestBase { +public class ExternalStateDependentIT extends ExternalStateTestBase { @RegisterExtension LocallyRunOperatorExtension operator = @@ -13,7 +12,7 @@ class ExternalStateDependentIT extends ExternalStateTestBase { .build(); @Override - LocallyRunOperatorExtension extension() { + public LocallyRunOperatorExtension extension() { return operator; } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/ExternalStateDependentReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateDependentReconciler.java similarity index 68% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/ExternalStateDependentReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateDependentReconciler.java index 8755e7099c..9140f40587 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/ExternalStateDependentReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateDependentReconciler.java @@ -1,21 +1,20 @@ -package io.javaoperatorsdk.operator.sample.externalstate; +package io.javaoperatorsdk.operator.dependent.externalstate; -import java.util.Map; +import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import io.fabric8.kubernetes.api.model.ConfigMap; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; import io.javaoperatorsdk.operator.api.reconciler.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; import io.javaoperatorsdk.operator.processing.event.source.EventSource; import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -@ControllerConfiguration( - dependents = @Dependent(type = ExternalWithStateDependentResource.class)) +@Workflow(dependents = @Dependent(type = ExternalWithStateDependentResource.class)) +@ControllerConfiguration public class ExternalStateDependentReconciler implements Reconciler, - EventSourceInitializer, TestExecutionInfoProvider { public static final String ID_KEY = "id"; @@ -35,11 +34,13 @@ public int getNumberOfExecutions() { } @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { var configMapEventSource = new InformerEventSource<>( - InformerConfiguration.from(ConfigMap.class, context).build(), context); - return EventSourceInitializer.nameEventSources(configMapEventSource); + InformerEventSourceConfiguration.from(ConfigMap.class, ExternalStateCustomResource.class) + .build(), + context); + return List.of(configMapEventSource); } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ExternalStateIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateIT.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/ExternalStateIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateIT.java index 3da607e324..066d777e80 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ExternalStateIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.externalstate; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -6,12 +6,9 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.externalstate.ExternalStateCustomResource; -import io.javaoperatorsdk.operator.sample.externalstate.ExternalStateReconciler; -import io.javaoperatorsdk.operator.sample.externalstate.ExternalStateSpec; import io.javaoperatorsdk.operator.support.ExternalIDGenServiceMock; -import static io.javaoperatorsdk.operator.sample.externalstate.ExternalStateReconciler.ID_KEY; +import static io.javaoperatorsdk.operator.dependent.externalstate.ExternalStateReconciler.ID_KEY; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/ExternalStateReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateReconciler.java similarity index 71% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/ExternalStateReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateReconciler.java index 66c53c3971..5fb2932152 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/ExternalStateReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateReconciler.java @@ -1,7 +1,9 @@ -package io.javaoperatorsdk.operator.sample.externalstate; +package io.javaoperatorsdk.operator.dependent.externalstate; import java.time.Duration; +import java.util.Arrays; import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; @@ -9,21 +11,27 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; -import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.Cleaner; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.DeleteControl; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.javaoperatorsdk.operator.processing.event.ResourceID; import io.javaoperatorsdk.operator.processing.event.source.EventSource; import io.javaoperatorsdk.operator.processing.event.source.EventSourceStartPriority; import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; +import io.javaoperatorsdk.operator.processing.event.source.polling.PerResourcePollingConfigurationBuilder; import io.javaoperatorsdk.operator.processing.event.source.polling.PerResourcePollingEventSource; import io.javaoperatorsdk.operator.support.ExternalIDGenServiceMock; import io.javaoperatorsdk.operator.support.ExternalResource; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -@ControllerConfiguration() +@ControllerConfiguration public class ExternalStateReconciler implements Reconciler, Cleaner, - EventSourceInitializer, TestExecutionInfoProvider { public static final String ID_KEY = "id"; @@ -99,24 +107,31 @@ public int getNumberOfExecutions() { } @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { configMapEventSource = new InformerEventSource<>( - InformerConfiguration.from(ConfigMap.class, context).build(), context); + InformerEventSourceConfiguration.from(ConfigMap.class, ExternalStateCustomResource.class) + .build(), + context); configMapEventSource.setEventSourcePriority(EventSourceStartPriority.RESOURCE_STATE_LOADER); - externalResourceEventSource = new PerResourcePollingEventSource<>(primaryResource -> { - var configMap = configMapEventSource.getSecondaryResource(primaryResource).orElse(null); - if (configMap == null) { - return Collections.emptySet(); - } - var id = configMap.getData().get(ID_KEY); - var externalResource = externalService.read(id); - return externalResource.map(Set::of).orElseGet(Collections::emptySet); - }, context, Duration.ofMillis(300L), ExternalResource.class); - - return EventSourceInitializer.nameEventSources(configMapEventSource, + final PerResourcePollingEventSource.ResourceFetcher fetcher = + (ExternalStateCustomResource primaryResource) -> { + var configMap = + configMapEventSource.getSecondaryResource(primaryResource).orElse(null); + if (configMap == null) { + return Collections.emptySet(); + } + var id = configMap.getData().get(ID_KEY); + var externalResource = externalService.read(id); + return externalResource.map(Set::of).orElseGet(Collections::emptySet); + }; + externalResourceEventSource = + new PerResourcePollingEventSource<>(ExternalResource.class, context, + new PerResourcePollingConfigurationBuilder<>(fetcher, Duration.ofMillis(300L)).build()); + + return Arrays.asList(configMapEventSource, externalResourceEventSource); } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/ExternalStateSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateSpec.java similarity index 76% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/ExternalStateSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateSpec.java index eda0a887eb..d073fcd1f8 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/ExternalStateSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.externalstate; +package io.javaoperatorsdk.operator.dependent.externalstate; public class ExternalStateSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ExternalStateTestBase.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateTestBase.java similarity index 89% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/ExternalStateTestBase.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateTestBase.java index 43982a6109..c58c7cf670 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ExternalStateTestBase.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalStateTestBase.java @@ -1,15 +1,13 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.externalstate; import org.junit.jupiter.api.Test; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.externalstate.ExternalStateCustomResource; -import io.javaoperatorsdk.operator.sample.externalstate.ExternalStateSpec; import io.javaoperatorsdk.operator.support.ExternalIDGenServiceMock; -import static io.javaoperatorsdk.operator.sample.externalstate.ExternalStateReconciler.ID_KEY; +import static io.javaoperatorsdk.operator.dependent.externalstate.ExternalStateReconciler.ID_KEY; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/ExternalWithStateDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalWithStateDependentResource.java similarity index 80% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/ExternalWithStateDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalWithStateDependentResource.java index c25113b406..47d6a25144 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/ExternalWithStateDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/ExternalWithStateDependentResource.java @@ -1,5 +1,6 @@ -package io.javaoperatorsdk.operator.sample.externalstate; +package io.javaoperatorsdk.operator.dependent.externalstate; +import java.time.Duration; import java.util.Collections; import java.util.Map; import java.util.Optional; @@ -16,8 +17,6 @@ import io.javaoperatorsdk.operator.support.ExternalIDGenServiceMock; import io.javaoperatorsdk.operator.support.ExternalResource; -import static io.javaoperatorsdk.operator.sample.externalstate.ExternalStateDependentReconciler.ID_KEY; - public class ExternalWithStateDependentResource extends PerResourcePollingDependentResource implements @@ -27,23 +26,33 @@ public class ExternalWithStateDependentResource extends ExternalIDGenServiceMock externalService = ExternalIDGenServiceMock.getInstance(); public ExternalWithStateDependentResource() { - super(ExternalResource.class, 300); + super(ExternalResource.class, Duration.ofMillis(300)); } @Override @SuppressWarnings("unchecked") public Set fetchResources( ExternalStateCustomResource primaryResource) { - Optional configMapOptional = - getExternalStateEventSource().getSecondaryResource(primaryResource); - - return configMapOptional.map(configMap -> { - var id = configMap.getData().get(ID_KEY); + return getResourceID(primaryResource).map(id -> { var externalResource = externalService.read(id); return externalResource.map(Set::of).orElseGet(Collections::emptySet); }).orElseGet(Collections::emptySet); } + @Override + protected Optional selectTargetSecondaryResource( + Set secondaryResources, + ExternalStateCustomResource primary, Context context) { + var id = getResourceID(primary); + return id.flatMap(k -> secondaryResources.stream().filter(e -> e.getId().equals(k)).findAny()); + } + + private Optional getResourceID(ExternalStateCustomResource primaryResource) { + Optional configMapOptional = + getExternalStateEventSource().getSecondaryResource(primaryResource); + return configMapOptional.map(cm -> cm.getData().get(ExternalStateDependentReconciler.ID_KEY)); + } + @Override protected ExternalResource desired(ExternalStateCustomResource primary, Context context) { @@ -63,7 +72,7 @@ public ConfigMap stateResource(ExternalStateCustomResource primary, .withName(primary.getMetadata().getName()) .withNamespace(primary.getMetadata().getNamespace()) .build()) - .withData(Map.of(ID_KEY, resource.getId())) + .withData(Map.of(ExternalStateDependentReconciler.ID_KEY, resource.getId())) .build(); configMap.addOwnerReference(primary); return configMap; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/externalstatebulkdependent/BulkDependentResourceExternalWithState.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/externalstatebulkdependent/BulkDependentResourceExternalWithState.java similarity index 86% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/externalstatebulkdependent/BulkDependentResourceExternalWithState.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/externalstatebulkdependent/BulkDependentResourceExternalWithState.java index 37684dd39f..df3171fbec 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/externalstatebulkdependent/BulkDependentResourceExternalWithState.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/externalstatebulkdependent/BulkDependentResourceExternalWithState.java @@ -1,5 +1,6 @@ -package io.javaoperatorsdk.operator.sample.externalstate.externalstatebulkdependent; +package io.javaoperatorsdk.operator.dependent.externalstate.externalstatebulkdependent; +import java.time.Duration; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -10,28 +11,24 @@ import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.processing.dependent.BulkDependentResource; -import io.javaoperatorsdk.operator.processing.dependent.BulkUpdater; -import io.javaoperatorsdk.operator.processing.dependent.DependentResourceWithExplicitState; -import io.javaoperatorsdk.operator.processing.dependent.Matcher; +import io.javaoperatorsdk.operator.dependent.externalstate.ExternalStateDependentReconciler; +import io.javaoperatorsdk.operator.processing.dependent.*; import io.javaoperatorsdk.operator.processing.dependent.external.PerResourcePollingDependentResource; import io.javaoperatorsdk.operator.support.ExternalIDGenServiceMock; import io.javaoperatorsdk.operator.support.ExternalResource; -import static io.javaoperatorsdk.operator.sample.externalstate.ExternalStateDependentReconciler.ID_KEY; - public class BulkDependentResourceExternalWithState extends PerResourcePollingDependentResource implements BulkDependentResource, - DependentResourceWithExplicitState, - BulkUpdater { + CRUDBulkDependentResource, + DependentResourceWithExplicitState { public static final String DELIMITER = "-"; ExternalIDGenServiceMock externalService = ExternalIDGenServiceMock.getInstance(); public BulkDependentResourceExternalWithState() { - super(ExternalResource.class, 300); + super(ExternalResource.class, Duration.ofMillis(300)); } @Override @@ -43,7 +40,7 @@ public Set fetchResources( Set res = new HashSet<>(); configMaps.forEach(cm -> { - var id = cm.getData().get(ID_KEY); + var id = cm.getData().get(ExternalStateDependentReconciler.ID_KEY); var externalResource = externalService.read(id); externalResource.ifPresent(res::add); }); @@ -63,7 +60,7 @@ public ConfigMap stateResource(ExternalStateBulkDependentCustomResource primary, .withName(configMapName(primary, resource)) .withNamespace(primary.getMetadata().getNamespace()) .build()) - .withData(Map.of(ID_KEY, resource.getId())) + .withData(Map.of(ExternalStateDependentReconciler.ID_KEY, resource.getId())) .build(); configMap.addOwnerReference(primary); return configMap; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/externalstatebulkdependent/ExternalStateBulkDependentCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/externalstatebulkdependent/ExternalStateBulkDependentCustomResource.java similarity index 84% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/externalstatebulkdependent/ExternalStateBulkDependentCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/externalstatebulkdependent/ExternalStateBulkDependentCustomResource.java index 9ee3e260e8..4e8c07dcc7 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/externalstatebulkdependent/ExternalStateBulkDependentCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/externalstatebulkdependent/ExternalStateBulkDependentCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.externalstate.externalstatebulkdependent; +package io.javaoperatorsdk.operator.dependent.externalstate.externalstatebulkdependent; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/externalstatebulkdependent/ExternalStateBulkDependentReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/externalstatebulkdependent/ExternalStateBulkDependentReconciler.java similarity index 54% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/externalstatebulkdependent/ExternalStateBulkDependentReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/externalstatebulkdependent/ExternalStateBulkDependentReconciler.java index ebc1655c38..2e0f672c79 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/externalstatebulkdependent/ExternalStateBulkDependentReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/externalstatebulkdependent/ExternalStateBulkDependentReconciler.java @@ -1,26 +1,20 @@ -package io.javaoperatorsdk.operator.sample.externalstate.externalstatebulkdependent; +package io.javaoperatorsdk.operator.dependent.externalstate.externalstatebulkdependent; -import java.util.Map; +import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import io.fabric8.kubernetes.api.model.ConfigMap; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; -import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; -import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; -import io.javaoperatorsdk.operator.api.reconciler.EventSourceInitializer; -import io.javaoperatorsdk.operator.api.reconciler.Reconciler; -import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; import io.javaoperatorsdk.operator.processing.event.source.EventSource; import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -@ControllerConfiguration( - dependents = @Dependent(type = BulkDependentResourceExternalWithState.class)) +@Workflow(dependents = @Dependent(type = BulkDependentResourceExternalWithState.class)) +@ControllerConfiguration public class ExternalStateBulkDependentReconciler implements Reconciler, - EventSourceInitializer, TestExecutionInfoProvider { private final AtomicInteger numberOfExecutions = new AtomicInteger(0); @@ -39,11 +33,14 @@ public int getNumberOfExecutions() { } @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { var configMapEventSource = new InformerEventSource<>( - InformerConfiguration.from(ConfigMap.class, context).build(), context); - return EventSourceInitializer.nameEventSources(configMapEventSource); + InformerEventSourceConfiguration + .from(ConfigMap.class, ExternalStateBulkDependentCustomResource.class) + .build(), + context); + return List.of(configMapEventSource); } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ExternalStateBulkIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/externalstatebulkdependent/ExternalStateBulkIT.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/ExternalStateBulkIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/externalstatebulkdependent/ExternalStateBulkIT.java index 7452958b8c..3677537b01 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ExternalStateBulkIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/externalstatebulkdependent/ExternalStateBulkIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.externalstate.externalstatebulkdependent; import java.time.Duration; @@ -7,9 +7,6 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.externalstate.externalstatebulkdependent.ExternalStateBulkDependentCustomResource; -import io.javaoperatorsdk.operator.sample.externalstate.externalstatebulkdependent.ExternalStateBulkDependentReconciler; -import io.javaoperatorsdk.operator.sample.externalstate.externalstatebulkdependent.ExternalStateBulkSpec; import io.javaoperatorsdk.operator.support.ExternalIDGenServiceMock; import static org.assertj.core.api.Assertions.assertThat; @@ -34,7 +31,7 @@ class ExternalStateBulkIT { .build(); @Test - void reconcilesResourceWithPersistentState() throws InterruptedException { + void reconcilesResourceWithPersistentState() { var resource = operator.create(testResource()); assertResources(resource, INITIAL_TEST_DATA, INITIAL_BULK_SIZE); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/externalstatebulkdependent/ExternalStateBulkSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/externalstatebulkdependent/ExternalStateBulkSpec.java similarity index 81% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/externalstatebulkdependent/ExternalStateBulkSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/externalstatebulkdependent/ExternalStateBulkSpec.java index ad52a389fd..a90a4575b5 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/externalstate/externalstatebulkdependent/ExternalStateBulkSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/externalstate/externalstatebulkdependent/ExternalStateBulkSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.externalstate.externalstatebulkdependent; +package io.javaoperatorsdk.operator.dependent.externalstate.externalstatebulkdependent; public class ExternalStateBulkSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/GenericKubernetesDependentSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/GenericKubernetesDependentSpec.java similarity index 76% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/GenericKubernetesDependentSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/GenericKubernetesDependentSpec.java index 050e0cf520..d2b33fe090 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/GenericKubernetesDependentSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/GenericKubernetesDependentSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.generickubernetesresource; +package io.javaoperatorsdk.operator.dependent.generickubernetesresource; public class GenericKubernetesDependentSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/GenericKubernetesDependentTestBase.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/GenericKubernetesDependentTestBase.java similarity index 76% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/GenericKubernetesDependentTestBase.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/GenericKubernetesDependentTestBase.java index fea23b7796..c26fcb42b4 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/GenericKubernetesDependentTestBase.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/GenericKubernetesDependentTestBase.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.generickubernetesresource; import java.time.Duration; @@ -6,10 +6,10 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.client.CustomResource; +import io.javaoperatorsdk.operator.dependent.generickubernetesresource.generickubernetesdependentstandalone.ConfigMapGenericKubernetesDependent; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.generickubernetesresource.GenericKubernetesDependentSpec; -import io.javaoperatorsdk.operator.sample.generickubernetesresource.generickubernetesdependentstandalone.ConfigMapGenericKubernetesDependent; +import static io.javaoperatorsdk.operator.IntegrationTestConstants.GARBAGE_COLLECTION_TIMEOUT_SECONDS; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; @@ -39,7 +39,7 @@ void testReconciliation() { extension().delete(resource); - await().timeout(Duration.ofSeconds(30)).untilAsserted(() -> { + await().timeout(Duration.ofSeconds(GARBAGE_COLLECTION_TIMEOUT_SECONDS)).untilAsserted(() -> { var cm = extension().get(ConfigMap.class, TEST_RESOURCE_NAME); assertThat(cm).isNull(); }); @@ -47,6 +47,6 @@ void testReconciliation() { public abstract LocallyRunOperatorExtension extension(); - abstract R testResource(String name, String data); + public abstract R testResource(String name, String data); } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesdependentresourcemanaged/ConfigMapGenericKubernetesDependent.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentresourcemanaged/ConfigMapGenericKubernetesDependent.java similarity index 89% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesdependentresourcemanaged/ConfigMapGenericKubernetesDependent.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentresourcemanaged/ConfigMapGenericKubernetesDependent.java index d5ab470cfb..54c91f66f1 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesdependentresourcemanaged/ConfigMapGenericKubernetesDependent.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentresourcemanaged/ConfigMapGenericKubernetesDependent.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.generickubernetesresource.generickubernetesdependentresourcemanaged; +package io.javaoperatorsdk.operator.dependent.generickubernetesresource.generickubernetesdependentresourcemanaged; import java.io.IOException; import java.io.InputStream; @@ -11,7 +11,9 @@ import io.javaoperatorsdk.operator.processing.dependent.Creator; import io.javaoperatorsdk.operator.processing.dependent.Updater; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.GenericKubernetesDependentResource; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; +@KubernetesDependent public class ConfigMapGenericKubernetesDependent extends GenericKubernetesDependentResource implements diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesdependentresourcemanaged/GenericKubernetesDependentManagedCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentresourcemanaged/GenericKubernetesDependentManagedCustomResource.java similarity index 69% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesdependentresourcemanaged/GenericKubernetesDependentManagedCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentresourcemanaged/GenericKubernetesDependentManagedCustomResource.java index d7c44ddab3..24c1bbcb08 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesdependentresourcemanaged/GenericKubernetesDependentManagedCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentresourcemanaged/GenericKubernetesDependentManagedCustomResource.java @@ -1,11 +1,11 @@ -package io.javaoperatorsdk.operator.sample.generickubernetesresource.generickubernetesdependentresourcemanaged; +package io.javaoperatorsdk.operator.dependent.generickubernetesresource.generickubernetesdependentresourcemanaged; 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; -import io.javaoperatorsdk.operator.sample.generickubernetesresource.GenericKubernetesDependentSpec; +import io.javaoperatorsdk.operator.dependent.generickubernetesresource.GenericKubernetesDependentSpec; @Group("sample.javaoperatorsdk") @Version("v1") diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/GenericKubernetesDependentManagedIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentresourcemanaged/GenericKubernetesDependentManagedIT.java similarity index 63% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/GenericKubernetesDependentManagedIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentresourcemanaged/GenericKubernetesDependentManagedIT.java index f06185d402..9bcccb9c46 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/GenericKubernetesDependentManagedIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentresourcemanaged/GenericKubernetesDependentManagedIT.java @@ -1,12 +1,11 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.generickubernetesresource.generickubernetesdependentresourcemanaged; import org.junit.jupiter.api.extension.RegisterExtension; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.dependent.generickubernetesresource.GenericKubernetesDependentSpec; +import io.javaoperatorsdk.operator.dependent.generickubernetesresource.GenericKubernetesDependentTestBase; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.generickubernetesresource.GenericKubernetesDependentSpec; -import io.javaoperatorsdk.operator.sample.generickubernetesresource.generickubernetesdependentresourcemanaged.GenericKubernetesDependentManagedCustomResource; -import io.javaoperatorsdk.operator.sample.generickubernetesresource.generickubernetesdependentresourcemanaged.GenericKubernetesDependentManagedReconciler; public class GenericKubernetesDependentManagedIT extends GenericKubernetesDependentTestBase { @@ -23,7 +22,7 @@ public LocallyRunOperatorExtension extension() { } @Override - GenericKubernetesDependentManagedCustomResource testResource(String name, String data) { + public GenericKubernetesDependentManagedCustomResource testResource(String name, String data) { var resource = new GenericKubernetesDependentManagedCustomResource(); resource.setMetadata(new ObjectMetaBuilder() .withName(name) diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentresourcemanaged/GenericKubernetesDependentManagedReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentresourcemanaged/GenericKubernetesDependentManagedReconciler.java new file mode 100644 index 0000000000..d122f8909e --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentresourcemanaged/GenericKubernetesDependentManagedReconciler.java @@ -0,0 +1,23 @@ +package io.javaoperatorsdk.operator.dependent.generickubernetesresource.generickubernetesdependentresourcemanaged; + +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 = ConfigMapGenericKubernetesDependent.class)}) +@ControllerConfiguration +public class GenericKubernetesDependentManagedReconciler + implements Reconciler { + + @Override + public UpdateControl reconcile( + GenericKubernetesDependentManagedCustomResource resource, + Context context) { + + return UpdateControl.noUpdate(); + } + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesdependentstandalone/ConfigMapGenericKubernetesDependent.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentstandalone/ConfigMapGenericKubernetesDependent.java similarity index 94% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesdependentstandalone/ConfigMapGenericKubernetesDependent.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentstandalone/ConfigMapGenericKubernetesDependent.java index 4efc968ef0..79324641f3 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesdependentstandalone/ConfigMapGenericKubernetesDependent.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentstandalone/ConfigMapGenericKubernetesDependent.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.generickubernetesresource.generickubernetesdependentstandalone; +package io.javaoperatorsdk.operator.dependent.generickubernetesresource.generickubernetesdependentstandalone; import java.io.IOException; import java.io.InputStream; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesdependentstandalone/GenericKubernetesDependentStandaloneCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentstandalone/GenericKubernetesDependentStandaloneCustomResource.java similarity index 70% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesdependentstandalone/GenericKubernetesDependentStandaloneCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentstandalone/GenericKubernetesDependentStandaloneCustomResource.java index 38eaf804e4..eaf56831c5 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesdependentstandalone/GenericKubernetesDependentStandaloneCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentstandalone/GenericKubernetesDependentStandaloneCustomResource.java @@ -1,11 +1,11 @@ -package io.javaoperatorsdk.operator.sample.generickubernetesresource.generickubernetesdependentstandalone; +package io.javaoperatorsdk.operator.dependent.generickubernetesresource.generickubernetesdependentstandalone; 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; -import io.javaoperatorsdk.operator.sample.generickubernetesresource.GenericKubernetesDependentSpec; +import io.javaoperatorsdk.operator.dependent.generickubernetesresource.GenericKubernetesDependentSpec; @Group("sample.javaoperatorsdk") @Version("v1") diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/GenericKubernetesDependentStandaloneIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentstandalone/GenericKubernetesDependentStandaloneIT.java similarity index 63% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/GenericKubernetesDependentStandaloneIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentstandalone/GenericKubernetesDependentStandaloneIT.java index 708d2f119c..07c264c6c2 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/GenericKubernetesDependentStandaloneIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentstandalone/GenericKubernetesDependentStandaloneIT.java @@ -1,12 +1,11 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.generickubernetesresource.generickubernetesdependentstandalone; import org.junit.jupiter.api.extension.RegisterExtension; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.dependent.generickubernetesresource.GenericKubernetesDependentSpec; +import io.javaoperatorsdk.operator.dependent.generickubernetesresource.GenericKubernetesDependentTestBase; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.generickubernetesresource.GenericKubernetesDependentSpec; -import io.javaoperatorsdk.operator.sample.generickubernetesresource.generickubernetesdependentstandalone.GenericKubernetesDependentStandaloneCustomResource; -import io.javaoperatorsdk.operator.sample.generickubernetesresource.generickubernetesdependentstandalone.GenericKubernetesDependentStandaloneReconciler; public class GenericKubernetesDependentStandaloneIT extends GenericKubernetesDependentTestBase { @@ -23,7 +22,7 @@ public LocallyRunOperatorExtension extension() { } @Override - GenericKubernetesDependentStandaloneCustomResource testResource(String name, String data) { + public GenericKubernetesDependentStandaloneCustomResource testResource(String name, String data) { var resource = new GenericKubernetesDependentStandaloneCustomResource(); resource.setMetadata(new ObjectMetaBuilder() .withName(name) diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesdependentstandalone/GenericKubernetesDependentStandaloneReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentstandalone/GenericKubernetesDependentStandaloneReconciler.java similarity index 53% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesdependentstandalone/GenericKubernetesDependentStandaloneReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentstandalone/GenericKubernetesDependentStandaloneReconciler.java index 1969ad8f2a..0e90d8e9d9 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesdependentstandalone/GenericKubernetesDependentStandaloneReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/generickubernetesresource/generickubernetesdependentstandalone/GenericKubernetesDependentStandaloneReconciler.java @@ -1,14 +1,17 @@ -package io.javaoperatorsdk.operator.sample.generickubernetesresource.generickubernetesdependentstandalone; +package io.javaoperatorsdk.operator.dependent.generickubernetesresource.generickubernetesdependentstandalone; -import java.util.Map; +import java.util.List; -import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.javaoperatorsdk.operator.processing.event.source.EventSource; @ControllerConfiguration public class GenericKubernetesDependentStandaloneReconciler - implements Reconciler, - EventSourceInitializer { + implements Reconciler { private final ConfigMapGenericKubernetesDependent dependent = new ConfigMapGenericKubernetesDependent(); @@ -22,12 +25,12 @@ public UpdateControl reconci dependent.reconcile(resource, context); - return UpdateControl.noUpdate(); + return UpdateControl.noUpdate(); } @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { - return EventSourceInitializer.nameEventSources(dependent.eventSource(context).orElseThrow()); + return List.of(dependent.eventSource(context).orElseThrow()); } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informerrelatedbehavior/ConfigMapDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/ConfigMapDependentResource.java similarity index 85% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informerrelatedbehavior/ConfigMapDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/ConfigMapDependentResource.java index c9747cbd00..37e109e8de 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informerrelatedbehavior/ConfigMapDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/ConfigMapDependentResource.java @@ -1,15 +1,16 @@ -package io.javaoperatorsdk.operator.sample.informerrelatedbehavior; +package io.javaoperatorsdk.operator.dependent.informerrelatedbehavior; import java.util.Map; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.api.config.informer.Informer; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; -@KubernetesDependent(labelSelector = "app=rbac-test") +@KubernetesDependent(informer = @Informer(labelSelector = "app=rbac-test")) public class ConfigMapDependentResource extends CRUDKubernetesDependentResource { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/InformerRelatedBehaviorITS.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/InformerRelatedBehaviorITS.java similarity index 91% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/InformerRelatedBehaviorITS.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/InformerRelatedBehaviorITS.java index 36e4fd23f6..21079c0504 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/InformerRelatedBehaviorITS.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/InformerRelatedBehaviorITS.java @@ -1,11 +1,10 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.informerrelatedbehavior; import java.time.Duration; import org.junit.jupiter.api.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import io.fabric8.kubeapitest.junit.EnableKubeAPIServer; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.Namespace; @@ -18,16 +17,15 @@ import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.KubernetesClientBuilder; import io.fabric8.kubernetes.client.utils.KubernetesResourceUtil; -import io.javaoperatorsdk.jenvtest.junit.EnableKubeAPIServer; +import io.javaoperatorsdk.operator.Operator; +import io.javaoperatorsdk.operator.OperatorException; +import io.javaoperatorsdk.operator.ReconcilerUtils; import io.javaoperatorsdk.operator.health.InformerHealthIndicator; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.processing.event.source.controller.ControllerResourceEventSource; -import io.javaoperatorsdk.operator.sample.informerrelatedbehavior.ConfigMapDependentResource; -import io.javaoperatorsdk.operator.sample.informerrelatedbehavior.InformerRelatedBehaviorTestCustomResource; -import io.javaoperatorsdk.operator.sample.informerrelatedbehavior.InformerRelatedBehaviorTestReconciler; +import io.javaoperatorsdk.operator.processing.event.source.controller.ControllerEventSource; -import static io.javaoperatorsdk.operator.sample.informerrelatedbehavior.InformerRelatedBehaviorTestReconciler.CONFIG_MAP_DEPENDENT_RESOURCE; -import static io.javaoperatorsdk.operator.sample.informerrelatedbehavior.InformerRelatedBehaviorTestReconciler.INFORMER_RELATED_BEHAVIOR_TEST_RECONCILER; +import static io.javaoperatorsdk.operator.dependent.informerrelatedbehavior.InformerRelatedBehaviorTestReconciler.CONFIG_MAP_DEPENDENT_RESOURCE; +import static io.javaoperatorsdk.operator.dependent.informerrelatedbehavior.InformerRelatedBehaviorTestReconciler.INFORMER_RELATED_BEHAVIOR_TEST_RECONCILER; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -49,8 +47,6 @@ @EnableKubeAPIServer(apiServerFlags = {"--min-request-timeout", "1"}, updateKubeConfigFile = true) class InformerRelatedBehaviorITS { - private static final Logger log = LoggerFactory.getLogger(InformerRelatedBehaviorITS.class); - public static final String TEST_RESOURCE_NAME = "test1"; public static final String ADDITIONAL_NAMESPACE_SUFFIX = "-additional"; @@ -77,7 +73,7 @@ void beforeEach(TestInfo testInfo) { @AfterEach void cleanup() { if (operator != null) { - operator.stop(Duration.ofSeconds(1)); + operator.stop(); } adminClient.resource(dependentConfigMap()).delete(); adminClient.resource(testCustomResource()).delete(); @@ -143,7 +139,7 @@ private void assertInformerNotWatchingForAdditionalNamespace(Operator operator) InformerHealthIndicator controllerHealthIndicator = (InformerHealthIndicator) unhealthyEventSources - .get(ControllerResourceEventSource.class.getSimpleName()) + .get(ControllerEventSource.NAME) .informerHealthIndicators().get(additionalNamespace); assertThat(controllerHealthIndicator).isNotNull(); assertThat(controllerHealthIndicator.getTargetNamespace()).isEqualTo(additionalNamespace); @@ -151,7 +147,7 @@ private void assertInformerNotWatchingForAdditionalNamespace(Operator operator) InformerHealthIndicator configMapHealthIndicator = (InformerHealthIndicator) unhealthyEventSources - .get(ConfigMapDependentResource.class.getSimpleName()) + .get(InformerRelatedBehaviorTestReconciler.CONFIG_MAP_DEPENDENT_RESOURCE) .informerHealthIndicators().get(additionalNamespace); assertThat(configMapHealthIndicator).isNotNull(); assertThat(configMapHealthIndicator.getTargetNamespace()).isEqualTo(additionalNamespace); @@ -270,13 +266,13 @@ private void assertRuntimeInfoNoCRPermission(Operator operator) { operator.getRuntimeInfo().unhealthyEventSources() .get(INFORMER_RELATED_BEHAVIOR_TEST_RECONCILER); assertThat(unhealthyEventSources).isNotEmpty(); - assertThat(unhealthyEventSources.get(ControllerResourceEventSource.class.getSimpleName())) + assertThat(unhealthyEventSources.get(ControllerEventSource.NAME)) .isNotNull(); var informerHealthIndicators = operator.getRuntimeInfo() .unhealthyInformerWrappingEventSourceHealthIndicator() .get(INFORMER_RELATED_BEHAVIOR_TEST_RECONCILER); assertThat(informerHealthIndicators).isNotEmpty(); - assertThat(informerHealthIndicators.get(ControllerResourceEventSource.class.getSimpleName()) + assertThat(informerHealthIndicators.get(ControllerEventSource.NAME) .informerHealthIndicators()) .hasSize(1); } @@ -317,10 +313,12 @@ Operator startOperator(boolean stopOnInformerErrorDuringStartup, boolean addStop reconciler = new InformerRelatedBehaviorTestReconciler(); - Operator operator = new Operator(clientUsingServiceAccount(), + Operator operator = new Operator( co -> { + co.withKubernetesClient(clientUsingServiceAccount()); co.withStopOnInformerErrorDuringStartup(stopOnInformerErrorDuringStartup); co.withCacheSyncTimeout(Duration.ofMillis(3000)); + co.withReconciliationTerminationTimeout(Duration.ofSeconds(1)); if (addStopHandler) { co.withInformerStoppedHandler((informer, ex) -> replacementStopHandlerCalled = true); } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informerrelatedbehavior/InformerRelatedBehaviorTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/InformerRelatedBehaviorTestCustomResource.java similarity index 86% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informerrelatedbehavior/InformerRelatedBehaviorTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/InformerRelatedBehaviorTestCustomResource.java index fa59c15831..9269dc5d6e 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informerrelatedbehavior/InformerRelatedBehaviorTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/InformerRelatedBehaviorTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.informerrelatedbehavior; +package io.javaoperatorsdk.operator.dependent.informerrelatedbehavior; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informerrelatedbehavior/InformerRelatedBehaviorTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/InformerRelatedBehaviorTestReconciler.java similarity index 69% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informerrelatedbehavior/InformerRelatedBehaviorTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/InformerRelatedBehaviorTestReconciler.java index f71f243c79..2fb7724f49 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informerrelatedbehavior/InformerRelatedBehaviorTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/InformerRelatedBehaviorTestReconciler.java @@ -1,24 +1,20 @@ -package io.javaoperatorsdk.operator.sample.informerrelatedbehavior; +package io.javaoperatorsdk.operator.dependent.informerrelatedbehavior; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.fabric8.kubernetes.client.KubernetesClient; -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.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; import io.javaoperatorsdk.operator.processing.event.ResourceID; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; +@Workflow(dependents = @Dependent( + name = InformerRelatedBehaviorTestReconciler.CONFIG_MAP_DEPENDENT_RESOURCE, + type = ConfigMapDependentResource.class)) @ControllerConfiguration( - name = InformerRelatedBehaviorTestReconciler.INFORMER_RELATED_BEHAVIOR_TEST_RECONCILER, - dependents = @Dependent( - name = InformerRelatedBehaviorTestReconciler.CONFIG_MAP_DEPENDENT_RESOURCE, - type = ConfigMapDependentResource.class)) + name = InformerRelatedBehaviorTestReconciler.INFORMER_RELATED_BEHAVIOR_TEST_RECONCILER) public class InformerRelatedBehaviorTestReconciler implements Reconciler, TestExecutionInfoProvider { @@ -30,7 +26,6 @@ public class InformerRelatedBehaviorTestReconciler public static final String CONFIG_MAP_DEPENDENT_RESOURCE = "ConfigMapDependentResource"; private final AtomicInteger numberOfExecutions = new AtomicInteger(0); - private KubernetesClient client; @Override public UpdateControl reconcile( diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestCustomResource.java similarity index 78% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestCustomResource.java index 5f1e5a0435..33f9899689 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.kubernetesdependentgarbagecollection; +package io.javaoperatorsdk.operator.dependent.kubernetesdependentgarbagecollection; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; @@ -11,6 +11,6 @@ @ShortNames("dgc") public class DependentGarbageCollectionTestCustomResource extends - CustomResource + CustomResource implements Namespaced { } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestCustomResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestCustomResourceSpec.java similarity index 80% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestCustomResourceSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestCustomResourceSpec.java index 9c29ebbacc..0571bbf97d 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestCustomResourceSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestCustomResourceSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.kubernetesdependentgarbagecollection; +package io.javaoperatorsdk.operator.dependent.kubernetesdependentgarbagecollection; public class DependentGarbageCollectionTestCustomResourceSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestReconciler.java similarity index 88% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestReconciler.java index fcb2192539..e786c1c2c1 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestReconciler.java @@ -1,5 +1,6 @@ -package io.javaoperatorsdk.operator.sample.kubernetesdependentgarbagecollection; +package io.javaoperatorsdk.operator.dependent.kubernetesdependentgarbagecollection; +import java.util.List; import java.util.Map; import io.fabric8.kubernetes.api.model.ConfigMap; @@ -15,9 +16,7 @@ @ControllerConfiguration public class DependentGarbageCollectionTestReconciler - implements Reconciler, - EventSourceInitializer, - ErrorStatusHandler { + implements Reconciler { private KubernetesClient kubernetesClient; private volatile boolean errorOccurred = false; @@ -29,10 +28,9 @@ public DependentGarbageCollectionTestReconciler() { } @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { - return EventSourceInitializer.nameEventSourcesFromDependentResource(context, - configMapDependent); + return EventSourceUtils.dependentEventSources(context, configMapDependent); } @Override diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/KubernetesDependentGarbageCollectionIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/kubernetesdependentgarbagecollection/KubernetesDependentGarbageCollectionIT.java similarity index 86% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/KubernetesDependentGarbageCollectionIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/kubernetesdependentgarbagecollection/KubernetesDependentGarbageCollectionIT.java index c32f328d76..afc89471a6 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/KubernetesDependentGarbageCollectionIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/kubernetesdependentgarbagecollection/KubernetesDependentGarbageCollectionIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.kubernetesdependentgarbagecollection; import java.time.Duration; @@ -7,10 +7,8 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.IntegrationTestConstants; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.kubernetesdependentgarbagecollection.DependentGarbageCollectionTestCustomResource; -import io.javaoperatorsdk.operator.sample.kubernetesdependentgarbagecollection.DependentGarbageCollectionTestCustomResourceSpec; -import io.javaoperatorsdk.operator.sample.kubernetesdependentgarbagecollection.DependentGarbageCollectionTestReconciler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresource/MultipleDependentResourceConfigMap.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresource/MultipleDependentResourceConfigMap.java new file mode 100644 index 0000000000..d0bc50ddd8 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresource/MultipleDependentResourceConfigMap.java @@ -0,0 +1,37 @@ +package io.javaoperatorsdk.operator.dependent.multipledependentresource; + +import java.util.Map; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; + +public class MultipleDependentResourceConfigMap + extends CRUDKubernetesDependentResource { + + public static final String DATA_KEY = "key"; + private final String value; + + public MultipleDependentResourceConfigMap(String value) { + super(ConfigMap.class); + this.value = value; + } + + @Override + protected ConfigMap desired(MultipleDependentResourceCustomResource primary, + Context context) { + + return new ConfigMapBuilder() + .withNewMetadata() + .withName(getConfigMapName(value)) + .withNamespace(primary.getMetadata().getNamespace()) + .endMetadata() + .withData(Map.of(DATA_KEY, primary.getSpec().getValue())) + .build(); + } + + public static String getConfigMapName(String id) { + return "configmap" + id; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresource/MultipleDependentResourceCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresource/MultipleDependentResourceCustomResource.java new file mode 100644 index 0000000000..7b8fb15466 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresource/MultipleDependentResourceCustomResource.java @@ -0,0 +1,15 @@ +package io.javaoperatorsdk.operator.dependent.multipledependentresource; + +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("sample.javaoperatorsdk") +@Version("v1") +@ShortNames("mdr") +public class MultipleDependentResourceCustomResource + extends CustomResource + implements Namespaced { +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresource/MultipleDependentResourceIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresource/MultipleDependentResourceIT.java new file mode 100644 index 0000000000..f8b9259b6a --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresource/MultipleDependentResourceIT.java @@ -0,0 +1,76 @@ +package io.javaoperatorsdk.operator.dependent.multipledependentresource; + +import java.time.Duration; + +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.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static io.javaoperatorsdk.operator.dependent.multipledependentresource.MultipleDependentResourceConfigMap.DATA_KEY; +import static io.javaoperatorsdk.operator.dependent.multipledependentresource.MultipleDependentResourceConfigMap.getConfigMapName; +import static io.javaoperatorsdk.operator.dependent.multipledependentresource.MultipleDependentResourceReconciler.FIRST_CONFIG_MAP_ID; +import static io.javaoperatorsdk.operator.dependent.multipledependentresource.MultipleDependentResourceReconciler.SECOND_CONFIG_MAP_ID; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public class MultipleDependentResourceIT { + + public static final String CHANGED_VALUE = "changed value"; + public static final String INITIAL_VALUE = "initial value"; + + @RegisterExtension + LocallyRunOperatorExtension extension = + LocallyRunOperatorExtension.builder() + .withReconciler(new MultipleDependentResourceReconciler()) + .build(); + + @Test + void handlesCRUDOperations() { + var res = extension.create(testResource()); + + await().untilAsserted(() -> { + var cm1 = extension.get(ConfigMap.class, getConfigMapName(FIRST_CONFIG_MAP_ID)); + var cm2 = extension.get(ConfigMap.class, getConfigMapName(SECOND_CONFIG_MAP_ID)); + + assertThat(cm1).isNotNull(); + assertThat(cm2).isNotNull(); + assertThat(cm1.getData()).containsEntry(DATA_KEY, INITIAL_VALUE); + assertThat(cm2.getData()).containsEntry(DATA_KEY, INITIAL_VALUE); + }); + + res.getSpec().setValue(CHANGED_VALUE); + res = extension.replace(res); + + await().untilAsserted(() -> { + var cm1 = extension.get(ConfigMap.class, getConfigMapName(FIRST_CONFIG_MAP_ID)); + var cm2 = extension.get(ConfigMap.class, getConfigMapName(SECOND_CONFIG_MAP_ID)); + + assertThat(cm1.getData()).containsEntry(DATA_KEY, CHANGED_VALUE); + assertThat(cm2.getData()).containsEntry(DATA_KEY, CHANGED_VALUE); + }); + + extension.delete(res); + + await().timeout(Duration.ofSeconds(120)).untilAsserted(() -> { + var cm1 = extension.get(ConfigMap.class, getConfigMapName(FIRST_CONFIG_MAP_ID)); + var cm2 = extension.get(ConfigMap.class, getConfigMapName(SECOND_CONFIG_MAP_ID)); + + assertThat(cm1).isNull(); + assertThat(cm2).isNull(); + }); + } + + MultipleDependentResourceCustomResource testResource() { + var res = new MultipleDependentResourceCustomResource(); + res.setMetadata(new ObjectMetaBuilder() + .withName("test1") + .build()); + res.setSpec(new MultipleDependentResourceSpec()); + res.getSpec().setValue(INITIAL_VALUE); + + return res; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresource/MultipleDependentResourceReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresource/MultipleDependentResourceReconciler.java new file mode 100644 index 0000000000..aeac786cda --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresource/MultipleDependentResourceReconciler.java @@ -0,0 +1,47 @@ +package io.javaoperatorsdk.operator.dependent.multipledependentresource; + +import java.util.List; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.processing.event.source.EventSource; +import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; + +@ControllerConfiguration +public class MultipleDependentResourceReconciler + implements Reconciler { + + public static final String FIRST_CONFIG_MAP_ID = "1"; + public static final String SECOND_CONFIG_MAP_ID = "2"; + + private final MultipleDependentResourceConfigMap firstDependentResourceConfigMap; + private final MultipleDependentResourceConfigMap secondDependentResourceConfigMap; + + public MultipleDependentResourceReconciler() { + firstDependentResourceConfigMap = new MultipleDependentResourceConfigMap(FIRST_CONFIG_MAP_ID); + secondDependentResourceConfigMap = new MultipleDependentResourceConfigMap(SECOND_CONFIG_MAP_ID); + } + + @Override + public UpdateControl reconcile( + MultipleDependentResourceCustomResource resource, + Context context) { + firstDependentResourceConfigMap.reconcile(resource, context); + secondDependentResourceConfigMap.reconcile(resource, context); + return UpdateControl.noUpdate(); + } + + @Override + public List> prepareEventSources( + EventSourceContext context) { + InformerEventSource eventSource = + new InformerEventSource<>(InformerEventSourceConfiguration + .from(ConfigMap.class, MultipleDependentResourceCustomResource.class) + .build(), context); + firstDependentResourceConfigMap.setEventSource(eventSource); + secondDependentResourceConfigMap.setEventSource(eventSource); + + return List.of(eventSource); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresource/MultipleDependentResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresource/MultipleDependentResourceSpec.java new file mode 100644 index 0000000000..96f7224d31 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresource/MultipleDependentResourceSpec.java @@ -0,0 +1,14 @@ +package io.javaoperatorsdk.operator.dependent.multipledependentresource; + +public class MultipleDependentResourceSpec { + + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentresource/MultipleDependentResourceConfigMap.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresourcewithsametype/MultipleDependentResourceConfigMap.java similarity index 75% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentresource/MultipleDependentResourceConfigMap.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresourcewithsametype/MultipleDependentResourceConfigMap.java index 5c2e9974b5..defef91b75 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentresource/MultipleDependentResourceConfigMap.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresourcewithsametype/MultipleDependentResourceConfigMap.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multipledependentresource; +package io.javaoperatorsdk.operator.dependent.multipledependentresourcewithsametype; import java.util.HashMap; import java.util.Map; @@ -9,7 +9,8 @@ import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; public class MultipleDependentResourceConfigMap - extends CRUDKubernetesDependentResource { + extends + CRUDKubernetesDependentResource { public static final String DATA_KEY = "key"; private final int value; @@ -20,8 +21,8 @@ public MultipleDependentResourceConfigMap(int value) { } @Override - protected ConfigMap desired(MultipleDependentResourceCustomResource primary, - Context context) { + protected ConfigMap desired(MultipleDependentResourceCustomResourceNoDiscriminator primary, + Context context) { Map data = new HashMap<>(); data.put(DATA_KEY, String.valueOf(value)); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentresource/MultipleDependentResourceCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresourcewithsametype/MultipleDependentResourceCustomResourceNoDiscriminator.java similarity index 57% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentresource/MultipleDependentResourceCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresourcewithsametype/MultipleDependentResourceCustomResourceNoDiscriminator.java index 55f0d60f2d..bd91aae234 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentresource/MultipleDependentResourceCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresourcewithsametype/MultipleDependentResourceCustomResourceNoDiscriminator.java @@ -1,18 +1,16 @@ -package io.javaoperatorsdk.operator.sample.multipledependentresource; +package io.javaoperatorsdk.operator.dependent.multipledependentresourcewithsametype; 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.Kind; import io.fabric8.kubernetes.model.annotation.ShortNames; import io.fabric8.kubernetes.model.annotation.Version; @Group("sample.javaoperatorsdk") @Version("v1") -@Kind("MultipleDependentResourceCustomResource") -@ShortNames("mdr") -public class MultipleDependentResourceCustomResource - extends CustomResource +@ShortNames("mdwd") +public class MultipleDependentResourceCustomResourceNoDiscriminator + extends CustomResource implements Namespaced { public String getConfigMapName(int id) { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentresource/MultipleDependentResourceReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresourcewithsametype/MultipleDependentResourceWithDiscriminatorReconciler.java similarity index 50% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentresource/MultipleDependentResourceReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresourcewithsametype/MultipleDependentResourceWithDiscriminatorReconciler.java index 2dc7f6490f..c96033d9bc 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentresource/MultipleDependentResourceReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresourcewithsametype/MultipleDependentResourceWithDiscriminatorReconciler.java @@ -1,20 +1,19 @@ -package io.javaoperatorsdk.operator.sample.multipledependentresource; +package io.javaoperatorsdk.operator.dependent.multipledependentresourcewithsametype; -import java.util.Map; +import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import io.fabric8.kubernetes.api.model.ConfigMap; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; import io.javaoperatorsdk.operator.api.reconciler.*; -import io.javaoperatorsdk.operator.processing.event.ResourceID; import io.javaoperatorsdk.operator.processing.event.source.EventSource; import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; @ControllerConfiguration -public class MultipleDependentResourceReconciler - implements Reconciler, - TestExecutionInfoProvider, EventSourceInitializer { +public class MultipleDependentResourceWithDiscriminatorReconciler + implements Reconciler, + TestExecutionInfoProvider { public static final int FIRST_CONFIG_MAP_ID = 1; public static final int SECOND_CONFIG_MAP_ID = 2; @@ -23,27 +22,15 @@ public class MultipleDependentResourceReconciler private final MultipleDependentResourceConfigMap firstDependentResourceConfigMap; private final MultipleDependentResourceConfigMap secondDependentResourceConfigMap; - public MultipleDependentResourceReconciler() { + public MultipleDependentResourceWithDiscriminatorReconciler() { firstDependentResourceConfigMap = new MultipleDependentResourceConfigMap(FIRST_CONFIG_MAP_ID); - secondDependentResourceConfigMap = new MultipleDependentResourceConfigMap(SECOND_CONFIG_MAP_ID); - - firstDependentResourceConfigMap - .setResourceDiscriminator( - new ResourceIDMatcherDiscriminator<>( - p -> new ResourceID(p.getConfigMapName(FIRST_CONFIG_MAP_ID), - p.getMetadata().getNamespace()))); - secondDependentResourceConfigMap - .setResourceDiscriminator( - new ResourceIDMatcherDiscriminator<>( - p -> new ResourceID(p.getConfigMapName(SECOND_CONFIG_MAP_ID), - p.getMetadata().getNamespace()))); } @Override - public UpdateControl reconcile( - MultipleDependentResourceCustomResource resource, - Context context) { + public UpdateControl reconcile( + MultipleDependentResourceCustomResourceNoDiscriminator resource, + Context context) { numberOfExecutions.getAndIncrement(); firstDependentResourceConfigMap.reconcile(resource, context); secondDependentResourceConfigMap.reconcile(resource, context); @@ -56,14 +43,15 @@ public int getNumberOfExecutions() { } @Override - public Map prepareEventSources( - EventSourceContext context) { - InformerEventSource eventSource = - new InformerEventSource<>(InformerConfiguration.from(ConfigMap.class, context) + public List> prepareEventSources( + EventSourceContext context) { + InformerEventSource eventSource = + new InformerEventSource<>(InformerEventSourceConfiguration.from(ConfigMap.class, + MultipleDependentResourceCustomResourceNoDiscriminator.class) .build(), context); - firstDependentResourceConfigMap.configureWith(eventSource); - secondDependentResourceConfigMap.configureWith(eventSource); + firstDependentResourceConfigMap.setEventSource(eventSource); + secondDependentResourceConfigMap.setEventSource(eventSource); - return EventSourceInitializer.nameEventSources(eventSource); + return List.of(eventSource); } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleDependentResourceIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresourcewithsametype/MultipleDependentResourceWithNoDiscriminatorIT.java similarity index 61% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleDependentResourceIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresourcewithsametype/MultipleDependentResourceWithNoDiscriminatorIT.java index d3e7f77fd5..b653a8b606 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleDependentResourceIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentresourcewithsametype/MultipleDependentResourceWithNoDiscriminatorIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.multipledependentresourcewithsametype; import java.time.Duration; import java.util.stream.IntStream; @@ -9,35 +9,35 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.multipledependentresource.MultipleDependentResourceConfigMap; -import io.javaoperatorsdk.operator.sample.multipledependentresource.MultipleDependentResourceCustomResource; -import io.javaoperatorsdk.operator.sample.multipledependentresource.MultipleDependentResourceReconciler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; -class MultipleDependentResourceIT { +class MultipleDependentResourceWithNoDiscriminatorIT { public static final String TEST_RESOURCE_NAME = "multipledependentresource-testresource"; @RegisterExtension LocallyRunOperatorExtension operator = LocallyRunOperatorExtension.builder() - .withReconciler(MultipleDependentResourceReconciler.class) + .withReconciler(MultipleDependentResourceWithDiscriminatorReconciler.class) .waitForNamespaceDeletion(true) .build(); @Test void twoConfigMapsHaveBeenCreated() { - MultipleDependentResourceCustomResource customResource = createTestCustomResource(); + MultipleDependentResourceCustomResourceNoDiscriminator customResource = + createTestCustomResource(); operator.create(customResource); - var reconciler = operator.getReconcilerOfType(MultipleDependentResourceReconciler.class); + var reconciler = + operator.getReconcilerOfType(MultipleDependentResourceWithDiscriminatorReconciler.class); await().pollDelay(Duration.ofMillis(300)) .until(() -> reconciler.getNumberOfExecutions() <= 1); - IntStream.of(MultipleDependentResourceReconciler.FIRST_CONFIG_MAP_ID, - MultipleDependentResourceReconciler.SECOND_CONFIG_MAP_ID).forEach(configMapId -> { + IntStream.of(MultipleDependentResourceWithDiscriminatorReconciler.FIRST_CONFIG_MAP_ID, + MultipleDependentResourceWithDiscriminatorReconciler.SECOND_CONFIG_MAP_ID) + .forEach(configMapId -> { ConfigMap configMap = operator.get(ConfigMap.class, customResource.getConfigMapName(configMapId)); assertThat(configMap).isNotNull(); @@ -48,9 +48,9 @@ void twoConfigMapsHaveBeenCreated() { }); } - public MultipleDependentResourceCustomResource createTestCustomResource() { - MultipleDependentResourceCustomResource resource = - new MultipleDependentResourceCustomResource(); + public MultipleDependentResourceCustomResourceNoDiscriminator createTestCustomResource() { + MultipleDependentResourceCustomResourceNoDiscriminator resource = + new MultipleDependentResourceCustomResourceNoDiscriminator(); resource.setMetadata( new ObjectMetaBuilder() .withName(TEST_RESOURCE_NAME) diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleDependentSameTypeMultiInformerIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentsametypemultiinformer/MultipleDependentSameTypeMultiInformerIT.java similarity index 81% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleDependentSameTypeMultiInformerIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentsametypemultiinformer/MultipleDependentSameTypeMultiInformerIT.java index 53d29f4552..6f244f554c 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleDependentSameTypeMultiInformerIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentsametypemultiinformer/MultipleDependentSameTypeMultiInformerIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.multipledependentsametypemultiinformer; import java.time.Duration; import java.util.stream.Collectors; @@ -8,12 +8,9 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.multipledependentsametypemultiinformer.MultipleManagedDependentResourceMultiInformerCustomResource; -import io.javaoperatorsdk.operator.sample.multipledependentsametypemultiinformer.MultipleManagedDependentResourceMultiInformerReconciler; -import io.javaoperatorsdk.operator.sample.multipledependentsametypemultiinformer.MultipleManagedDependentResourceMultiInformerSpec; import static io.javaoperatorsdk.operator.IntegrationTestConstants.GARBAGE_COLLECTION_TIMEOUT_SECONDS; -import static io.javaoperatorsdk.operator.sample.multipledependentsametypemultiinformer.MultipleManagedDependentResourceMultiInformerReconciler.DATA_KEY; +import static io.javaoperatorsdk.operator.dependent.multipledependentsametypemultiinformer.MultipleManagedDependentResourceMultiInformerReconciler.DATA_KEY; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerConfigMap1.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerConfigMap1.java similarity index 82% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerConfigMap1.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerConfigMap1.java index 2a63b7267e..47c65f1a95 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerConfigMap1.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerConfigMap1.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multipledependentsametypemultiinformer; +package io.javaoperatorsdk.operator.dependent.multipledependentsametypemultiinformer; import java.util.HashMap; import java.util.Map; @@ -6,11 +6,11 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.dependent.multiplemanageddependentsametype.MultipleManagedDependentResourceReconciler; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; -import io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype.MultipleManagedDependentResourceReconciler; -@KubernetesDependent(resourceDiscriminator = ConfigMap1MultiInformerDiscriminator.class) +@KubernetesDependent public class MultipleManagedDependentResourceMultiInformerConfigMap1 extends CRUDKubernetesDependentResource { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerConfigMap2.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerConfigMap2.java similarity index 80% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerConfigMap2.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerConfigMap2.java index 8db20cac14..320768de24 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerConfigMap2.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerConfigMap2.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multipledependentsametypemultiinformer; +package io.javaoperatorsdk.operator.dependent.multipledependentsametypemultiinformer; import java.util.HashMap; import java.util.Map; @@ -9,9 +9,9 @@ import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; -import static io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype.MultipleManagedDependentResourceReconciler.DATA_KEY; +import static io.javaoperatorsdk.operator.dependent.multiplemanageddependentsametype.MultipleManagedDependentResourceReconciler.DATA_KEY; -@KubernetesDependent(resourceDiscriminator = ConfigMap2MultiInformerDiscriminator.class) +@KubernetesDependent public class MultipleManagedDependentResourceMultiInformerConfigMap2 extends CRUDKubernetesDependentResource { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerCustomResource.java similarity index 85% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerCustomResource.java index 24ee0ea0dc..060a8f6b62 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multipledependentsametypemultiinformer; +package io.javaoperatorsdk.operator.dependent.multipledependentsametypemultiinformer; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerReconciler.java similarity index 88% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerReconciler.java index 81c2308eb5..f0fe034c97 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multipledependentsametypemultiinformer; +package io.javaoperatorsdk.operator.dependent.multipledependentsametypemultiinformer; import java.util.concurrent.atomic.AtomicInteger; @@ -6,17 +6,17 @@ import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -@ControllerConfiguration(dependents = { +@Workflow(dependents = { @Dependent(name = MultipleManagedDependentResourceMultiInformerReconciler.CONFIG_MAP_1_DR, type = MultipleManagedDependentResourceMultiInformerConfigMap1.class), @Dependent(name = MultipleManagedDependentResourceMultiInformerReconciler.CONFIG_MAP_2_DR, type = MultipleManagedDependentResourceMultiInformerConfigMap2.class) }) +@ControllerConfiguration public class MultipleManagedDependentResourceMultiInformerReconciler implements Reconciler, TestExecutionInfoProvider { - public static final String CONFIG_MAP_EVENT_SOURCE = "ConfigMapEventSource"; public static final String DATA_KEY = "key"; public static final String CONFIG_MAP_1_DR = "ConfigMap1"; public static final String CONFIG_MAP_2_DR = "ConfigMap2"; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerSpec.java similarity index 76% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerSpec.java index a98a3c0f92..c8893adc72 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledependentsametypemultiinformer/MultipleManagedDependentResourceMultiInformerSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multipledependentsametypemultiinformer; +package io.javaoperatorsdk.operator.dependent.multipledependentsametypemultiinformer; public class MultipleManagedDependentResourceMultiInformerSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledrsametypenodiscriminator/MultipleManagedDependentNoDiscriminatorConfigMap1.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledrsametypenodiscriminator/MultipleManagedDependentNoDiscriminatorConfigMap1.java new file mode 100644 index 0000000000..6b83593173 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledrsametypenodiscriminator/MultipleManagedDependentNoDiscriminatorConfigMap1.java @@ -0,0 +1,52 @@ +package io.javaoperatorsdk.operator.dependent.multipledrsametypenodiscriminator; + +import java.util.HashMap; +import java.util.Map; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; +import io.javaoperatorsdk.operator.processing.event.ResourceID; + +@KubernetesDependent +public class MultipleManagedDependentNoDiscriminatorConfigMap1 + extends + CRUDKubernetesDependentResource { + + public static final String NAME_SUFFIX = "-1"; + + public MultipleManagedDependentNoDiscriminatorConfigMap1() { + super(ConfigMap.class); + } + + /* + * Showcases optimization to avoid computing the whole desired state by providing the ResourceID + * of the target resource. In this particular case this would not be necessary, since desired + * state creation is pretty lightweight. However, this might make sense in situation where the + * desired state is more costly + */ + protected ResourceID targetSecondaryResourceID( + MultipleManagedDependentNoDiscriminatorCustomResource primary, + Context context) { + return new ResourceID(primary.getMetadata().getName() + NAME_SUFFIX, + primary.getMetadata().getNamespace()); + } + + @Override + protected ConfigMap desired(MultipleManagedDependentNoDiscriminatorCustomResource primary, + Context context) { + Map data = new HashMap<>(); + data.put(MultipleManagedDependentSameTypeNoDiscriminatorReconciler.DATA_KEY, + primary.getSpec().getValue()); + + return new ConfigMapBuilder() + .withNewMetadata() + .withName(primary.getMetadata().getName() + NAME_SUFFIX) + .withNamespace(primary.getMetadata().getNamespace()) + .endMetadata() + .withData(data) + .build(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledrsametypenodiscriminator/MultipleManagedDependentNoDiscriminatorConfigMap2.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledrsametypenodiscriminator/MultipleManagedDependentNoDiscriminatorConfigMap2.java new file mode 100644 index 0000000000..373a70bcda --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledrsametypenodiscriminator/MultipleManagedDependentNoDiscriminatorConfigMap2.java @@ -0,0 +1,39 @@ +package io.javaoperatorsdk.operator.dependent.multipledrsametypenodiscriminator; + +import java.util.HashMap; +import java.util.Map; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; + +import static io.javaoperatorsdk.operator.dependent.multiplemanageddependentsametype.MultipleManagedDependentResourceReconciler.DATA_KEY; + +@KubernetesDependent +public class MultipleManagedDependentNoDiscriminatorConfigMap2 + extends + CRUDKubernetesDependentResource { + + public static final String NAME_SUFFIX = "-2"; + + public MultipleManagedDependentNoDiscriminatorConfigMap2() { + super(ConfigMap.class); + } + + @Override + protected ConfigMap desired(MultipleManagedDependentNoDiscriminatorCustomResource primary, + Context context) { + Map data = new HashMap<>(); + data.put(DATA_KEY, primary.getSpec().getValue()); + + return new ConfigMapBuilder() + .withNewMetadata() + .withName(primary.getMetadata().getName() + NAME_SUFFIX) + .withNamespace(primary.getMetadata().getNamespace()) + .endMetadata() + .withData(data) + .build(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledrsametypenodiscriminator/MultipleManagedDependentNoDiscriminatorCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledrsametypenodiscriminator/MultipleManagedDependentNoDiscriminatorCustomResource.java new file mode 100644 index 0000000000..7681cf7792 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledrsametypenodiscriminator/MultipleManagedDependentNoDiscriminatorCustomResource.java @@ -0,0 +1,16 @@ +package io.javaoperatorsdk.operator.dependent.multipledrsametypenodiscriminator; + +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("sample.javaoperatorsdk") +@Version("v1") +@ShortNames("mnd") +public class MultipleManagedDependentNoDiscriminatorCustomResource + extends CustomResource + implements Namespaced { + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledrsametypenodiscriminator/MultipleManagedDependentNoDiscriminatorIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledrsametypenodiscriminator/MultipleManagedDependentNoDiscriminatorIT.java new file mode 100644 index 0000000000..cc6b79066a --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledrsametypenodiscriminator/MultipleManagedDependentNoDiscriminatorIT.java @@ -0,0 +1,80 @@ +package io.javaoperatorsdk.operator.dependent.multipledrsametypenodiscriminator; + +import java.time.Duration; + +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.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static io.javaoperatorsdk.operator.dependent.multipledrsametypenodiscriminator.MultipleManagedDependentSameTypeNoDiscriminatorReconciler.DATA_KEY; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public class MultipleManagedDependentNoDiscriminatorIT { + + public static final String RESOURCE_NAME = "test1"; + public static final String INITIAL_VALUE = "initial_value"; + public static final String CHANGED_VALUE = "changed_value"; + + @RegisterExtension + LocallyRunOperatorExtension extension = + LocallyRunOperatorExtension.builder() + .withReconciler(new MultipleManagedDependentSameTypeNoDiscriminatorReconciler()) + .build(); + + @Test + void handlesCRUDOperations() { + var res = extension.create(testResource()); + + await().untilAsserted(() -> { + var cm1 = extension.get(ConfigMap.class, + RESOURCE_NAME + MultipleManagedDependentNoDiscriminatorConfigMap1.NAME_SUFFIX); + var cm2 = extension.get(ConfigMap.class, + RESOURCE_NAME + MultipleManagedDependentNoDiscriminatorConfigMap2.NAME_SUFFIX); + + assertThat(cm1).isNotNull(); + assertThat(cm2).isNotNull(); + assertThat(cm1.getData()).containsEntry(DATA_KEY, INITIAL_VALUE); + assertThat(cm2.getData()).containsEntry(DATA_KEY, INITIAL_VALUE); + }); + + res.getSpec().setValue(CHANGED_VALUE); + res = extension.replace(res); + + await().untilAsserted(() -> { + var cm1 = extension.get(ConfigMap.class, + RESOURCE_NAME + MultipleManagedDependentNoDiscriminatorConfigMap1.NAME_SUFFIX); + var cm2 = extension.get(ConfigMap.class, + RESOURCE_NAME + MultipleManagedDependentNoDiscriminatorConfigMap2.NAME_SUFFIX); + + assertThat(cm1.getData()).containsEntry(DATA_KEY, CHANGED_VALUE); + assertThat(cm2.getData()).containsEntry(DATA_KEY, CHANGED_VALUE); + }); + + extension.delete(res); + + await().timeout(Duration.ofSeconds(60)).untilAsserted(() -> { + var cm1 = extension.get(ConfigMap.class, + RESOURCE_NAME + MultipleManagedDependentNoDiscriminatorConfigMap1.NAME_SUFFIX); + var cm2 = extension.get(ConfigMap.class, + RESOURCE_NAME + MultipleManagedDependentNoDiscriminatorConfigMap2.NAME_SUFFIX); + + assertThat(cm1).isNull(); + assertThat(cm2).isNull(); + }); + } + + MultipleManagedDependentNoDiscriminatorCustomResource testResource() { + var res = new MultipleManagedDependentNoDiscriminatorCustomResource(); + res.setMetadata(new ObjectMetaBuilder() + .withName(RESOURCE_NAME) + .build()); + res.setSpec(new MultipleManagedDependentNoDiscriminatorSpec()); + res.getSpec().setValue(INITIAL_VALUE); + return res; + } + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledrsametypenodiscriminator/MultipleManagedDependentNoDiscriminatorSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledrsametypenodiscriminator/MultipleManagedDependentNoDiscriminatorSpec.java new file mode 100644 index 0000000000..5ee30673d4 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledrsametypenodiscriminator/MultipleManagedDependentNoDiscriminatorSpec.java @@ -0,0 +1,15 @@ +package io.javaoperatorsdk.operator.dependent.multipledrsametypenodiscriminator; + +public class MultipleManagedDependentNoDiscriminatorSpec { + + private String value; + + public String getValue() { + return value; + } + + public MultipleManagedDependentNoDiscriminatorSpec setValue(String value) { + this.value = value; + return this; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledrsametypenodiscriminator/MultipleManagedDependentSameTypeNoDiscriminatorReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledrsametypenodiscriminator/MultipleManagedDependentSameTypeNoDiscriminatorReconciler.java new file mode 100644 index 0000000000..09c0b5cc23 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipledrsametypenodiscriminator/MultipleManagedDependentSameTypeNoDiscriminatorReconciler.java @@ -0,0 +1,61 @@ +package io.javaoperatorsdk.operator.dependent.multipledrsametypenodiscriminator; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; +import io.javaoperatorsdk.operator.processing.event.source.EventSource; +import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; +import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; + +import static io.javaoperatorsdk.operator.dependent.multiplemanageddependentsametype.MultipleManagedDependentResourceReconciler.CONFIG_MAP_EVENT_SOURCE; + +@Workflow(dependents = { + @Dependent(type = MultipleManagedDependentNoDiscriminatorConfigMap1.class, + useEventSourceWithName = CONFIG_MAP_EVENT_SOURCE), + @Dependent(type = MultipleManagedDependentNoDiscriminatorConfigMap2.class, + useEventSourceWithName = CONFIG_MAP_EVENT_SOURCE) +}) +@ControllerConfiguration +public class MultipleManagedDependentSameTypeNoDiscriminatorReconciler + implements Reconciler, + TestExecutionInfoProvider { + + public static final String CONFIG_MAP_EVENT_SOURCE = "ConfigMapEventSource"; + public static final String DATA_KEY = "key"; + + private final AtomicInteger numberOfExecutions = new AtomicInteger(0); + + public MultipleManagedDependentSameTypeNoDiscriminatorReconciler() {} + + @Override + public UpdateControl reconcile( + MultipleManagedDependentNoDiscriminatorCustomResource resource, + Context context) { + numberOfExecutions.getAndIncrement(); + + return UpdateControl.noUpdate(); + } + + + public int getNumberOfExecutions() { + return numberOfExecutions.get(); + } + + @Override + public List> prepareEventSources( + EventSourceContext context) { + InformerEventSource ies = + new InformerEventSource<>( + InformerEventSourceConfiguration.from(ConfigMap.class, + MultipleManagedDependentNoDiscriminatorCustomResource.class) + .withName(CONFIG_MAP_EVENT_SOURCE) + .build(), + context); + + return List.of(ies); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/MultipleManagedDependentResourceConfigMap1.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanageddependentsametype/MultipleManagedDependentResourceConfigMap1.java similarity index 89% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/MultipleManagedDependentResourceConfigMap1.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanageddependentsametype/MultipleManagedDependentResourceConfigMap1.java index 98f8033076..4d69ef25e3 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/MultipleManagedDependentResourceConfigMap1.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanageddependentsametype/MultipleManagedDependentResourceConfigMap1.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype; +package io.javaoperatorsdk.operator.dependent.multiplemanageddependentsametype; import java.util.HashMap; import java.util.Map; @@ -9,7 +9,7 @@ import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; -@KubernetesDependent(resourceDiscriminator = ConfigMap1Discriminator.class) +@KubernetesDependent public class MultipleManagedDependentResourceConfigMap1 extends CRUDKubernetesDependentResource { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/MultipleManagedDependentResourceConfigMap2.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanageddependentsametype/MultipleManagedDependentResourceConfigMap2.java similarity index 77% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/MultipleManagedDependentResourceConfigMap2.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanageddependentsametype/MultipleManagedDependentResourceConfigMap2.java index d4cdd4170f..11231470e7 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/MultipleManagedDependentResourceConfigMap2.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanageddependentsametype/MultipleManagedDependentResourceConfigMap2.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype; +package io.javaoperatorsdk.operator.dependent.multiplemanageddependentsametype; import java.util.HashMap; import java.util.Map; @@ -9,9 +9,7 @@ import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; -import static io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype.MultipleManagedDependentResourceReconciler.DATA_KEY; - -@KubernetesDependent(resourceDiscriminator = ConfigMap2Discriminator.class) +@KubernetesDependent public class MultipleManagedDependentResourceConfigMap2 extends CRUDKubernetesDependentResource { @@ -26,7 +24,7 @@ public MultipleManagedDependentResourceConfigMap2() { protected ConfigMap desired(MultipleManagedDependentResourceCustomResource primary, Context context) { Map data = new HashMap<>(); - data.put(DATA_KEY, primary.getSpec().getValue()); + data.put(MultipleManagedDependentResourceReconciler.DATA_KEY, primary.getSpec().getValue()); return new ConfigMapBuilder() .withNewMetadata() diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/MultipleManagedDependentResourceCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanageddependentsametype/MultipleManagedDependentResourceCustomResource.java similarity index 86% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/MultipleManagedDependentResourceCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanageddependentsametype/MultipleManagedDependentResourceCustomResource.java index 44564727a2..2c131978b6 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/MultipleManagedDependentResourceCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanageddependentsametype/MultipleManagedDependentResourceCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype; +package io.javaoperatorsdk.operator.dependent.multiplemanageddependentsametype; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/MultipleManagedDependentResourceReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanageddependentsametype/MultipleManagedDependentResourceReconciler.java similarity index 67% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/MultipleManagedDependentResourceReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanageddependentsametype/MultipleManagedDependentResourceReconciler.java index 2d9b4f3ee9..f25587b2ee 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/MultipleManagedDependentResourceReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanageddependentsametype/MultipleManagedDependentResourceReconciler.java @@ -1,28 +1,28 @@ -package io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype; +package io.javaoperatorsdk.operator.dependent.multiplemanageddependentsametype; -import java.util.Map; +import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import io.fabric8.kubernetes.api.model.ConfigMap; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; import io.javaoperatorsdk.operator.api.reconciler.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; import io.javaoperatorsdk.operator.processing.event.source.EventSource; import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -import static io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype.MultipleManagedDependentResourceReconciler.CONFIG_MAP_EVENT_SOURCE; +import static io.javaoperatorsdk.operator.dependent.multiplemanageddependentsametype.MultipleManagedDependentResourceReconciler.CONFIG_MAP_EVENT_SOURCE; -@ControllerConfiguration(dependents = { +@Workflow(dependents = { @Dependent(type = MultipleManagedDependentResourceConfigMap1.class, useEventSourceWithName = CONFIG_MAP_EVENT_SOURCE), @Dependent(type = MultipleManagedDependentResourceConfigMap2.class, useEventSourceWithName = CONFIG_MAP_EVENT_SOURCE) }) +@ControllerConfiguration public class MultipleManagedDependentResourceReconciler implements Reconciler, - TestExecutionInfoProvider, - EventSourceInitializer { + TestExecutionInfoProvider { public static final String CONFIG_MAP_EVENT_SOURCE = "ConfigMapEventSource"; public static final String DATA_KEY = "key"; @@ -46,12 +46,15 @@ public int getNumberOfExecutions() { } @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { InformerEventSource ies = - new InformerEventSource<>(InformerConfiguration.from(ConfigMap.class, context) - .build(), context); - - return Map.of(CONFIG_MAP_EVENT_SOURCE, ies); + new InformerEventSource<>( + InformerEventSourceConfiguration + .from(ConfigMap.class, MultipleManagedDependentResourceCustomResource.class) + .withName(CONFIG_MAP_EVENT_SOURCE) + .build(), + context); + return List.of(ies); } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/MultipleManagedDependentResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanageddependentsametype/MultipleManagedDependentResourceSpec.java similarity index 75% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/MultipleManagedDependentResourceSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanageddependentsametype/MultipleManagedDependentResourceSpec.java index cdd524e03e..9b50de6ad1 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/MultipleManagedDependentResourceSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanageddependentsametype/MultipleManagedDependentResourceSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype; +package io.javaoperatorsdk.operator.dependent.multiplemanageddependentsametype; public class MultipleManagedDependentResourceSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleManagedDependentSameTypeIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanageddependentsametype/MultipleManagedDependentSameTypeIT.java similarity index 83% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleManagedDependentSameTypeIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanageddependentsametype/MultipleManagedDependentSameTypeIT.java index 32fe0eaec4..ed568e75e1 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleManagedDependentSameTypeIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanageddependentsametype/MultipleManagedDependentSameTypeIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.multiplemanageddependentsametype; import java.time.Duration; import java.util.stream.Collectors; @@ -8,12 +8,9 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype.MultipleManagedDependentResourceCustomResource; -import io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype.MultipleManagedDependentResourceReconciler; -import io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype.MultipleManagedDependentResourceSpec; import static io.javaoperatorsdk.operator.IntegrationTestConstants.GARBAGE_COLLECTION_TIMEOUT_SECONDS; -import static io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype.MultipleManagedDependentResourceReconciler.DATA_KEY; +import static io.javaoperatorsdk.operator.dependent.multiplemanageddependentsametype.MultipleManagedDependentResourceReconciler.DATA_KEY; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanagedexternaldependenttype/AbstractExternalDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/AbstractExternalDependentResource.java similarity index 97% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanagedexternaldependenttype/AbstractExternalDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/AbstractExternalDependentResource.java index f7d3c91dd3..9cc3830be8 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanagedexternaldependenttype/AbstractExternalDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/AbstractExternalDependentResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multiplemanagedexternaldependenttype; +package io.javaoperatorsdk.operator.dependent.multiplemanagedexternaldependenttype; import java.util.Map; import java.util.Set; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanagedexternaldependenttype/ExternalDependentResource1.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/ExternalDependentResource1.java similarity index 51% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanagedexternaldependenttype/ExternalDependentResource1.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/ExternalDependentResource1.java index cfe67a3796..d3894f797d 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanagedexternaldependenttype/ExternalDependentResource1.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/ExternalDependentResource1.java @@ -1,13 +1,9 @@ -package io.javaoperatorsdk.operator.sample.multiplemanagedexternaldependenttype; +package io.javaoperatorsdk.operator.dependent.multiplemanagedexternaldependenttype; public class ExternalDependentResource1 extends AbstractExternalDependentResource { public static final String SUFFIX = "-1"; - public ExternalDependentResource1() { - setResourceDiscriminator(new ExternalResourceDiscriminator(SUFFIX)); - } - @Override protected String resourceIDSuffix() { return SUFFIX; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanagedexternaldependenttype/ExternalDependentResource2.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/ExternalDependentResource2.java similarity index 51% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanagedexternaldependenttype/ExternalDependentResource2.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/ExternalDependentResource2.java index 29bb237e1a..9281bf3a9a 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanagedexternaldependenttype/ExternalDependentResource2.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/ExternalDependentResource2.java @@ -1,13 +1,9 @@ -package io.javaoperatorsdk.operator.sample.multiplemanagedexternaldependenttype; +package io.javaoperatorsdk.operator.dependent.multiplemanagedexternaldependenttype; public class ExternalDependentResource2 extends AbstractExternalDependentResource { public static final String SUFFIX = "-2"; - public ExternalDependentResource2() { - setResourceDiscriminator(new ExternalResourceDiscriminator(SUFFIX)); - } - @Override protected String resourceIDSuffix() { return SUFFIX; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanagedexternaldependenttype/MultipleManagedExternalDependentResourceCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/MultipleManagedExternalDependentResourceCustomResource.java similarity index 71% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanagedexternaldependenttype/MultipleManagedExternalDependentResourceCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/MultipleManagedExternalDependentResourceCustomResource.java index c989a5c96c..df443880c9 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanagedexternaldependenttype/MultipleManagedExternalDependentResourceCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/MultipleManagedExternalDependentResourceCustomResource.java @@ -1,11 +1,11 @@ -package io.javaoperatorsdk.operator.sample.multiplemanagedexternaldependenttype; +package io.javaoperatorsdk.operator.dependent.multiplemanagedexternaldependenttype; 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; -import io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype.MultipleManagedDependentResourceSpec; +import io.javaoperatorsdk.operator.dependent.multiplemanageddependentsametype.MultipleManagedDependentResourceSpec; @Group("sample.javaoperatorsdk") @Version("v1") diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/MultipleManagedExternalDependentResourceReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/MultipleManagedExternalDependentResourceReconciler.java new file mode 100644 index 0000000000..cd17f1706b --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/MultipleManagedExternalDependentResourceReconciler.java @@ -0,0 +1,82 @@ +package io.javaoperatorsdk.operator.dependent.multiplemanagedexternaldependenttype; + +import java.time.Duration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; +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.javaoperatorsdk.operator.processing.event.ResourceID; +import io.javaoperatorsdk.operator.processing.event.source.EventSource; +import io.javaoperatorsdk.operator.processing.event.source.polling.PollingConfigurationBuilder; +import io.javaoperatorsdk.operator.processing.event.source.polling.PollingEventSource; +import io.javaoperatorsdk.operator.support.ExternalResource; +import io.javaoperatorsdk.operator.support.ExternalServiceMock; +import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; + +import static io.javaoperatorsdk.operator.dependent.multiplemanagedexternaldependenttype.MultipleManagedExternalDependentResourceReconciler.EVENT_SOURCE_NAME; + +@Workflow(dependents = { + @Dependent(type = ExternalDependentResource1.class, + useEventSourceWithName = EVENT_SOURCE_NAME), + @Dependent(type = ExternalDependentResource2.class, + useEventSourceWithName = EVENT_SOURCE_NAME) +}) +@ControllerConfiguration() +public class MultipleManagedExternalDependentResourceReconciler + implements Reconciler, + TestExecutionInfoProvider { + + public static final String EVENT_SOURCE_NAME = "ConfigMapEventSource"; + protected ExternalServiceMock externalServiceMock = ExternalServiceMock.getInstance(); + private final AtomicInteger numberOfExecutions = new AtomicInteger(0); + + public MultipleManagedExternalDependentResourceReconciler() {} + + @Override + public UpdateControl reconcile( + MultipleManagedExternalDependentResourceCustomResource resource, + Context context) { + numberOfExecutions.getAndIncrement(); + + return UpdateControl.noUpdate(); + } + + public int getNumberOfExecutions() { + return numberOfExecutions.get(); + } + + @Override + public List> prepareEventSources( + EventSourceContext context) { + + final PollingEventSource.GenericResourceFetcher fetcher = () -> { + var lists = externalServiceMock.listResources(); + final Map> res = new HashMap<>(); + lists.forEach(er -> { + var resourceId = er.toResourceID(); + res.computeIfAbsent(resourceId, rid -> new HashSet<>()); + res.get(resourceId).add(er); + }); + return res; + }; + + PollingEventSource pollingEventSource = + new PollingEventSource<>(ExternalResource.class, + new PollingConfigurationBuilder<>(fetcher, Duration.ofMillis(1000L)) + .withName(EVENT_SOURCE_NAME) + .withCacheKeyMapper(ExternalResource::getId) + .build()); + + return List.of(pollingEventSource); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleManagedExternalDependentSameTypeIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/MultipleManagedExternalDependentSameTypeIT.java similarity index 84% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleManagedExternalDependentSameTypeIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/MultipleManagedExternalDependentSameTypeIT.java index e62835c063..024060202b 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MultipleManagedExternalDependentSameTypeIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multiplemanagedexternaldependenttype/MultipleManagedExternalDependentSameTypeIT.java @@ -1,13 +1,11 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.multiplemanagedexternaldependenttype; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.dependent.multiplemanageddependentsametype.MultipleManagedDependentResourceSpec; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype.MultipleManagedDependentResourceSpec; -import io.javaoperatorsdk.operator.sample.multiplemanagedexternaldependenttype.MultipleManagedExternalDependentResourceCustomResource; -import io.javaoperatorsdk.operator.sample.multiplemanagedexternaldependenttype.MultipleManagedExternalDependentResourceReconciler; import io.javaoperatorsdk.operator.support.ExternalServiceMock; import static org.assertj.core.api.Assertions.assertThat; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MultiOwnerDependentTriggeringIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipleupdateondependent/MultiOwnerDependentTriggeringIT.java similarity index 85% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/MultiOwnerDependentTriggeringIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipleupdateondependent/MultiOwnerDependentTriggeringIT.java index 7f6f917c55..d9c62d9a29 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/MultiOwnerDependentTriggeringIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipleupdateondependent/MultiOwnerDependentTriggeringIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.multipleupdateondependent; import java.util.Set; @@ -8,10 +8,6 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.multipleupdateondependent.MultipleOwnerDependentConfigMap; -import io.javaoperatorsdk.operator.sample.multipleupdateondependent.MultipleOwnerDependentCustomResource; -import io.javaoperatorsdk.operator.sample.multipleupdateondependent.MultipleOwnerDependentReconciler; -import io.javaoperatorsdk.operator.sample.multipleupdateondependent.MultipleOwnerDependentSpec; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipleupdateondependent/MultipleOwnerDependentConfigMap.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipleupdateondependent/MultipleOwnerDependentConfigMap.java similarity index 93% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipleupdateondependent/MultipleOwnerDependentConfigMap.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipleupdateondependent/MultipleOwnerDependentConfigMap.java index 698cec88af..b906796708 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipleupdateondependent/MultipleOwnerDependentConfigMap.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipleupdateondependent/MultipleOwnerDependentConfigMap.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multipleupdateondependent; +package io.javaoperatorsdk.operator.dependent.multipleupdateondependent; import java.util.HashMap; import java.util.List; @@ -49,7 +49,7 @@ public Optional getSecondaryResource(MultipleOwnerDependentCustomReso Context context) { InformerEventSource ies = (InformerEventSource) context - .eventSourceRetriever().getResourceEventSourceFor(ConfigMap.class); + .eventSourceRetriever().getEventSourceFor(ConfigMap.class); return ies.get(new ResourceID(RESOURCE_NAME, primary.getMetadata().getNamespace())); } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipleupdateondependent/MultipleOwnerDependentCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipleupdateondependent/MultipleOwnerDependentCustomResource.java similarity index 86% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipleupdateondependent/MultipleOwnerDependentCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipleupdateondependent/MultipleOwnerDependentCustomResource.java index 85b8be124c..d84e1bf5db 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipleupdateondependent/MultipleOwnerDependentCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipleupdateondependent/MultipleOwnerDependentCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multipleupdateondependent; +package io.javaoperatorsdk.operator.dependent.multipleupdateondependent; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipleupdateondependent/MultipleOwnerDependentReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipleupdateondependent/MultipleOwnerDependentReconciler.java similarity index 70% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipleupdateondependent/MultipleOwnerDependentReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipleupdateondependent/MultipleOwnerDependentReconciler.java index c1f1262414..b4c01cb6b9 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipleupdateondependent/MultipleOwnerDependentReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipleupdateondependent/MultipleOwnerDependentReconciler.java @@ -1,17 +1,15 @@ -package io.javaoperatorsdk.operator.sample.multipleupdateondependent; +package io.javaoperatorsdk.operator.dependent.multipleupdateondependent; import java.util.concurrent.atomic.AtomicInteger; -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.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -@ControllerConfiguration(dependents = { +@Workflow(dependents = { @Dependent(type = MultipleOwnerDependentConfigMap.class) }) +@ControllerConfiguration() public class MultipleOwnerDependentReconciler implements Reconciler, TestExecutionInfoProvider { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipleupdateondependent/MultipleOwnerDependentSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipleupdateondependent/MultipleOwnerDependentSpec.java similarity index 75% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipleupdateondependent/MultipleOwnerDependentSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipleupdateondependent/MultipleOwnerDependentSpec.java index cda4377cdc..5600dde5a4 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipleupdateondependent/MultipleOwnerDependentSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/multipleupdateondependent/MultipleOwnerDependentSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.multipleupdateondependent; +package io.javaoperatorsdk.operator.dependent.multipleupdateondependent; public class MultipleOwnerDependentSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentPrimaryIndexerIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primaryindexer/DependentPrimaryIndexerIT.java similarity index 71% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentPrimaryIndexerIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primaryindexer/DependentPrimaryIndexerIT.java index 44d88aaecf..16bb0d46a7 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/DependentPrimaryIndexerIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primaryindexer/DependentPrimaryIndexerIT.java @@ -1,7 +1,7 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.primaryindexer; +import io.javaoperatorsdk.operator.baseapi.primaryindexer.PrimaryIndexerIT; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.primaryindexer.DependentPrimaryIndexerTestReconciler; public class DependentPrimaryIndexerIT extends PrimaryIndexerIT { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primaryindexer/DependentPrimaryIndexerTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primaryindexer/DependentPrimaryIndexerTestReconciler.java new file mode 100644 index 0000000000..bb97a32cf9 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primaryindexer/DependentPrimaryIndexerTestReconciler.java @@ -0,0 +1,75 @@ +package io.javaoperatorsdk.operator.dependent.primaryindexer; + +import java.util.List; +import java.util.stream.Collectors; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +import io.javaoperatorsdk.operator.api.reconciler.Workflow; +import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; +import io.javaoperatorsdk.operator.baseapi.primaryindexer.AbstractPrimaryIndexerTestReconciler; +import io.javaoperatorsdk.operator.baseapi.primaryindexer.PrimaryIndexerTestCustomResource; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; +import io.javaoperatorsdk.operator.processing.event.ResourceID; +import io.javaoperatorsdk.operator.processing.event.source.EventSource; +import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; + +import static io.javaoperatorsdk.operator.dependent.primaryindexer.DependentPrimaryIndexerTestReconciler.CONFIG_MAP_EVENT_SOURCE; + +@Workflow(dependents = @Dependent(useEventSourceWithName = CONFIG_MAP_EVENT_SOURCE, + type = DependentPrimaryIndexerTestReconciler.ReadOnlyConfigMapDependent.class)) +@ControllerConfiguration +public class DependentPrimaryIndexerTestReconciler extends AbstractPrimaryIndexerTestReconciler + implements + Reconciler { + + public static final String CONFIG_MAP_EVENT_SOURCE = "configMapEventSource"; + + @Override + public List> prepareEventSources( + EventSourceContext context) { + + var cache = context.getPrimaryCache(); + cache.addIndexer(CONFIG_MAP_RELATION_INDEXER, indexer); + + InformerEventSource es = + new InformerEventSource<>( + InformerEventSourceConfiguration + .from(ConfigMap.class, PrimaryIndexerTestCustomResource.class) + .withName(CONFIG_MAP_EVENT_SOURCE) + .withSecondaryToPrimaryMapper(resource -> cache + .byIndex(CONFIG_MAP_RELATION_INDEXER, resource.getMetadata().getName()) + .stream() + .map(ResourceID::fromResource) + .collect(Collectors.toSet())) + .build(), + context); + + return List.of(es); + } + + public static class ReadOnlyConfigMapDependent + extends KubernetesDependentResource { + + public ReadOnlyConfigMapDependent() { + super(ConfigMap.class); + } + + @Override + protected ConfigMap desired(PrimaryIndexerTestCustomResource primary, + Context context) { + return new ConfigMapBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName(CONFIG_MAP_NAME) + .withNamespace(primary.getMetadata().getNamespace()) + .build()) + .build(); + } + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/ConfigMapDependent.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/ConfigMapDependent.java new file mode 100644 index 0000000000..c9b85acc69 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/ConfigMapDependent.java @@ -0,0 +1,28 @@ +package io.javaoperatorsdk.operator.dependent.primarytosecondaydependent; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; + +public class ConfigMapDependent extends + KubernetesDependentResource { + + public static final String TEST_CONFIG_MAP_NAME = "testconfigmap"; + + public ConfigMapDependent() { + super(ConfigMap.class); + } + + @Override + protected ConfigMap desired(PrimaryToSecondaryDependentCustomResource primary, + Context context) { + return new ConfigMapBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName(TEST_CONFIG_MAP_NAME) + .withNamespace(primary.getMetadata().getNamespace()) + .build()) + .build(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondaydependent/ConfigMapReconcilePrecondition.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/ConfigMapReconcilePrecondition.java similarity index 78% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondaydependent/ConfigMapReconcilePrecondition.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/ConfigMapReconcilePrecondition.java index b8aa65585d..ab4ba62edf 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondaydependent/ConfigMapReconcilePrecondition.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/ConfigMapReconcilePrecondition.java @@ -1,12 +1,10 @@ -package io.javaoperatorsdk.operator.sample.primarytosecondaydependent; +package io.javaoperatorsdk.operator.dependent.primarytosecondaydependent; import io.fabric8.kubernetes.api.model.ConfigMap; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; import io.javaoperatorsdk.operator.processing.dependent.workflow.Condition; -import static io.javaoperatorsdk.operator.sample.primarytosecondaydependent.PrimaryToSecondaryDependentReconciler.DATA_KEY; - public class ConfigMapReconcilePrecondition implements Condition { @@ -18,7 +16,7 @@ public boolean isMet( PrimaryToSecondaryDependentCustomResource primary, Context context) { return dependentResource.getSecondaryResource(primary, context).map(cm -> { - var data = cm.getData().get(DATA_KEY); + var data = cm.getData().get(PrimaryToSecondaryDependentReconciler.DATA_KEY); return data != null && !data.equals(DO_NOT_RECONCILE); }) .orElse(false); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondaydependent/PrimaryToSecondaryDependentCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/PrimaryToSecondaryDependentCustomResource.java similarity index 86% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondaydependent/PrimaryToSecondaryDependentCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/PrimaryToSecondaryDependentCustomResource.java index 4ec7065f2e..8be9ecf5c6 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondaydependent/PrimaryToSecondaryDependentCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/PrimaryToSecondaryDependentCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.primarytosecondaydependent; +package io.javaoperatorsdk.operator.dependent.primarytosecondaydependent; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/PrimaryToSecondaryDependentIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/PrimaryToSecondaryDependentIT.java similarity index 77% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/PrimaryToSecondaryDependentIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/PrimaryToSecondaryDependentIT.java index eaa7e4410f..681c57e0d1 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/PrimaryToSecondaryDependentIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/PrimaryToSecondaryDependentIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.primarytosecondaydependent; import java.time.Duration; import java.util.Map; @@ -10,18 +10,16 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.api.model.Secret; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.primarytosecondaydependent.PrimaryToSecondaryDependentCustomResource; -import io.javaoperatorsdk.operator.sample.primarytosecondaydependent.PrimaryToSecondaryDependentReconciler; -import io.javaoperatorsdk.operator.sample.primarytosecondaydependent.PrimaryToSecondaryDependentSpec; -import static io.javaoperatorsdk.operator.sample.primarytosecondaydependent.ConfigMapReconcilePrecondition.DO_NOT_RECONCILE; -import static io.javaoperatorsdk.operator.sample.primarytosecondaydependent.PrimaryToSecondaryDependentReconciler.DATA_KEY; +import static io.javaoperatorsdk.operator.dependent.primarytosecondaydependent.ConfigMapDependent.TEST_CONFIG_MAP_NAME; +import static io.javaoperatorsdk.operator.dependent.primarytosecondaydependent.ConfigMapReconcilePrecondition.DO_NOT_RECONCILE; +import static io.javaoperatorsdk.operator.dependent.primarytosecondaydependent.PrimaryToSecondaryDependentReconciler.DATA_KEY; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; class PrimaryToSecondaryDependentIT { - public static final String TEST_CONFIG_MAP_NAME = "testconfigmap"; + public static final String TEST_CR_NAME = "test1"; public static final String TEST_DATA = "testData"; public diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondaydependent/PrimaryToSecondaryDependentReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/PrimaryToSecondaryDependentReconciler.java similarity index 81% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondaydependent/PrimaryToSecondaryDependentReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/PrimaryToSecondaryDependentReconciler.java index c51111b206..76e2015be8 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondaydependent/PrimaryToSecondaryDependentReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/PrimaryToSecondaryDependentReconciler.java @@ -1,13 +1,12 @@ -package io.javaoperatorsdk.operator.sample.primarytosecondaydependent; +package io.javaoperatorsdk.operator.dependent.primarytosecondaydependent; import java.util.List; -import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import io.fabric8.kubernetes.api.model.ConfigMap; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; import io.javaoperatorsdk.operator.api.reconciler.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; import io.javaoperatorsdk.operator.processing.event.ResourceID; @@ -16,22 +15,22 @@ import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -import static io.javaoperatorsdk.operator.sample.primarytosecondaydependent.PrimaryToSecondaryDependentReconciler.CONFIG_MAP; -import static io.javaoperatorsdk.operator.sample.primarytosecondaydependent.PrimaryToSecondaryDependentReconciler.CONFIG_MAP_EVENT_SOURCE; +import static io.javaoperatorsdk.operator.dependent.primarytosecondaydependent.PrimaryToSecondaryDependentReconciler.CONFIG_MAP; +import static io.javaoperatorsdk.operator.dependent.primarytosecondaydependent.PrimaryToSecondaryDependentReconciler.CONFIG_MAP_EVENT_SOURCE; /** * Sample showcases how it is possible to do a primary to secondary mapper for a dependent resource. * Note that this is usually just used with read only resources. So it has limited usage, one reason * to use it is to have nice condition on that resource within a workflow. */ -@ControllerConfiguration(dependents = {@Dependent(type = ConfigMapDependent.class, +@Workflow(dependents = {@Dependent(type = ConfigMapDependent.class, name = CONFIG_MAP, reconcilePrecondition = ConfigMapReconcilePrecondition.class, useEventSourceWithName = CONFIG_MAP_EVENT_SOURCE), @Dependent(type = SecretDependent.class, dependsOn = CONFIG_MAP)}) +@ControllerConfiguration() public class PrimaryToSecondaryDependentReconciler - implements Reconciler, TestExecutionInfoProvider, - EventSourceInitializer { + implements Reconciler, TestExecutionInfoProvider { public static final String DATA_KEY = "data"; public static final String CONFIG_MAP = "ConfigMap"; @@ -59,7 +58,7 @@ public int getNumberOfExecutions() { * demand for it. **/ @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { // there is no owner reference in the config map, but we still want to trigger reconciliation if // the config map changes. So first we add an index which custom resource references the config @@ -67,8 +66,9 @@ public Map prepareEventSources( context.getPrimaryCache().addIndexer(CONFIG_MAP_INDEX, (primary -> List .of(indexKey(primary.getSpec().getConfigMapName(), primary.getMetadata().getNamespace())))); - var cmES = new InformerEventSource<>(InformerConfiguration - .from(ConfigMap.class, context) + var es = new InformerEventSource<>(InformerEventSourceConfiguration + .from(ConfigMap.class, PrimaryToSecondaryDependentCustomResource.class) + .withName(CONFIG_MAP_EVENT_SOURCE) // if there is a many-to-many relationship (thus no direct owner reference) // PrimaryToSecondaryMapper needs to be added .withPrimaryToSecondaryMapper( @@ -83,7 +83,7 @@ public Map prepareEventSources( .build(), context); - return Map.of(CONFIG_MAP_EVENT_SOURCE, cmES); + return List.of(es); } private String indexKey(String configMapName, String namespace) { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondaydependent/PrimaryToSecondaryDependentSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/PrimaryToSecondaryDependentSpec.java similarity index 79% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondaydependent/PrimaryToSecondaryDependentSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/PrimaryToSecondaryDependentSpec.java index 966a5c242b..bf2773f571 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondaydependent/PrimaryToSecondaryDependentSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/PrimaryToSecondaryDependentSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.primarytosecondaydependent; +package io.javaoperatorsdk.operator.dependent.primarytosecondaydependent; public class PrimaryToSecondaryDependentSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondaydependent/SecretDependent.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/SecretDependent.java similarity index 83% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondaydependent/SecretDependent.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/SecretDependent.java index c78f3c470f..aa9470676d 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondaydependent/SecretDependent.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/primarytosecondaydependent/SecretDependent.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.primarytosecondaydependent; +package io.javaoperatorsdk.operator.dependent.primarytosecondaydependent; import java.util.Map; @@ -8,7 +8,7 @@ import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; -import static io.javaoperatorsdk.operator.sample.primarytosecondaydependent.PrimaryToSecondaryDependentReconciler.DATA_KEY; +import static io.javaoperatorsdk.operator.dependent.primarytosecondaydependent.PrimaryToSecondaryDependentReconciler.DATA_KEY; public class SecretDependent extends CRUDKubernetesDependentResource { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/readonly/ConfigMapReader.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/readonly/ConfigMapReader.java similarity index 85% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/readonly/ConfigMapReader.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/readonly/ConfigMapReader.java index ffff1bf78a..c904a1741e 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/readonly/ConfigMapReader.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/readonly/ConfigMapReader.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.readonly; +package io.javaoperatorsdk.operator.dependent.readonly; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/readonly/ReadOnlyDependent.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/readonly/ReadOnlyDependent.java similarity index 65% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/readonly/ReadOnlyDependent.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/readonly/ReadOnlyDependent.java index 15fb02a0b6..63e43fef95 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/readonly/ReadOnlyDependent.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/readonly/ReadOnlyDependent.java @@ -1,8 +1,10 @@ -package io.javaoperatorsdk.operator.sample.readonly; +package io.javaoperatorsdk.operator.dependent.readonly; import io.fabric8.kubernetes.api.model.ConfigMap; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; +@KubernetesDependent public class ReadOnlyDependent extends KubernetesDependentResource { public ReadOnlyDependent() { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/restart/ConfigMapDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/restart/ConfigMapDependentResource.java similarity index 85% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/restart/ConfigMapDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/restart/ConfigMapDependentResource.java index edb4e2baff..b7e69febd1 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/restart/ConfigMapDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/restart/ConfigMapDependentResource.java @@ -1,15 +1,16 @@ -package io.javaoperatorsdk.operator.sample.restart; +package io.javaoperatorsdk.operator.dependent.restart; import java.util.Map; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.api.config.informer.Informer; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; -@KubernetesDependent(labelSelector = "app=restart-test") +@KubernetesDependent(informer = @Informer(labelSelector = "app=restart-test")) public class ConfigMapDependentResource extends CRUDKubernetesDependentResource { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/OperatorRestartIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/restart/OperatorRestartIT.java similarity index 89% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/OperatorRestartIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/restart/OperatorRestartIT.java index 9f506cc927..db51c81081 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/OperatorRestartIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/restart/OperatorRestartIT.java @@ -1,11 +1,10 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.restart; import org.junit.jupiter.api.*; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.Operator; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.restart.RestartTestCustomResource; -import io.javaoperatorsdk.operator.sample.restart.RestartTestReconciler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/restart/RestartTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/restart/RestartTestCustomResource.java similarity index 89% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/restart/RestartTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/restart/RestartTestCustomResource.java index a3bcd31053..6f9c08251d 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/restart/RestartTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/restart/RestartTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.restart; +package io.javaoperatorsdk.operator.dependent.restart; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/restart/RestartTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/restart/RestartTestReconciler.java similarity index 63% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/restart/RestartTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/restart/RestartTestReconciler.java index decd9b597b..6f59c29dc8 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/restart/RestartTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/restart/RestartTestReconciler.java @@ -1,16 +1,13 @@ -package io.javaoperatorsdk.operator.sample.restart; +package io.javaoperatorsdk.operator.dependent.restart; import java.util.concurrent.atomic.AtomicInteger; -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.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -@ControllerConfiguration( - dependents = @Dependent(type = ConfigMapDependentResource.class)) +@Workflow(dependents = @Dependent(type = ConfigMapDependentResource.class)) +@ControllerConfiguration public class RestartTestReconciler implements Reconciler, TestExecutionInfoProvider { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/servicestrictmatcher/ServiceDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/servicestrictmatcher/ServiceDependentResource.java similarity index 93% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/servicestrictmatcher/ServiceDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/servicestrictmatcher/ServiceDependentResource.java index deddf20263..a88fa14463 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/servicestrictmatcher/ServiceDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/servicestrictmatcher/ServiceDependentResource.java @@ -1,11 +1,10 @@ -package io.javaoperatorsdk.operator.sample.servicestrictmatcher; +package io.javaoperatorsdk.operator.dependent.servicestrictmatcher; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import io.fabric8.kubernetes.api.model.Service; -import io.javaoperatorsdk.operator.ServiceStrictMatcherIT; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.processing.dependent.Matcher; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; @@ -27,7 +26,8 @@ public ServiceDependentResource() { @Override protected Service desired(ServiceStrictMatcherTestCustomResource primary, Context context) { - Service service = loadYaml(Service.class, ServiceStrictMatcherIT.class, "service.yaml"); + Service service = loadYaml(Service.class, ServiceStrictMatcherIT.class, + "/io/javaoperatorsdk/operator/service.yaml"); service.getMetadata().setName(primary.getMetadata().getName()); service.getMetadata().setNamespace(primary.getMetadata().getNamespace()); Map labels = new HashMap<>(); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ServiceStrictMatcherIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/servicestrictmatcher/ServiceStrictMatcherIT.java similarity index 79% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/ServiceStrictMatcherIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/servicestrictmatcher/ServiceStrictMatcherIT.java index 97caab21ee..7d1b306210 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ServiceStrictMatcherIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/servicestrictmatcher/ServiceStrictMatcherIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.servicestrictmatcher; import java.time.Duration; @@ -7,10 +7,6 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.servicestrictmatcher.ServiceDependentResource; -import io.javaoperatorsdk.operator.sample.servicestrictmatcher.ServiceStrictMatcherSpec; -import io.javaoperatorsdk.operator.sample.servicestrictmatcher.ServiceStrictMatcherTestCustomResource; -import io.javaoperatorsdk.operator.sample.servicestrictmatcher.ServiceStrictMatcherTestReconciler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/servicestrictmatcher/ServiceStrictMatcherSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/servicestrictmatcher/ServiceStrictMatcherSpec.java similarity index 76% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/servicestrictmatcher/ServiceStrictMatcherSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/servicestrictmatcher/ServiceStrictMatcherSpec.java index 1233b70914..d8840d92ba 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/servicestrictmatcher/ServiceStrictMatcherSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/servicestrictmatcher/ServiceStrictMatcherSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.servicestrictmatcher; +package io.javaoperatorsdk.operator.dependent.servicestrictmatcher; public class ServiceStrictMatcherSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/servicestrictmatcher/ServiceStrictMatcherTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/servicestrictmatcher/ServiceStrictMatcherTestCustomResource.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/servicestrictmatcher/ServiceStrictMatcherTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/servicestrictmatcher/ServiceStrictMatcherTestCustomResource.java index 6079ceb757..6e05628633 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/servicestrictmatcher/ServiceStrictMatcherTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/servicestrictmatcher/ServiceStrictMatcherTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.servicestrictmatcher; +package io.javaoperatorsdk.operator.dependent.servicestrictmatcher; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/servicestrictmatcher/ServiceStrictMatcherTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/servicestrictmatcher/ServiceStrictMatcherTestReconciler.java similarity index 62% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/servicestrictmatcher/ServiceStrictMatcherTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/servicestrictmatcher/ServiceStrictMatcherTestReconciler.java index 64e81e7c31..556f28113d 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/servicestrictmatcher/ServiceStrictMatcherTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/servicestrictmatcher/ServiceStrictMatcherTestReconciler.java @@ -1,14 +1,12 @@ -package io.javaoperatorsdk.operator.sample.servicestrictmatcher; +package io.javaoperatorsdk.operator.dependent.servicestrictmatcher; import java.util.concurrent.atomic.AtomicInteger; -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.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; -@ControllerConfiguration(dependents = {@Dependent(type = ServiceDependentResource.class)}) +@Workflow(dependents = {@Dependent(type = ServiceDependentResource.class)}) +@ControllerConfiguration public class ServiceStrictMatcherTestReconciler implements Reconciler { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/specialresourcesdependent/ServiceAccountDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/specialresourcesdependent/ServiceAccountDependentResource.java similarity index 85% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/specialresourcesdependent/ServiceAccountDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/specialresourcesdependent/ServiceAccountDependentResource.java index 6ab5695a84..b5f8cd3225 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/specialresourcesdependent/ServiceAccountDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/specialresourcesdependent/ServiceAccountDependentResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.specialresourcesdependent; +package io.javaoperatorsdk.operator.dependent.specialresourcesdependent; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.api.model.ServiceAccount; @@ -6,7 +6,7 @@ import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; -import static io.javaoperatorsdk.operator.sample.specialresourcesdependent.SpecialResourceSpec.INITIAL_VALUE; +import static io.javaoperatorsdk.operator.dependent.specialresourcesdependent.SpecialResourceSpec.INITIAL_VALUE; @KubernetesDependent public class ServiceAccountDependentResource extends diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/specialresourcesdependent/SpecialResourceCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/specialresourcesdependent/SpecialResourceCustomResource.java similarity index 86% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/specialresourcesdependent/SpecialResourceCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/specialresourcesdependent/SpecialResourceCustomResource.java index 89ed0ca06e..fc7feeb805 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/specialresourcesdependent/SpecialResourceCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/specialresourcesdependent/SpecialResourceCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.specialresourcesdependent; +package io.javaoperatorsdk.operator.dependent.specialresourcesdependent; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/specialresourcesdependent/SpecialResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/specialresourcesdependent/SpecialResourceSpec.java similarity index 82% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/specialresourcesdependent/SpecialResourceSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/specialresourcesdependent/SpecialResourceSpec.java index 69386d72dc..f1596e0829 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/specialresourcesdependent/SpecialResourceSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/specialresourcesdependent/SpecialResourceSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.specialresourcesdependent; +package io.javaoperatorsdk.operator.dependent.specialresourcesdependent; public class SpecialResourceSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/specialresourcesdependent/SpecialResourceTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/specialresourcesdependent/SpecialResourceTestReconciler.java similarity index 73% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/specialresourcesdependent/SpecialResourceTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/specialresourcesdependent/SpecialResourceTestReconciler.java index 5fa7d778b3..7d2720c5c2 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/specialresourcesdependent/SpecialResourceTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/specialresourcesdependent/SpecialResourceTestReconciler.java @@ -1,16 +1,17 @@ -package io.javaoperatorsdk.operator.sample.specialresourcesdependent; +package io.javaoperatorsdk.operator.dependent.specialresourcesdependent; import java.util.concurrent.atomic.AtomicInteger; +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.support.TestExecutionInfoProvider; +@Workflow(dependents = { + @Dependent(type = ServiceAccountDependentResource.class), +}) @ControllerConfiguration( - namespaces = Constants.WATCH_CURRENT_NAMESPACE, - dependents = { - @Dependent(type = ServiceAccountDependentResource.class), - }) + informer = @Informer(namespaces = Constants.WATCH_CURRENT_NAMESPACE)) public class SpecialResourceTestReconciler implements Reconciler, TestExecutionInfoProvider { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/SpecialResourcesDependentIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/specialresourcesdependent/SpecialResourcesDependentIT.java similarity index 76% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/SpecialResourcesDependentIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/specialresourcesdependent/SpecialResourcesDependentIT.java index a050417254..89cd94e51d 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/SpecialResourcesDependentIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/specialresourcesdependent/SpecialResourcesDependentIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.specialresourcesdependent; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -6,12 +6,9 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.api.model.ServiceAccount; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.specialresourcesdependent.SpecialResourceCustomResource; -import io.javaoperatorsdk.operator.sample.specialresourcesdependent.SpecialResourceSpec; -import io.javaoperatorsdk.operator.sample.specialresourcesdependent.SpecialResourceTestReconciler; -import static io.javaoperatorsdk.operator.sample.specialresourcesdependent.SpecialResourceSpec.CHANGED_VALUE; -import static io.javaoperatorsdk.operator.sample.specialresourcesdependent.SpecialResourceSpec.INITIAL_VALUE; +import static io.javaoperatorsdk.operator.dependent.specialresourcesdependent.SpecialResourceSpec.CHANGED_VALUE; +import static io.javaoperatorsdk.operator.dependent.specialresourcesdependent.SpecialResourceSpec.INITIAL_VALUE; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ssalegacymatcher/SSALegacyMatcherCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/ssalegacymatcher/SSALegacyMatcherCustomResource.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ssalegacymatcher/SSALegacyMatcherCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/ssalegacymatcher/SSALegacyMatcherCustomResource.java index d68372bbeb..fe58579035 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ssalegacymatcher/SSALegacyMatcherCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/ssalegacymatcher/SSALegacyMatcherCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.ssalegacymatcher; +package io.javaoperatorsdk.operator.dependent.ssalegacymatcher; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ssalegacymatcher/SSALegacyMatcherReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/ssalegacymatcher/SSALegacyMatcherReconciler.java similarity index 60% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ssalegacymatcher/SSALegacyMatcherReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/ssalegacymatcher/SSALegacyMatcherReconciler.java index a513133670..179496f1b9 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ssalegacymatcher/SSALegacyMatcherReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/ssalegacymatcher/SSALegacyMatcherReconciler.java @@ -1,14 +1,12 @@ -package io.javaoperatorsdk.operator.sample.ssalegacymatcher; +package io.javaoperatorsdk.operator.dependent.ssalegacymatcher; import java.util.concurrent.atomic.AtomicInteger; -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.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; -@ControllerConfiguration(dependents = {@Dependent(type = ServiceDependentResource.class)}) +@Workflow(dependents = {@Dependent(type = ServiceDependentResource.class)}) +@ControllerConfiguration public class SSALegacyMatcherReconciler implements Reconciler { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ssalegacymatcher/SSALegacyMatcherSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/ssalegacymatcher/SSALegacyMatcherSpec.java similarity index 77% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ssalegacymatcher/SSALegacyMatcherSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/ssalegacymatcher/SSALegacyMatcherSpec.java index 6ee56aafd0..b2bee7f12d 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ssalegacymatcher/SSALegacyMatcherSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/ssalegacymatcher/SSALegacyMatcherSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.ssalegacymatcher; +package io.javaoperatorsdk.operator.dependent.ssalegacymatcher; public class SSALegacyMatcherSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/SSAWithLegacyMatcherIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/ssalegacymatcher/SSAWithLegacyMatcherIT.java similarity index 79% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/SSAWithLegacyMatcherIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/ssalegacymatcher/SSAWithLegacyMatcherIT.java index ba3444bfb8..090f60c7d5 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/SSAWithLegacyMatcherIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/ssalegacymatcher/SSAWithLegacyMatcherIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.ssalegacymatcher; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -6,10 +6,6 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.api.model.Service; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.ssalegacymatcher.SSALegacyMatcherCustomResource; -import io.javaoperatorsdk.operator.sample.ssalegacymatcher.SSALegacyMatcherReconciler; -import io.javaoperatorsdk.operator.sample.ssalegacymatcher.SSALegacyMatcherSpec; -import io.javaoperatorsdk.operator.sample.ssalegacymatcher.ServiceDependentResource; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ssalegacymatcher/ServiceDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/ssalegacymatcher/ServiceDependentResource.java similarity index 91% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ssalegacymatcher/ServiceDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/ssalegacymatcher/ServiceDependentResource.java index a1f5f6faf0..98036036cc 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ssalegacymatcher/ServiceDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/ssalegacymatcher/ServiceDependentResource.java @@ -1,11 +1,10 @@ -package io.javaoperatorsdk.operator.sample.ssalegacymatcher; +package io.javaoperatorsdk.operator.dependent.ssalegacymatcher; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import io.fabric8.kubernetes.api.model.Service; -import io.javaoperatorsdk.operator.SSAWithLegacyMatcherIT; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.GenericKubernetesResourceMatcher; @@ -27,7 +26,8 @@ public ServiceDependentResource() { protected Service desired(SSALegacyMatcherCustomResource primary, Context context) { - Service service = loadYaml(Service.class, SSAWithLegacyMatcherIT.class, "service.yaml"); + Service service = loadYaml(Service.class, SSAWithLegacyMatcherIT.class, + "/io/javaoperatorsdk/operator/service.yaml"); service.getMetadata().setName(primary.getMetadata().getName()); service.getMetadata().setNamespace(primary.getMetadata().getNamespace()); Map labels = new HashMap<>(); @@ -39,8 +39,10 @@ protected Service desired(SSALegacyMatcherCustomResource primary, @Override public Result match(Service actualResource, SSALegacyMatcherCustomResource primary, Context context) { + var desired = desired(primary, context); + return GenericKubernetesResourceMatcher.match(this, actualResource, primary, context, - true, false, false); + false, false); } // override just to check the exec count diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/StandaloneDependentResourceIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/standalonedependent/StandaloneDependentResourceIT.java similarity index 91% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/StandaloneDependentResourceIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/standalonedependent/StandaloneDependentResourceIT.java index 5d1c570410..19853842e7 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/StandaloneDependentResourceIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/standalonedependent/StandaloneDependentResourceIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.standalonedependent; import java.time.Duration; import java.util.Set; @@ -12,9 +12,6 @@ import io.javaoperatorsdk.operator.api.config.*; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.standalonedependent.StandaloneDependentTestCustomResource; -import io.javaoperatorsdk.operator.sample.standalonedependent.StandaloneDependentTestCustomResourceSpec; -import io.javaoperatorsdk.operator.sample.standalonedependent.StandaloneDependentTestReconciler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/standalonedependent/StandaloneDependentTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/standalonedependent/StandaloneDependentTestCustomResource.java similarity index 71% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/standalonedependent/StandaloneDependentTestCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/standalonedependent/StandaloneDependentTestCustomResource.java index e88d00c985..3f2d2c9c2e 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/standalonedependent/StandaloneDependentTestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/standalonedependent/StandaloneDependentTestCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.standalonedependent; +package io.javaoperatorsdk.operator.dependent.standalonedependent; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; @@ -11,6 +11,6 @@ @ShortNames("sdt") public class StandaloneDependentTestCustomResource extends - CustomResource + CustomResource implements Namespaced { } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/standalonedependent/StandaloneDependentTestCustomResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/standalonedependent/StandaloneDependentTestCustomResourceSpec.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/standalonedependent/StandaloneDependentTestCustomResourceSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/standalonedependent/StandaloneDependentTestCustomResourceSpec.java index 4a88cf6044..664331bbaf 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/standalonedependent/StandaloneDependentTestCustomResourceSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/standalonedependent/StandaloneDependentTestCustomResourceSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.standalonedependent; +package io.javaoperatorsdk.operator.dependent.standalonedependent; public class StandaloneDependentTestCustomResourceSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/standalonedependent/StandaloneDependentTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/standalonedependent/StandaloneDependentTestReconciler.java similarity index 79% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/standalonedependent/StandaloneDependentTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/standalonedependent/StandaloneDependentTestReconciler.java index 3798fdbcbb..e10a20a93c 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/standalonedependent/StandaloneDependentTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/standalonedependent/StandaloneDependentTestReconciler.java @@ -1,21 +1,24 @@ -package io.javaoperatorsdk.operator.sample.standalonedependent; +package io.javaoperatorsdk.operator.dependent.standalonedependent; -import java.util.Map; +import java.util.List; import java.util.Optional; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.client.KubernetesClientException; import io.javaoperatorsdk.operator.ReconcilerUtils; -import io.javaoperatorsdk.operator.StandaloneDependentResourceIT; -import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.ErrorStatusUpdateControl; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceUtils; +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; import io.javaoperatorsdk.operator.processing.event.source.EventSource; @ControllerConfiguration public class StandaloneDependentTestReconciler - implements Reconciler, - EventSourceInitializer, - ErrorStatusHandler { + implements Reconciler { private volatile boolean errorOccurred = false; DeploymentDependentResource deploymentDependent; @@ -25,9 +28,9 @@ public StandaloneDependentTestReconciler() { } @Override - public Map prepareEventSources( + public List> prepareEventSources( EventSourceContext context) { - return EventSourceInitializer.nameEventSourcesFromDependentResource(context, + return EventSourceUtils.dependentEventSources(context, deploymentDependent); } @@ -76,7 +79,7 @@ protected Deployment desired(StandaloneDependentTestCustomResource primary, Context context) { Deployment deployment = ReconcilerUtils.loadYaml(Deployment.class, StandaloneDependentResourceIT.class, - "nginx-deployment.yaml"); + "/io/javaoperatorsdk/operator/nginx-deployment.yaml"); deployment.getMetadata().setName(primary.getMetadata().getName()); deployment.getSpec().setReplicas(primary.getSpec().getReplicaCount()); deployment.getMetadata().setNamespace(primary.getMetadata().getNamespace()); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerCustomResource.java similarity index 84% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerCustomResource.java index bf35304da0..e500206207 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.statefulsetdesiredsanitizer; +package io.javaoperatorsdk.operator.dependent.statefulsetdesiredsanitizer; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerDependentResource.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerDependentResource.java index 12525c4c8d..98ac4897d7 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerDependentResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.statefulsetdesiredsanitizer; +package io.javaoperatorsdk.operator.dependent.statefulsetdesiredsanitizer; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.api.model.apps.StatefulSet; @@ -20,7 +20,8 @@ public StatefulSetDesiredSanitizerDependentResource() { protected StatefulSet desired(StatefulSetDesiredSanitizerCustomResource primary, Context context) { var template = - ReconcilerUtils.loadYaml(StatefulSet.class, getClass(), "statefulset.yaml"); + ReconcilerUtils.loadYaml(StatefulSet.class, getClass(), + "/io/javaoperatorsdk/operator/statefulset.yaml"); template.setMetadata(new ObjectMetaBuilder() .withName(primary.getMetadata().getName()) .withNamespace(primary.getMetadata().getNamespace()) diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/StatefulSetDesiredSanitizerIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerIT.java similarity index 77% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/StatefulSetDesiredSanitizerIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerIT.java index 5313fb7dfb..49c08f7a8b 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/StatefulSetDesiredSanitizerIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.dependent.statefulsetdesiredsanitizer; import java.time.Duration; @@ -8,10 +8,6 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.api.model.apps.StatefulSet; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.statefulsetdesiredsanitizer.StatefulSetDesiredSanitizerCustomResource; -import io.javaoperatorsdk.operator.sample.statefulsetdesiredsanitizer.StatefulSetDesiredSanitizerDependentResource; -import io.javaoperatorsdk.operator.sample.statefulsetdesiredsanitizer.StatefulSetDesiredSanitizerReconciler; -import io.javaoperatorsdk.operator.sample.statefulsetdesiredsanitizer.StatefulSetDesiredSanitizerSpec; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerReconciler.java similarity index 51% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerReconciler.java index c884619227..f84f71411e 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerReconciler.java @@ -1,13 +1,10 @@ -package io.javaoperatorsdk.operator.sample.statefulsetdesiredsanitizer; +package io.javaoperatorsdk.operator.dependent.statefulsetdesiredsanitizer; -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.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; -@ControllerConfiguration( - dependents = {@Dependent(type = StatefulSetDesiredSanitizerDependentResource.class)}) +@Workflow(dependents = {@Dependent(type = StatefulSetDesiredSanitizerDependentResource.class)}) +@ControllerConfiguration public class StatefulSetDesiredSanitizerReconciler implements Reconciler { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerSpec.java similarity index 76% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerSpec.java index 3cca134108..59fd852097 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/dependent/statefulsetdesiredsanitizer/StatefulSetDesiredSanitizerSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.statefulsetdesiredsanitizer; +package io.javaoperatorsdk.operator.dependent.statefulsetdesiredsanitizer; public class StatefulSetDesiredSanitizerSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/ManagedDeleterBulkReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/ManagedDeleterBulkReconciler.java deleted file mode 100644 index e759bdd200..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/ManagedDeleterBulkReconciler.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.javaoperatorsdk.operator.sample.bulkdependent; - -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.dependent.Dependent; - -@ControllerConfiguration( - dependents = @Dependent(type = ConfigMapDeleterBulkDependentResource.class)) -public class ManagedDeleterBulkReconciler implements Reconciler { - @Override - public UpdateControl reconcile( - BulkDependentTestCustomResource resource, - Context context) - throws Exception { - - return UpdateControl.noUpdate(); - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/external/ExternalBulkResourceReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/external/ExternalBulkResourceReconciler.java deleted file mode 100644 index 2543422d74..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/bulkdependent/external/ExternalBulkResourceReconciler.java +++ /dev/null @@ -1,19 +0,0 @@ -package io.javaoperatorsdk.operator.sample.bulkdependent.external; - -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.dependent.Dependent; -import io.javaoperatorsdk.operator.sample.bulkdependent.BulkDependentTestCustomResource; - -@ControllerConfiguration(dependents = @Dependent(type = ExternalBulkDependentResource.class)) -public class ExternalBulkResourceReconciler implements Reconciler { - - @Override - public UpdateControl reconcile( - BulkDependentTestCustomResource resource, Context context) - throws Exception { - return UpdateControl.noUpdate(); - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/ComplexDependentReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/ComplexDependentReconciler.java deleted file mode 100644 index da0aaf1060..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/ComplexDependentReconciler.java +++ /dev/null @@ -1,71 +0,0 @@ -package io.javaoperatorsdk.operator.sample.complexdependent; - -import java.util.Map; -import java.util.Objects; - -import io.fabric8.kubernetes.api.model.Service; -import io.fabric8.kubernetes.api.model.apps.StatefulSet; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; -import io.javaoperatorsdk.operator.api.reconciler.*; -import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; -import io.javaoperatorsdk.operator.processing.event.source.EventSource; -import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; -import io.javaoperatorsdk.operator.sample.complexdependent.dependent.*; - -import static io.javaoperatorsdk.operator.sample.complexdependent.ComplexDependentReconciler.SERVICE_EVENT_SOURCE_NAME; -import static io.javaoperatorsdk.operator.sample.complexdependent.ComplexDependentReconciler.STATEFUL_SET_EVENT_SOURCE_NAME; - -@ControllerConfiguration( - name = "project-operator", - dependents = { - @Dependent(name = "first-svc", type = FirstService.class, - useEventSourceWithName = SERVICE_EVENT_SOURCE_NAME), - @Dependent(name = "second-svc", type = SecondService.class, - useEventSourceWithName = SERVICE_EVENT_SOURCE_NAME), - @Dependent(name = "first", type = FirstStatefulSet.class, - useEventSourceWithName = STATEFUL_SET_EVENT_SOURCE_NAME, - dependsOn = {"first-svc"}, - readyPostcondition = StatefulSetReadyCondition.class), - @Dependent(name = "second", - type = SecondStatefulSet.class, - useEventSourceWithName = STATEFUL_SET_EVENT_SOURCE_NAME, - dependsOn = {"second-svc", "first"}, - readyPostcondition = StatefulSetReadyCondition.class), - }) -public class ComplexDependentReconciler implements Reconciler, - EventSourceInitializer { - - public static final String SERVICE_EVENT_SOURCE_NAME = "serviceEventSource"; - public static final String STATEFUL_SET_EVENT_SOURCE_NAME = "statefulSetEventSource"; - - @Override - public UpdateControl reconcile( - ComplexDependentCustomResource resource, - Context context) throws Exception { - var ready = context.managedDependentResourceContext().getWorkflowReconcileResult() - .orElseThrow().allDependentResourcesReady(); - - var status = Objects.requireNonNullElseGet(resource.getStatus(), ComplexDependentStatus::new); - status.setStatus(ready ? RECONCILE_STATUS.READY : RECONCILE_STATUS.NOT_READY); - resource.setStatus(status); - - return UpdateControl.updateStatus(resource); - } - - @Override - public Map prepareEventSources( - EventSourceContext context) { - InformerEventSource serviceEventSource = - new InformerEventSource<>(InformerConfiguration.from(Service.class, context).build(), - context); - InformerEventSource statefulSetEventSource = - new InformerEventSource<>(InformerConfiguration.from(StatefulSet.class, context).build(), - context); - return Map.of(SERVICE_EVENT_SOURCE_NAME, serviceEventSource, STATEFUL_SET_EVENT_SOURCE_NAME, - statefulSetEventSource); - } - - public enum RECONCILE_STATUS { - READY, NOT_READY - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/ComplexDependentSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/ComplexDependentSpec.java deleted file mode 100644 index 1eefabdf6c..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/ComplexDependentSpec.java +++ /dev/null @@ -1,14 +0,0 @@ -package io.javaoperatorsdk.operator.sample.complexdependent; - -public class ComplexDependentSpec { - private String projectId; - - public String getProjectId() { - return projectId; - } - - public ComplexDependentSpec setProjectId(String projectId) { - this.projectId = projectId; - return this; - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/ComplexDependentStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/ComplexDependentStatus.java deleted file mode 100644 index f541cbae1d..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/ComplexDependentStatus.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.javaoperatorsdk.operator.sample.complexdependent; - - -public class ComplexDependentStatus { - private ComplexDependentReconciler.RECONCILE_STATUS status; - - public ComplexDependentReconciler.RECONCILE_STATUS getStatus() { - return status; - } - - public ComplexDependentStatus setStatus(ComplexDependentReconciler.RECONCILE_STATUS status) { - this.status = status; - return this; - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/FirstService.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/FirstService.java deleted file mode 100644 index b6b0513254..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/FirstService.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.javaoperatorsdk.operator.sample.complexdependent.dependent; - -import io.fabric8.kubernetes.api.model.Service; -import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; - -@KubernetesDependent(resourceDiscriminator = FirstService.Discriminator.class) -public class FirstService extends BaseService { - public static final String DISCRIMINATOR_PREFIX = "first"; - - public FirstService() { - super(DISCRIMINATOR_PREFIX); - } - - public static class Discriminator extends NamePrefixResourceDiscriminator { - protected Discriminator() { - super(DISCRIMINATOR_PREFIX); - } - } - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/FirstStatefulSet.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/FirstStatefulSet.java deleted file mode 100644 index f50b94fe5f..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/FirstStatefulSet.java +++ /dev/null @@ -1,22 +0,0 @@ -package io.javaoperatorsdk.operator.sample.complexdependent.dependent; - -import io.fabric8.kubernetes.api.model.apps.StatefulSet; -import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; - -@KubernetesDependent(resourceDiscriminator = FirstStatefulSet.Discriminator.class) -public class FirstStatefulSet extends BaseStatefulSet { - - public static final String DISCRIMINATOR_PREFIX = "first"; - - public FirstStatefulSet() { - super(DISCRIMINATOR_PREFIX); - } - - - public static class Discriminator extends NamePrefixResourceDiscriminator { - protected Discriminator() { - super(DISCRIMINATOR_PREFIX); - } - } - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/NamePrefixResourceDiscriminator.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/NamePrefixResourceDiscriminator.java deleted file mode 100644 index eef8566c78..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/NamePrefixResourceDiscriminator.java +++ /dev/null @@ -1,31 +0,0 @@ -package io.javaoperatorsdk.operator.sample.complexdependent.dependent; - -import java.util.Optional; -import java.util.stream.Collectors; - -import io.fabric8.kubernetes.api.model.HasMetadata; -import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.api.reconciler.ResourceDiscriminator; -import io.javaoperatorsdk.operator.sample.complexdependent.ComplexDependentCustomResource; - -public abstract class NamePrefixResourceDiscriminator - implements ResourceDiscriminator { - - private final String prefix; - - protected NamePrefixResourceDiscriminator(String prefix) { - this.prefix = prefix; - } - - @Override - public Optional distinguish(Class resource, ComplexDependentCustomResource primary, - Context context) { - var resources = context.getSecondaryResources(resource); - var filtered = resources.stream().filter(r -> r.getMetadata().getName().startsWith(prefix)) - .collect(Collectors.toList()); - if (filtered.size() > 1) { - throw new IllegalStateException("More resources than expected for" + primary); - } - return filtered.isEmpty() ? Optional.empty() : Optional.of(filtered.get(0)); - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/SecondService.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/SecondService.java deleted file mode 100644 index c939d1c2e6..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/SecondService.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.javaoperatorsdk.operator.sample.complexdependent.dependent; - -import io.fabric8.kubernetes.api.model.Service; -import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; - -@KubernetesDependent(resourceDiscriminator = SecondService.Discriminator.class) -public class SecondService extends BaseService { - - public static final String DISCRIMINATOR_PREFIX = "second"; - - public SecondService() { - super(DISCRIMINATOR_PREFIX); - } - - public static class Discriminator extends NamePrefixResourceDiscriminator { - protected Discriminator() { - super(DISCRIMINATOR_PREFIX); - } - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/SecondStatefulSet.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/SecondStatefulSet.java deleted file mode 100644 index 7a07682c57..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/SecondStatefulSet.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.javaoperatorsdk.operator.sample.complexdependent.dependent; - -import io.fabric8.kubernetes.api.model.apps.StatefulSet; -import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; - -@KubernetesDependent(resourceDiscriminator = SecondStatefulSet.Discriminator.class) -public class SecondStatefulSet extends BaseStatefulSet { - - public static final String DISCRIMINATOR_PREFIX = "second"; - - public SecondStatefulSet() { - super(DISCRIMINATOR_PREFIX); - } - - public static class Discriminator extends NamePrefixResourceDiscriminator { - protected Discriminator() { - super(DISCRIMINATOR_PREFIX); - } - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createupdateeventfilter/CreateUpdateEventFilterTestCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createupdateeventfilter/CreateUpdateEventFilterTestCustomResourceStatus.java deleted file mode 100644 index 6733e1a7cd..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/createupdateeventfilter/CreateUpdateEventFilterTestCustomResourceStatus.java +++ /dev/null @@ -1,7 +0,0 @@ -package io.javaoperatorsdk.operator.sample.createupdateeventfilter; - -import io.javaoperatorsdk.operator.api.ObservedGenerationAwareStatus; - -public class CreateUpdateEventFilterTestCustomResourceStatus extends ObservedGenerationAwareStatus { - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/customfilter/CustomFilteringTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/customfilter/CustomFilteringTestReconciler.java deleted file mode 100644 index 1e42e8e6e1..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/customfilter/CustomFilteringTestReconciler.java +++ /dev/null @@ -1,25 +0,0 @@ -package io.javaoperatorsdk.operator.sample.customfilter; - -import java.util.concurrent.atomic.AtomicInteger; - -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(eventFilters = {CustomFlagFilter.class, CustomFlagFilter2.class}) -public class CustomFilteringTestReconciler implements Reconciler { - - private final AtomicInteger numberOfExecutions = new AtomicInteger(0); - - @Override - public UpdateControl reconcile(CustomFilteringTestResource resource, - Context context) { - numberOfExecutions.incrementAndGet(); - return UpdateControl.noUpdate(); - } - - public int getNumberOfExecutions() { - return numberOfExecutions.get(); - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/customfilter/CustomFilteringTestResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/customfilter/CustomFilteringTestResourceSpec.java deleted file mode 100644 index 8bb1f48054..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/customfilter/CustomFilteringTestResourceSpec.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.javaoperatorsdk.operator.sample.customfilter; - -public class CustomFilteringTestResourceSpec { - - private boolean filter1; - - private boolean filter2; - - public boolean isFilter1() { - return filter1; - } - - public CustomFilteringTestResourceSpec setFilter1(boolean filter1) { - this.filter1 = filter1; - return this; - } - - public boolean isFilter2() { - return filter2; - } - - public CustomFilteringTestResourceSpec setFilter2(boolean filter2) { - this.filter2 = filter2; - return this; - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/customfilter/CustomFlagFilter.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/customfilter/CustomFlagFilter.java deleted file mode 100644 index bba45a44ac..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/customfilter/CustomFlagFilter.java +++ /dev/null @@ -1,13 +0,0 @@ -package io.javaoperatorsdk.operator.sample.customfilter; - -import io.javaoperatorsdk.operator.processing.Controller; -import io.javaoperatorsdk.operator.processing.event.source.controller.ResourceEventFilter; - -public class CustomFlagFilter implements ResourceEventFilter { - - @Override - public boolean acceptChange(Controller configuration, - CustomFilteringTestResource oldResource, CustomFilteringTestResource newResource) { - return newResource.getSpec().isFilter1(); - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/customfilter/CustomFlagFilter2.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/customfilter/CustomFlagFilter2.java deleted file mode 100644 index ae6b5d684f..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/customfilter/CustomFlagFilter2.java +++ /dev/null @@ -1,13 +0,0 @@ -package io.javaoperatorsdk.operator.sample.customfilter; - -import io.javaoperatorsdk.operator.processing.Controller; -import io.javaoperatorsdk.operator.processing.event.source.controller.ResourceEventFilter; - -public class CustomFlagFilter2 implements ResourceEventFilter { - - @Override - public boolean acceptChange(Controller configuration, - CustomFilteringTestResource oldResource, CustomFilteringTestResource newResource) { - return newResource.getSpec().isFilter2(); - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentannotationsecondarymapper/DependentAnnotationSecondaryMapperResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentannotationsecondarymapper/DependentAnnotationSecondaryMapperResourceStatus.java deleted file mode 100644 index 33ea00e819..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentannotationsecondarymapper/DependentAnnotationSecondaryMapperResourceStatus.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.javaoperatorsdk.operator.sample.dependentannotationsecondarymapper; - -public class DependentAnnotationSecondaryMapperResourceStatus { - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentfilter/DependentFilterTestResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentfilter/DependentFilterTestResourceStatus.java deleted file mode 100644 index 99e8d54514..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentfilter/DependentFilterTestResourceStatus.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.javaoperatorsdk.operator.sample.dependentfilter; - -public class DependentFilterTestResourceStatus { - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentresourcecrossref/DependentResourceCrossRefResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentresourcecrossref/DependentResourceCrossRefResourceStatus.java deleted file mode 100644 index aa249a0916..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/dependentresourcecrossref/DependentResourceCrossRefResourceStatus.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.javaoperatorsdk.operator.sample.dependentresourcecrossref; - -public class DependentResourceCrossRefResourceStatus { - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomResourceSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomResourceSpec.java deleted file mode 100644 index 02212957a9..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomResourceSpec.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.javaoperatorsdk.operator.sample.doubleupdate; - -public class DoubleUpdateTestCustomResourceSpec { - - private String value; - - public String getValue() { - return value; - } - - public DoubleUpdateTestCustomResourceSpec setValue(String value) { - this.value = value; - return this; - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomResourceStatus.java deleted file mode 100644 index 3c7b694853..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomResourceStatus.java +++ /dev/null @@ -1,19 +0,0 @@ -package io.javaoperatorsdk.operator.sample.doubleupdate; - -public class DoubleUpdateTestCustomResourceStatus { - - private State state; - - public State getState() { - return state; - } - - public DoubleUpdateTestCustomResourceStatus setState(State state) { - this.state = state; - return this; - } - - public enum State { - SUCCESS, ERROR - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/filter/FilterTestResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/filter/FilterTestResourceStatus.java deleted file mode 100644 index cf0d24aa2c..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/filter/FilterTestResourceStatus.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.javaoperatorsdk.operator.sample.filter; - -public class FilterTestResourceStatus { - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesdependentresourcemanaged/GenericKubernetesDependentManagedReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesdependentresourcemanaged/GenericKubernetesDependentManagedReconciler.java deleted file mode 100644 index 64651ec23e..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/generickubernetesresource/generickubernetesdependentresourcemanaged/GenericKubernetesDependentManagedReconciler.java +++ /dev/null @@ -1,19 +0,0 @@ -package io.javaoperatorsdk.operator.sample.generickubernetesresource.generickubernetesdependentresourcemanaged; - -import io.javaoperatorsdk.operator.api.reconciler.*; -import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; - -@ControllerConfiguration( - dependents = {@Dependent(type = ConfigMapGenericKubernetesDependent.class)}) -public class GenericKubernetesDependentManagedReconciler - implements Reconciler { - - @Override - public UpdateControl reconcile( - GenericKubernetesDependentManagedCustomResource resource, - Context context) { - - return UpdateControl.noUpdate(); - } - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/gracefulstop/GracefulStopTestCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/gracefulstop/GracefulStopTestCustomResourceStatus.java deleted file mode 100644 index f59f5b1163..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/gracefulstop/GracefulStopTestCustomResourceStatus.java +++ /dev/null @@ -1,7 +0,0 @@ -package io.javaoperatorsdk.operator.sample.gracefulstop; - -import io.javaoperatorsdk.operator.api.ObservedGenerationAwareStatus; - -public class GracefulStopTestCustomResourceStatus extends ObservedGenerationAwareStatus { - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/indexdiscriminator/IndexDiscriminatorTestDRConfigMap.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/indexdiscriminator/IndexDiscriminatorTestDRConfigMap.java deleted file mode 100644 index 88dc40f55c..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/indexdiscriminator/IndexDiscriminatorTestDRConfigMap.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.javaoperatorsdk.operator.sample.indexdiscriminator; - -import java.util.HashMap; -import java.util.Map; - -import io.fabric8.kubernetes.api.model.ConfigMap; -import io.fabric8.kubernetes.api.model.ConfigMapBuilder; -import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDNoGCKubernetesDependentResource; -import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; - -@KubernetesDependent -public class IndexDiscriminatorTestDRConfigMap - extends CRUDNoGCKubernetesDependentResource { - - public static final String DATA_KEY = "key"; - private final String suffix; - - public IndexDiscriminatorTestDRConfigMap(String value) { - super(ConfigMap.class); - this.suffix = value; - } - - @Override - protected ConfigMap desired(IndexDiscriminatorTestCustomResource primary, - Context context) { - Map data = new HashMap<>(); - data.put(DATA_KEY, primary.getSpec().getValue()); - - return new ConfigMapBuilder() - .withNewMetadata() - .withName(primary.getMetadata().getName() + suffix) - .withNamespace(primary.getMetadata().getNamespace()) - .endMetadata() - .withData(data) - .build(); - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/indexdiscriminator/IndexDiscriminatorTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/indexdiscriminator/IndexDiscriminatorTestReconciler.java deleted file mode 100644 index 4acda2feee..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/indexdiscriminator/IndexDiscriminatorTestReconciler.java +++ /dev/null @@ -1,104 +0,0 @@ -package io.javaoperatorsdk.operator.sample.indexdiscriminator; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; - -import io.fabric8.kubernetes.api.model.ConfigMap; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; -import io.javaoperatorsdk.operator.api.reconciler.*; -import io.javaoperatorsdk.operator.processing.event.source.EventSource; -import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; -import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; - -@ControllerConfiguration -public class IndexDiscriminatorTestReconciler - implements Reconciler, - Cleaner, - TestExecutionInfoProvider, EventSourceInitializer { - - public static final String FIRST_CONFIG_MAP_SUFFIX_1 = "-1"; - public static final String FIRST_CONFIG_MAP_SUFFIX_2 = "-2"; - public static final String CONFIG_MAP_INDEX_1 = "CONFIG_MAP_INDEX1"; - public static final String CONFIG_MAP_INDEX_2 = "CONFIG_MAP_INDEX2"; - - private final AtomicInteger numberOfExecutions = new AtomicInteger(0); - - private final IndexDiscriminatorTestDRConfigMap firstDependentResourceConfigMap; - private final IndexDiscriminatorTestDRConfigMap secondDependentResourceConfigMap; - - public IndexDiscriminatorTestReconciler() { - firstDependentResourceConfigMap = - new IndexDiscriminatorTestDRConfigMap(FIRST_CONFIG_MAP_SUFFIX_1); - secondDependentResourceConfigMap = - new IndexDiscriminatorTestDRConfigMap(FIRST_CONFIG_MAP_SUFFIX_2); - } - - @Override - public UpdateControl reconcile( - IndexDiscriminatorTestCustomResource resource, - Context context) { - numberOfExecutions.getAndIncrement(); - firstDependentResourceConfigMap.reconcile(resource, context); - secondDependentResourceConfigMap.reconcile(resource, context); - return UpdateControl.noUpdate(); - } - - public int getNumberOfExecutions() { - return numberOfExecutions.get(); - } - - @Override - public Map prepareEventSources( - EventSourceContext context) { - - InformerEventSource eventSource = - new InformerEventSource<>(InformerConfiguration.from(ConfigMap.class, context) - .build(), context); - - eventSource.addIndexer(CONFIG_MAP_INDEX_1, cm -> { - if (cm.getMetadata().getName().endsWith(FIRST_CONFIG_MAP_SUFFIX_1)) { - return List.of(configMapKey(cm)); - } else { - return Collections.emptyList(); - } - }); - eventSource.addIndexer(CONFIG_MAP_INDEX_2, cm -> { - if (cm.getMetadata().getName().endsWith(FIRST_CONFIG_MAP_SUFFIX_2)) { - return List.of(configMapKey(cm)); - } else { - return Collections.emptyList(); - } - }); - - firstDependentResourceConfigMap.configureWith(eventSource); - secondDependentResourceConfigMap.configureWith(eventSource); - - firstDependentResourceConfigMap - .setResourceDiscriminator( - new TestIndexDiscriminator(CONFIG_MAP_INDEX_1, FIRST_CONFIG_MAP_SUFFIX_1)); - secondDependentResourceConfigMap - .setResourceDiscriminator( - new TestIndexDiscriminator(CONFIG_MAP_INDEX_2, FIRST_CONFIG_MAP_SUFFIX_2)); - return EventSourceInitializer.nameEventSources(eventSource); - } - - public static String configMapKey(ConfigMap configMap) { - return configMap.getMetadata().getName() + "#" + configMap.getMetadata().getNamespace(); - } - - public static String configMapKeyFromPrimary(IndexDiscriminatorTestCustomResource primary, - String nameSuffix) { - return primary.getMetadata().getName() + nameSuffix + "#" - + primary.getMetadata().getNamespace(); - } - - @Override - public DeleteControl cleanup(IndexDiscriminatorTestCustomResource resource, - Context context) { - firstDependentResourceConfigMap.delete(resource, context); - secondDependentResourceConfigMap.delete(resource, context); - return DeleteControl.defaultDelete(); - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/indexdiscriminator/IndexDiscriminatorTestSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/indexdiscriminator/IndexDiscriminatorTestSpec.java deleted file mode 100644 index fcedd48abe..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/indexdiscriminator/IndexDiscriminatorTestSpec.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.javaoperatorsdk.operator.sample.indexdiscriminator; - -public class IndexDiscriminatorTestSpec { - - private String value; - - public String getValue() { - return value; - } - - public IndexDiscriminatorTestSpec setValue(String value) { - this.value = value; - return this; - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/indexdiscriminator/IndexDiscriminatorTestStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/indexdiscriminator/IndexDiscriminatorTestStatus.java deleted file mode 100644 index d31c86e8de..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/indexdiscriminator/IndexDiscriminatorTestStatus.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.javaoperatorsdk.operator.sample.indexdiscriminator; - -public class IndexDiscriminatorTestStatus { - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/indexdiscriminator/TestIndexDiscriminator.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/indexdiscriminator/TestIndexDiscriminator.java deleted file mode 100644 index a56e44ced8..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/indexdiscriminator/TestIndexDiscriminator.java +++ /dev/null @@ -1,14 +0,0 @@ -package io.javaoperatorsdk.operator.sample.indexdiscriminator; - -import io.fabric8.kubernetes.api.model.ConfigMap; -import io.javaoperatorsdk.operator.api.reconciler.IndexDiscriminator; - -import static io.javaoperatorsdk.operator.sample.indexdiscriminator.IndexDiscriminatorTestReconciler.configMapKeyFromPrimary; - -public class TestIndexDiscriminator - extends IndexDiscriminator { - - public TestIndexDiscriminator(String indexName, String nameSuffix) { - super(indexName, p -> configMapKeyFromPrimary(p, nameSuffix)); - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestCustomResourceStatus.java deleted file mode 100644 index 79f67c017e..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/kubernetesdependentgarbagecollection/DependentGarbageCollectionTestCustomResourceStatus.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.javaoperatorsdk.operator.sample.kubernetesdependentgarbagecollection; - -public class DependentGarbageCollectionTestCustomResourceStatus { - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/maxinterval/MaxIntervalTestCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/maxinterval/MaxIntervalTestCustomResourceStatus.java deleted file mode 100644 index 5c403febfb..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/maxinterval/MaxIntervalTestCustomResourceStatus.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.javaoperatorsdk.operator.sample.maxinterval; - -public class MaxIntervalTestCustomResourceStatus { - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentresource/MultipleDependentResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentresource/MultipleDependentResourceStatus.java deleted file mode 100644 index bde0468c89..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentresource/MultipleDependentResourceStatus.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.javaoperatorsdk.operator.sample.multipledependentresource; - -public class MultipleDependentResourceStatus { - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/ConfigMap1MultiInformerDiscriminator.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/ConfigMap1MultiInformerDiscriminator.java deleted file mode 100644 index 32cf830bc1..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/ConfigMap1MultiInformerDiscriminator.java +++ /dev/null @@ -1,28 +0,0 @@ -package io.javaoperatorsdk.operator.sample.multipledependentsametypemultiinformer; - -import java.util.Optional; - -import io.fabric8.kubernetes.api.model.ConfigMap; -import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.api.reconciler.ResourceDiscriminator; -import io.javaoperatorsdk.operator.processing.event.ResourceID; -import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; - -import static io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype.MultipleManagedDependentResourceConfigMap1.NAME_SUFFIX; - -public class ConfigMap1MultiInformerDiscriminator - implements - ResourceDiscriminator { - @Override - public Optional distinguish(Class resource, - MultipleManagedDependentResourceMultiInformerCustomResource primary, - Context context) { - InformerEventSource ies = - (InformerEventSource) context - .eventSourceRetriever().getResourceEventSourceFor(ConfigMap.class, - MultipleManagedDependentResourceMultiInformerReconciler.CONFIG_MAP_1_DR); - - return ies.get(new ResourceID(primary.getMetadata().getName() + NAME_SUFFIX, - primary.getMetadata().getNamespace())); - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/ConfigMap2MultiInformerDiscriminator.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/ConfigMap2MultiInformerDiscriminator.java deleted file mode 100644 index cc6a0a656e..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multipledependentsametypemultiinformer/ConfigMap2MultiInformerDiscriminator.java +++ /dev/null @@ -1,28 +0,0 @@ -package io.javaoperatorsdk.operator.sample.multipledependentsametypemultiinformer; - -import java.util.Optional; - -import io.fabric8.kubernetes.api.model.ConfigMap; -import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.api.reconciler.ResourceDiscriminator; -import io.javaoperatorsdk.operator.processing.event.ResourceID; -import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; - -import static io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype.MultipleManagedDependentResourceConfigMap2.NAME_SUFFIX; - -public class ConfigMap2MultiInformerDiscriminator - implements - ResourceDiscriminator { - @Override - public Optional distinguish(Class resource, - MultipleManagedDependentResourceMultiInformerCustomResource primary, - Context context) { - InformerEventSource ies = - (InformerEventSource) context - .eventSourceRetriever().getResourceEventSourceFor(ConfigMap.class, - MultipleManagedDependentResourceMultiInformerReconciler.CONFIG_MAP_2_DR); - - return ies.get(new ResourceID(primary.getMetadata().getName() + NAME_SUFFIX, - primary.getMetadata().getNamespace())); - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/ConfigMap1Discriminator.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/ConfigMap1Discriminator.java deleted file mode 100644 index cc20dfa45e..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/ConfigMap1Discriminator.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype; - -import java.util.Optional; - -import io.fabric8.kubernetes.api.model.ConfigMap; -import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.api.reconciler.ResourceDiscriminator; -import io.javaoperatorsdk.operator.processing.event.ResourceID; -import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; - -import static io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype.MultipleManagedDependentResourceConfigMap1.NAME_SUFFIX; - -public class ConfigMap1Discriminator - implements ResourceDiscriminator { - @Override - public Optional distinguish(Class resource, - MultipleManagedDependentResourceCustomResource primary, - Context context) { - InformerEventSource ies = - (InformerEventSource) context - .eventSourceRetriever().getResourceEventSourceFor(ConfigMap.class); - - return ies.get(new ResourceID(primary.getMetadata().getName() + NAME_SUFFIX, - primary.getMetadata().getNamespace())); - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/ConfigMap2Discriminator.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/ConfigMap2Discriminator.java deleted file mode 100644 index 8bda6afcee..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanageddependentsametype/ConfigMap2Discriminator.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype; - -import java.util.Optional; - -import io.fabric8.kubernetes.api.model.ConfigMap; -import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.api.reconciler.ResourceDiscriminator; -import io.javaoperatorsdk.operator.processing.event.ResourceID; -import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; - -import static io.javaoperatorsdk.operator.sample.multiplemanageddependentsametype.MultipleManagedDependentResourceConfigMap2.NAME_SUFFIX; - -public class ConfigMap2Discriminator - implements ResourceDiscriminator { - @Override - public Optional distinguish(Class resource, - MultipleManagedDependentResourceCustomResource primary, - Context context) { - InformerEventSource ies = - (InformerEventSource) context - .eventSourceRetriever().getResourceEventSourceFor(ConfigMap.class); - - return ies.get(new ResourceID(primary.getMetadata().getName() + NAME_SUFFIX, - primary.getMetadata().getNamespace())); - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanagedexternaldependenttype/ExternalResourceDiscriminator.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanagedexternaldependenttype/ExternalResourceDiscriminator.java deleted file mode 100644 index 5a394113c1..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanagedexternaldependenttype/ExternalResourceDiscriminator.java +++ /dev/null @@ -1,25 +0,0 @@ -package io.javaoperatorsdk.operator.sample.multiplemanagedexternaldependenttype; - -import java.util.Optional; - -import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.api.reconciler.ResourceDiscriminator; -import io.javaoperatorsdk.operator.support.ExternalResource; - -public class ExternalResourceDiscriminator implements - ResourceDiscriminator { - - private final String suffix; - - public ExternalResourceDiscriminator(String suffix) { - this.suffix = suffix; - } - - @Override - public Optional distinguish(Class resource, - MultipleManagedExternalDependentResourceCustomResource primary, - Context context) { - var resources = context.getSecondaryResources(ExternalResource.class); - return resources.stream().filter(r -> r.getId().endsWith(suffix)).findFirst(); - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanagedexternaldependenttype/MultipleManagedExternalDependentResourceReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanagedexternaldependenttype/MultipleManagedExternalDependentResourceReconciler.java deleted file mode 100644 index 349409ec73..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplemanagedexternaldependenttype/MultipleManagedExternalDependentResourceReconciler.java +++ /dev/null @@ -1,68 +0,0 @@ -package io.javaoperatorsdk.operator.sample.multiplemanagedexternaldependenttype; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; - -import io.javaoperatorsdk.operator.api.reconciler.*; -import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; -import io.javaoperatorsdk.operator.processing.event.ResourceID; -import io.javaoperatorsdk.operator.processing.event.source.EventSource; -import io.javaoperatorsdk.operator.processing.event.source.polling.PollingEventSource; -import io.javaoperatorsdk.operator.support.ExternalResource; -import io.javaoperatorsdk.operator.support.ExternalServiceMock; -import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; - -import static io.javaoperatorsdk.operator.sample.multiplemanagedexternaldependenttype.MultipleManagedExternalDependentResourceReconciler.CONFIG_MAP_EVENT_SOURCE; - -@ControllerConfiguration(dependents = { - @Dependent(type = ExternalDependentResource1.class, - useEventSourceWithName = CONFIG_MAP_EVENT_SOURCE), - @Dependent(type = ExternalDependentResource2.class, - useEventSourceWithName = CONFIG_MAP_EVENT_SOURCE) -}) -public class MultipleManagedExternalDependentResourceReconciler - implements Reconciler, - TestExecutionInfoProvider, - EventSourceInitializer { - - public static final String CONFIG_MAP_EVENT_SOURCE = "ConfigMapEventSource"; - protected ExternalServiceMock externalServiceMock = ExternalServiceMock.getInstance(); - private final AtomicInteger numberOfExecutions = new AtomicInteger(0); - - public MultipleManagedExternalDependentResourceReconciler() {} - - @Override - public UpdateControl reconcile( - MultipleManagedExternalDependentResourceCustomResource resource, - Context context) { - numberOfExecutions.getAndIncrement(); - - return UpdateControl.noUpdate(); - } - - public int getNumberOfExecutions() { - return numberOfExecutions.get(); - } - - @Override - public Map prepareEventSources( - EventSourceContext context) { - - PollingEventSource pollingEventSource = - new PollingEventSource<>(() -> { - var lists = externalServiceMock.listResources(); - Map> res = new HashMap<>(); - lists.forEach(er -> { - var resourceId = er.toResourceID(); - res.computeIfAbsent(resourceId, rid -> new HashSet<>()); - res.get(resourceId).add(er); - }); - return res; - }, 1000L, ExternalResource.class, ExternalResource::getId); - - return Map.of(CONFIG_MAP_EVENT_SOURCE, pollingEventSource); - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplesecondaryeventsource/MultipleSecondaryEventSourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplesecondaryeventsource/MultipleSecondaryEventSourceStatus.java deleted file mode 100644 index 2a78bf0531..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/multiplesecondaryeventsource/MultipleSecondaryEventSourceStatus.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.javaoperatorsdk.operator.sample.multiplesecondaryeventsource; - -public class MultipleSecondaryEventSourceStatus { - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/observedgeneration/ObservedGenerationTestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/observedgeneration/ObservedGenerationTestCustomResource.java deleted file mode 100644 index 8a0ede3a5d..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/observedgeneration/ObservedGenerationTestCustomResource.java +++ /dev/null @@ -1,18 +0,0 @@ -package io.javaoperatorsdk.operator.sample.observedgeneration; - -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.Kind; -import io.fabric8.kubernetes.model.annotation.ShortNames; -import io.fabric8.kubernetes.model.annotation.Version; - -@Group("sample.javaoperatorsdk") -@Version("v1") -@Kind("ObservedGenerationTestCustomResource") -@ShortNames("og") -public class ObservedGenerationTestCustomResource - extends CustomResource - implements Namespaced { - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/observedgeneration/ObservedGenerationTestCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/observedgeneration/ObservedGenerationTestCustomResourceStatus.java deleted file mode 100644 index 14071775f3..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/observedgeneration/ObservedGenerationTestCustomResourceStatus.java +++ /dev/null @@ -1,7 +0,0 @@ -package io.javaoperatorsdk.operator.sample.observedgeneration; - -import io.javaoperatorsdk.operator.api.ObservedGenerationAwareStatus; - -public class ObservedGenerationTestCustomResourceStatus extends ObservedGenerationAwareStatus { - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/observedgeneration/ObservedGenerationTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/observedgeneration/ObservedGenerationTestReconciler.java deleted file mode 100644 index 7e2127ec7c..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/observedgeneration/ObservedGenerationTestReconciler.java +++ /dev/null @@ -1,28 +0,0 @@ -package io.javaoperatorsdk.operator.sample.observedgeneration; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -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 -public class ObservedGenerationTestReconciler - implements Reconciler { - - private static final Logger log = LoggerFactory.getLogger(ObservedGenerationTestReconciler.class); - - @Override - public UpdateControl reconcile( - ObservedGenerationTestCustomResource resource, - Context context) { - log.info("Reconcile ObservedGenerationTestCustomResource: {}", - resource.getMetadata().getName()); - if (resource.getStatus() == null) { - resource.setStatus(new ObservedGenerationTestCustomResourceStatus()); - } - return UpdateControl.patchStatus(resource); - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primaryindexer/DependentPrimaryIndexerTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primaryindexer/DependentPrimaryIndexerTestReconciler.java deleted file mode 100644 index 89b2a43700..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primaryindexer/DependentPrimaryIndexerTestReconciler.java +++ /dev/null @@ -1,49 +0,0 @@ -package io.javaoperatorsdk.operator.sample.primaryindexer; - -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import io.fabric8.kubernetes.api.model.ConfigMap; -import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; -import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; -import io.javaoperatorsdk.operator.api.reconciler.Reconciler; -import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; -import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; -import io.javaoperatorsdk.operator.processing.event.ResourceID; -import io.javaoperatorsdk.operator.processing.event.source.IndexerResourceCache; -import io.javaoperatorsdk.operator.processing.event.source.SecondaryToPrimaryMapper; -import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; - -@ControllerConfiguration(dependents = @Dependent( - type = DependentPrimaryIndexerTestReconciler.ReadOnlyConfigMapDependent.class)) -public class DependentPrimaryIndexerTestReconciler extends AbstractPrimaryIndexerTestReconciler - implements - Reconciler { - - public static class ReadOnlyConfigMapDependent - extends KubernetesDependentResource implements - SecondaryToPrimaryMapper { - private IndexerResourceCache cache; - - public ReadOnlyConfigMapDependent() { - super(ConfigMap.class); - } - - @Override - public Set toPrimaryResourceIDs(ConfigMap resource) { - return cache.byIndex(CONFIG_MAP_RELATION_INDEXER, resource.getMetadata().getName()) - .stream() - .map(ResourceID::fromResource) - .collect(Collectors.toSet()); - } - - @Override - public Optional> eventSource( - EventSourceContext context) { - cache = context.getPrimaryCache(); - cache.addIndexer(CONFIG_MAP_RELATION_INDEXER, indexer); - return super.eventSource(context); - } - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondary/ClusterStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondary/ClusterStatus.java deleted file mode 100644 index eac5c48b70..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondary/ClusterStatus.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.javaoperatorsdk.operator.sample.primarytosecondary; - -public class ClusterStatus { - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondary/JobStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondary/JobStatus.java deleted file mode 100644 index b2d7cf6259..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondary/JobStatus.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.javaoperatorsdk.operator.sample.primarytosecondary; - -public class JobStatus { - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondaydependent/ConfigMapDependent.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondaydependent/ConfigMapDependent.java deleted file mode 100644 index d08bc2131f..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/primarytosecondaydependent/ConfigMapDependent.java +++ /dev/null @@ -1,12 +0,0 @@ -package io.javaoperatorsdk.operator.sample.primarytosecondaydependent; - -import io.fabric8.kubernetes.api.model.ConfigMap; -import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; - -public class ConfigMapDependent extends - KubernetesDependentResource { - - public ConfigMapDependent() { - super(ConfigMap.class); - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ratelimit/RateLimitCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ratelimit/RateLimitCustomResourceStatus.java deleted file mode 100644 index 087408fc16..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/ratelimit/RateLimitCustomResourceStatus.java +++ /dev/null @@ -1,7 +0,0 @@ -package io.javaoperatorsdk.operator.sample.ratelimit; - -import io.javaoperatorsdk.operator.api.ObservedGenerationAwareStatus; - -public class RateLimitCustomResourceStatus extends ObservedGenerationAwareStatus { - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/standalonedependent/StandaloneDependentTestCustomResourceStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/standalonedependent/StandaloneDependentTestCustomResourceStatus.java deleted file mode 100644 index 5f12f1ef72..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/standalonedependent/StandaloneDependentTestCustomResourceStatus.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.javaoperatorsdk.operator.sample.standalonedependent; - -public class StandaloneDependentTestCustomResourceStatus { - -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/ConfigMapReconcileCondition.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/ConfigMapReconcileCondition.java deleted file mode 100644 index b3d9d7a541..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/ConfigMapReconcileCondition.java +++ /dev/null @@ -1,19 +0,0 @@ -package io.javaoperatorsdk.operator.sample.workflowallfeature; - -import io.fabric8.kubernetes.api.model.ConfigMap; -import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; -import io.javaoperatorsdk.operator.processing.dependent.workflow.Condition; - -public class ConfigMapReconcileCondition - implements Condition { - - @Override - public boolean isMet( - DependentResource dependentResource, - WorkflowAllFeatureCustomResource primary, - Context context) { - - return primary.getSpec().isCreateConfigMap(); - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/WorkflowAllFeatureStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/WorkflowAllFeatureStatus.java deleted file mode 100644 index 11d0798fca..0000000000 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/WorkflowAllFeatureStatus.java +++ /dev/null @@ -1,15 +0,0 @@ -package io.javaoperatorsdk.operator.sample.workflowallfeature; - -public class WorkflowAllFeatureStatus { - - private Boolean ready; - - public Boolean getReady() { - return ready; - } - - public WorkflowAllFeatureStatus setReady(Boolean ready) { - this.ready = ready; - return this; - } -} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/support/TestUtils.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/support/TestUtils.java index ea3a72043b..952ad75b19 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/support/TestUtils.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/support/TestUtils.java @@ -4,9 +4,9 @@ import java.util.UUID; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.baseapi.simple.TestCustomResource; +import io.javaoperatorsdk.operator.baseapi.simple.TestCustomResourceSpec; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; -import io.javaoperatorsdk.operator.sample.simple.TestCustomResourceSpec; public class TestUtils { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/ComplexDependentCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/ComplexWorkflowCustomResource.java similarity index 62% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/ComplexDependentCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/ComplexWorkflowCustomResource.java index e4a5031a6f..cb48ea8c97 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/ComplexDependentCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/ComplexWorkflowCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.complexdependent; +package io.javaoperatorsdk.operator.workflow.complexdependent; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; @@ -9,6 +9,6 @@ @Group("sample.javaoperatorsdk") @Version("v1") @ShortNames("cdc") -public class ComplexDependentCustomResource - extends CustomResource implements Namespaced { +public class ComplexWorkflowCustomResource + extends CustomResource implements Namespaced { } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ComplexDependentIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/ComplexWorkflowIT.java similarity index 65% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/ComplexDependentIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/ComplexWorkflowIT.java index 3bc7afaa6a..163abe34a7 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ComplexDependentIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/ComplexWorkflowIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.workflow.complexdependent; import java.time.Duration; @@ -12,27 +12,24 @@ import io.fabric8.kubernetes.api.model.apps.StatefulSet; import io.fabric8.kubernetes.client.readiness.Readiness; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.complexdependent.ComplexDependentCustomResource; -import io.javaoperatorsdk.operator.sample.complexdependent.ComplexDependentReconciler; -import io.javaoperatorsdk.operator.sample.complexdependent.ComplexDependentSpec; -import io.javaoperatorsdk.operator.sample.complexdependent.dependent.FirstService; -import io.javaoperatorsdk.operator.sample.complexdependent.dependent.FirstStatefulSet; -import io.javaoperatorsdk.operator.sample.complexdependent.dependent.SecondService; -import io.javaoperatorsdk.operator.sample.complexdependent.dependent.SecondStatefulSet; +import io.javaoperatorsdk.operator.workflow.complexdependent.dependent.FirstService; +import io.javaoperatorsdk.operator.workflow.complexdependent.dependent.FirstStatefulSet; +import io.javaoperatorsdk.operator.workflow.complexdependent.dependent.SecondService; +import io.javaoperatorsdk.operator.workflow.complexdependent.dependent.SecondStatefulSet; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; -class ComplexDependentIT { +class ComplexWorkflowIT { public static final String TEST_RESOURCE_NAME = "test1"; - Logger log = LoggerFactory.getLogger(ComplexDependentIT.class); + Logger log = LoggerFactory.getLogger(ComplexWorkflowIT.class); @RegisterExtension LocallyRunOperatorExtension operator = LocallyRunOperatorExtension.builder() - .withReconciler(new ComplexDependentReconciler()) + .withReconciler(new ComplexWorkflowReconciler()) .build(); @Test @@ -41,10 +38,10 @@ void successfullyReconciles() { await().atMost(Duration.ofSeconds(90)) .untilAsserted(() -> { - var res = operator.get(ComplexDependentCustomResource.class, TEST_RESOURCE_NAME); + var res = operator.get(ComplexWorkflowCustomResource.class, TEST_RESOURCE_NAME); assertThat(res.getStatus()).isNotNull(); assertThat(res.getStatus().getStatus()) - .isEqualTo(ComplexDependentReconciler.RECONCILE_STATUS.READY); + .isEqualTo(ComplexWorkflowReconciler.RECONCILE_STATUS.READY); }); var firstStatefulSet = operator.get(StatefulSet.class, String.format("%s-%s", @@ -63,12 +60,12 @@ void successfullyReconciles() { assertThat(Readiness.isStatefulSetReady(secondStatefulSet)).isTrue(); } - ComplexDependentCustomResource testResource() { - var resource = new ComplexDependentCustomResource(); + ComplexWorkflowCustomResource testResource() { + var resource = new ComplexWorkflowCustomResource(); resource.setMetadata(new ObjectMetaBuilder() .withName(TEST_RESOURCE_NAME) .build()); - resource.setSpec(new ComplexDependentSpec()); + resource.setSpec(new ComplexWorkflowSpec()); resource.getSpec().setProjectId(TEST_RESOURCE_NAME); return resource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/ComplexWorkflowReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/ComplexWorkflowReconciler.java new file mode 100644 index 0000000000..bab93d032e --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/ComplexWorkflowReconciler.java @@ -0,0 +1,80 @@ +package io.javaoperatorsdk.operator.workflow.complexdependent; + +import java.util.List; +import java.util.Objects; + +import io.fabric8.kubernetes.api.model.Service; +import io.fabric8.kubernetes.api.model.apps.StatefulSet; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; +import io.javaoperatorsdk.operator.processing.event.source.EventSource; +import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; +import io.javaoperatorsdk.operator.workflow.complexdependent.dependent.FirstService; +import io.javaoperatorsdk.operator.workflow.complexdependent.dependent.FirstStatefulSet; +import io.javaoperatorsdk.operator.workflow.complexdependent.dependent.SecondService; +import io.javaoperatorsdk.operator.workflow.complexdependent.dependent.SecondStatefulSet; +import io.javaoperatorsdk.operator.workflow.complexdependent.dependent.StatefulSetReadyCondition; + +import static io.javaoperatorsdk.operator.workflow.complexdependent.ComplexWorkflowReconciler.SERVICE_EVENT_SOURCE_NAME; +import static io.javaoperatorsdk.operator.workflow.complexdependent.ComplexWorkflowReconciler.STATEFUL_SET_EVENT_SOURCE_NAME; + +@Workflow(dependents = { + @Dependent(name = "first-svc", type = FirstService.class, + useEventSourceWithName = SERVICE_EVENT_SOURCE_NAME), + @Dependent(name = "second-svc", type = SecondService.class, + useEventSourceWithName = SERVICE_EVENT_SOURCE_NAME), + @Dependent(name = "first", type = FirstStatefulSet.class, + useEventSourceWithName = STATEFUL_SET_EVENT_SOURCE_NAME, + dependsOn = {"first-svc"}, + readyPostcondition = StatefulSetReadyCondition.class), + @Dependent(name = "second", + type = SecondStatefulSet.class, + useEventSourceWithName = STATEFUL_SET_EVENT_SOURCE_NAME, + dependsOn = {"second-svc", "first"}, + readyPostcondition = StatefulSetReadyCondition.class), +}) +@ControllerConfiguration(name = "project-operator") +public class ComplexWorkflowReconciler implements Reconciler { + + public static final String SERVICE_EVENT_SOURCE_NAME = "serviceEventSource"; + public static final String STATEFUL_SET_EVENT_SOURCE_NAME = "statefulSetEventSource"; + + @Override + public UpdateControl reconcile( + ComplexWorkflowCustomResource resource, + Context context) throws Exception { + var ready = context.managedWorkflowAndDependentResourceContext().getWorkflowReconcileResult() + .allDependentResourcesReady(); + + var status = Objects.requireNonNullElseGet(resource.getStatus(), ComplexWorkflowStatus::new); + status.setStatus(ready ? RECONCILE_STATUS.READY : RECONCILE_STATUS.NOT_READY); + resource.setStatus(status); + + return UpdateControl.patchStatus(resource); + } + + @Override + public List> prepareEventSources( + EventSourceContext context) { + InformerEventSource serviceEventSource = + new InformerEventSource<>( + InformerEventSourceConfiguration + .from(Service.class, ComplexWorkflowCustomResource.class) + .withName(SERVICE_EVENT_SOURCE_NAME) + .build(), + context); + InformerEventSource statefulSetEventSource = + new InformerEventSource<>( + InformerEventSourceConfiguration + .from(StatefulSet.class, ComplexWorkflowCustomResource.class) + .withName(STATEFUL_SET_EVENT_SOURCE_NAME) + .build(), + context); + return List.of(serviceEventSource, statefulSetEventSource); + } + + public enum RECONCILE_STATUS { + READY, NOT_READY + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/ComplexWorkflowSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/ComplexWorkflowSpec.java new file mode 100644 index 0000000000..1e8f599c67 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/ComplexWorkflowSpec.java @@ -0,0 +1,14 @@ +package io.javaoperatorsdk.operator.workflow.complexdependent; + +public class ComplexWorkflowSpec { + private String projectId; + + public String getProjectId() { + return projectId; + } + + public ComplexWorkflowSpec setProjectId(String projectId) { + this.projectId = projectId; + return this; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/ComplexWorkflowStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/ComplexWorkflowStatus.java new file mode 100644 index 0000000000..d9b498682a --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/ComplexWorkflowStatus.java @@ -0,0 +1,15 @@ +package io.javaoperatorsdk.operator.workflow.complexdependent; + + +public class ComplexWorkflowStatus { + private ComplexWorkflowReconciler.RECONCILE_STATUS status; + + public ComplexWorkflowReconciler.RECONCILE_STATUS getStatus() { + return status; + } + + public ComplexWorkflowStatus setStatus(ComplexWorkflowReconciler.RECONCILE_STATUS status) { + this.status = status; + return this; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/BaseDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/BaseDependentResource.java similarity index 67% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/BaseDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/BaseDependentResource.java index 08e7e5fe2e..e6bd8462cb 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/BaseDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/BaseDependentResource.java @@ -1,12 +1,12 @@ -package io.javaoperatorsdk.operator.sample.complexdependent.dependent; +package io.javaoperatorsdk.operator.workflow.complexdependent.dependent; import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; -import io.javaoperatorsdk.operator.sample.complexdependent.ComplexDependentCustomResource; +import io.javaoperatorsdk.operator.workflow.complexdependent.ComplexWorkflowCustomResource; public abstract class BaseDependentResource - extends CRUDKubernetesDependentResource { + extends CRUDKubernetesDependentResource { public static final String K8S_NAME = "app.kubernetes.io/name"; protected final String component; @@ -16,11 +16,11 @@ public BaseDependentResource(Class resourceType, String component) { this.component = component; } - protected String name(ComplexDependentCustomResource primary) { + protected String name(ComplexWorkflowCustomResource primary) { return String.format("%s-%s", component, primary.getSpec().getProjectId()); } - protected ObjectMetaBuilder createMeta(ComplexDependentCustomResource primary) { + protected ObjectMetaBuilder createMeta(ComplexWorkflowCustomResource primary) { String name = name(primary); return new ObjectMetaBuilder() .withName(name) diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/BaseService.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/BaseService.java similarity index 64% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/BaseService.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/BaseService.java index 192bc97de9..75a4d7ee03 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/BaseService.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/BaseService.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.complexdependent.dependent; +package io.javaoperatorsdk.operator.workflow.complexdependent.dependent; import java.util.Map; @@ -6,7 +6,7 @@ import io.fabric8.kubernetes.api.model.ServiceBuilder; import io.javaoperatorsdk.operator.ReconcilerUtils; import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.sample.complexdependent.ComplexDependentCustomResource; +import io.javaoperatorsdk.operator.workflow.complexdependent.ComplexWorkflowCustomResource; public abstract class BaseService extends BaseDependentResource { @@ -15,9 +15,10 @@ public BaseService(String component) { } @Override - protected Service desired(ComplexDependentCustomResource primary, - Context context) { - var template = ReconcilerUtils.loadYaml(Service.class, getClass(), "service.yaml"); + protected Service desired(ComplexWorkflowCustomResource primary, + Context context) { + var template = ReconcilerUtils.loadYaml(Service.class, getClass(), + "/io/javaoperatorsdk/operator/workflow/complexdependent/service.yaml"); return new ServiceBuilder(template) .withMetadata(createMeta(primary).build()) diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/BaseStatefulSet.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/BaseStatefulSet.java similarity index 73% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/BaseStatefulSet.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/BaseStatefulSet.java index 0609e8dab7..fe05db1c1b 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/BaseStatefulSet.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/BaseStatefulSet.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.complexdependent.dependent; +package io.javaoperatorsdk.operator.workflow.complexdependent.dependent; import java.util.Map; @@ -6,7 +6,7 @@ import io.fabric8.kubernetes.api.model.apps.StatefulSetBuilder; import io.javaoperatorsdk.operator.ReconcilerUtils; import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.sample.complexdependent.ComplexDependentCustomResource; +import io.javaoperatorsdk.operator.workflow.complexdependent.ComplexWorkflowCustomResource; public abstract class BaseStatefulSet extends BaseDependentResource { public BaseStatefulSet(String component) { @@ -14,9 +14,10 @@ public BaseStatefulSet(String component) { } @Override - protected StatefulSet desired(ComplexDependentCustomResource primary, - Context context) { - var template = ReconcilerUtils.loadYaml(StatefulSet.class, getClass(), "statefulset.yaml"); + protected StatefulSet desired(ComplexWorkflowCustomResource primary, + Context context) { + var template = ReconcilerUtils.loadYaml(StatefulSet.class, getClass(), + "/io/javaoperatorsdk/operator/workflow/complexdependent/statefulset.yaml"); var name = name(primary); var metadata = createMeta(primary).build(); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/FirstService.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/FirstService.java new file mode 100644 index 0000000000..36b1ec4845 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/FirstService.java @@ -0,0 +1,13 @@ +package io.javaoperatorsdk.operator.workflow.complexdependent.dependent; + +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; + +@KubernetesDependent +public class FirstService extends BaseService { + public static final String DISCRIMINATOR_PREFIX = "first"; + + public FirstService() { + super(DISCRIMINATOR_PREFIX); + } + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/FirstStatefulSet.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/FirstStatefulSet.java new file mode 100644 index 0000000000..d9cd2933fd --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/FirstStatefulSet.java @@ -0,0 +1,14 @@ +package io.javaoperatorsdk.operator.workflow.complexdependent.dependent; + +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; + +@KubernetesDependent +public class FirstStatefulSet extends BaseStatefulSet { + + public static final String DISCRIMINATOR_PREFIX = "first"; + + public FirstStatefulSet() { + super(DISCRIMINATOR_PREFIX); + } + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/SecondService.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/SecondService.java new file mode 100644 index 0000000000..1b361ced71 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/SecondService.java @@ -0,0 +1,13 @@ +package io.javaoperatorsdk.operator.workflow.complexdependent.dependent; + +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; + +@KubernetesDependent() +public class SecondService extends BaseService { + + public static final String DISCRIMINATOR_PREFIX = "second"; + + public SecondService() { + super(DISCRIMINATOR_PREFIX); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/SecondStatefulSet.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/SecondStatefulSet.java new file mode 100644 index 0000000000..78ab7953eb --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/SecondStatefulSet.java @@ -0,0 +1,14 @@ +package io.javaoperatorsdk.operator.workflow.complexdependent.dependent; + +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; + +@KubernetesDependent +public class SecondStatefulSet extends BaseStatefulSet { + + public static final String DISCRIMINATOR_PREFIX = "second"; + + public SecondStatefulSet() { + super(DISCRIMINATOR_PREFIX); + } + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/StatefulSetReadyCondition.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/StatefulSetReadyCondition.java similarity index 58% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/StatefulSetReadyCondition.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/StatefulSetReadyCondition.java index 894cab310a..1116bd7f1d 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/complexdependent/dependent/StatefulSetReadyCondition.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/complexdependent/dependent/StatefulSetReadyCondition.java @@ -1,19 +1,19 @@ -package io.javaoperatorsdk.operator.sample.complexdependent.dependent; +package io.javaoperatorsdk.operator.workflow.complexdependent.dependent; import io.fabric8.kubernetes.api.model.apps.StatefulSet; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; import io.javaoperatorsdk.operator.processing.dependent.workflow.Condition; -import io.javaoperatorsdk.operator.sample.complexdependent.ComplexDependentCustomResource; +import io.javaoperatorsdk.operator.workflow.complexdependent.ComplexWorkflowCustomResource; public class StatefulSetReadyCondition - implements Condition { + implements Condition { @Override public boolean isMet( - DependentResource dependentResource, - ComplexDependentCustomResource primary, - Context context) { + DependentResource dependentResource, + ComplexWorkflowCustomResource primary, + Context context) { return dependentResource.getSecondaryResource(primary, context).map(secondary -> { var readyReplicas = secondary.getStatus().getReadyReplicas(); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/crdpresentactivation/CRDPresentActivationConditionIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/crdpresentactivation/CRDPresentActivationConditionIT.java new file mode 100644 index 0000000000..85cb3aa6c5 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/crdpresentactivation/CRDPresentActivationConditionIT.java @@ -0,0 +1,67 @@ +package io.javaoperatorsdk.operator.workflow.crdpresentactivation; + +import java.time.Duration; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinition; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public class CRDPresentActivationConditionIT { + + public static final String TEST_1 = "test1"; + public static final String CRD_NAME = + "crdpresentactivationdependentcustomresources.sample.javaoperatorsdk"; + + @RegisterExtension + LocallyRunOperatorExtension extension = + LocallyRunOperatorExtension.builder() + .withReconciler(new CRDPresentActivationReconciler()) + .build(); + + + @Test + void resourceCreatedOnlyIfCRDPresent() { + // deleted so test can be repeated + extension.getKubernetesClient().resources(CustomResourceDefinition.class) + .withName(CRD_NAME).delete(); + + var resource = extension.create(testResource()); + + await().pollDelay(Duration.ofMillis(300)).untilAsserted(() -> { + var crd = extension.getKubernetesClient().resources(CustomResourceDefinition.class) + .withName(CRD_NAME).get(); + assertThat(crd).isNull(); + + var dr = extension.get(CRDPresentActivationDependentCustomResource.class, TEST_1); + assertThat(dr).isNull(); + }); + + LocallyRunOperatorExtension.applyCrd(CRDPresentActivationDependentCustomResource.class, + extension.getKubernetesClient()); + + resource.getMetadata().setAnnotations(Map.of("sample", "value")); + extension.replace(resource); + + await().pollDelay(Duration.ofMillis(300)).untilAsserted(() -> { + var cm = extension.get(CRDPresentActivationDependentCustomResource.class, TEST_1); + assertThat(cm).isNull(); + }); + + } + + CRDPresentActivationCustomResource testResource() { + var res = new CRDPresentActivationCustomResource(); + res.setMetadata(new ObjectMetaBuilder() + .withName(TEST_1) + .build()); + return res; + } + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/customfilter/CustomFilteringTestResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/crdpresentactivation/CRDPresentActivationCustomResource.java similarity index 65% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/customfilter/CustomFilteringTestResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/crdpresentactivation/CRDPresentActivationCustomResource.java index dec7b6c40a..5b8dc2f704 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/customfilter/CustomFilteringTestResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/crdpresentactivation/CRDPresentActivationCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.customfilter; +package io.javaoperatorsdk.operator.workflow.crdpresentactivation; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; @@ -8,8 +8,10 @@ @Group("sample.javaoperatorsdk") @Version("v1") -@ShortNames("cft") -public class CustomFilteringTestResource - extends CustomResource +@ShortNames("crdp") +public class CRDPresentActivationCustomResource + extends CustomResource implements Namespaced { + + } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/crdpresentactivation/CRDPresentActivationDependent.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/crdpresentactivation/CRDPresentActivationDependent.java new file mode 100644 index 0000000000..fdfcda1700 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/crdpresentactivation/CRDPresentActivationDependent.java @@ -0,0 +1,26 @@ +package io.javaoperatorsdk.operator.workflow.crdpresentactivation; + +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDNoGCKubernetesDependentResource; + +public class CRDPresentActivationDependent + extends + CRUDNoGCKubernetesDependentResource { + + public CRDPresentActivationDependent() { + super(CRDPresentActivationDependentCustomResource.class); + } + + @Override + protected CRDPresentActivationDependentCustomResource desired( + CRDPresentActivationCustomResource primary, + Context context) { + var res = new CRDPresentActivationDependentCustomResource(); + res.setMetadata(new ObjectMetaBuilder() + .withName(primary.getMetadata().getName()) + .withNamespace(primary.getMetadata().getNamespace()) + .build()); + return res; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/crdpresentactivation/CRDPresentActivationDependentCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/crdpresentactivation/CRDPresentActivationDependentCustomResource.java new file mode 100644 index 0000000000..18280ee6b3 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/crdpresentactivation/CRDPresentActivationDependentCustomResource.java @@ -0,0 +1,16 @@ +package io.javaoperatorsdk.operator.workflow.crdpresentactivation; + +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("sample.javaoperatorsdk") +@Version("v1") +@ShortNames("addp") +public class CRDPresentActivationDependentCustomResource extends CustomResource + implements Namespaced { + + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/crdpresentactivation/CRDPresentActivationReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/crdpresentactivation/CRDPresentActivationReconciler.java new file mode 100644 index 0000000000..9cc05eaddc --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/crdpresentactivation/CRDPresentActivationReconciler.java @@ -0,0 +1,30 @@ +package io.javaoperatorsdk.operator.workflow.crdpresentactivation; + +import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; +import io.javaoperatorsdk.operator.processing.dependent.workflow.CRDPresentActivationCondition; + +@Workflow(dependents = { + @Dependent(type = CRDPresentActivationDependent.class, + activationCondition = CRDPresentActivationCondition.class), +}) +// to trigger reconciliation with metadata change +@ControllerConfiguration(generationAwareEventProcessing = false) +public class CRDPresentActivationReconciler + implements Reconciler, + Cleaner { + + @Override + public UpdateControl reconcile( + CRDPresentActivationCustomResource resource, + Context context) { + + return UpdateControl.noUpdate(); + } + + @Override + public DeleteControl cleanup(CRDPresentActivationCustomResource resource, + Context context) { + return DeleteControl.defaultDelete(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/getnonactivesecondary/ConfigMapDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/getnonactivesecondary/ConfigMapDependentResource.java new file mode 100644 index 0000000000..0c1bdd5900 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/getnonactivesecondary/ConfigMapDependentResource.java @@ -0,0 +1,28 @@ +package io.javaoperatorsdk.operator.workflow.getnonactivesecondary; + + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; + +public class ConfigMapDependentResource + extends CRUDKubernetesDependentResource { + + public static final String DATA_KEY = "data"; + + public ConfigMapDependentResource() { + super(ConfigMap.class); + } + + @Override + protected ConfigMap desired(GetNonActiveSecondaryCustomResource primary, + Context context) { + ConfigMap configMap = new ConfigMap(); + configMap.setMetadata(new ObjectMetaBuilder() + .withName(primary.getMetadata().getName()) + .withNamespace(primary.getMetadata().getNamespace()) + .build()); + return configMap; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/getnonactivesecondary/FalseActivationCondition.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/getnonactivesecondary/FalseActivationCondition.java new file mode 100644 index 0000000000..fde69215bc --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/getnonactivesecondary/FalseActivationCondition.java @@ -0,0 +1,17 @@ +package io.javaoperatorsdk.operator.workflow.getnonactivesecondary; + +import io.fabric8.openshift.api.model.Route; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; +import io.javaoperatorsdk.operator.processing.dependent.workflow.Condition; + +public class FalseActivationCondition + implements Condition { + @Override + public boolean isMet( + DependentResource dependentResource, + GetNonActiveSecondaryCustomResource primary, + Context context) { + return false; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/getnonactivesecondary/GetNonActiveSecondaryCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/getnonactivesecondary/GetNonActiveSecondaryCustomResource.java new file mode 100644 index 0000000000..fddcd9fe75 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/getnonactivesecondary/GetNonActiveSecondaryCustomResource.java @@ -0,0 +1,17 @@ +package io.javaoperatorsdk.operator.workflow.getnonactivesecondary; + +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("sample.javaoperatorsdk") +@Version("v1") +@ShortNames("gnas") +public class GetNonActiveSecondaryCustomResource + extends CustomResource + implements Namespaced { + + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/getnonactivesecondary/RouteDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/getnonactivesecondary/RouteDependentResource.java new file mode 100644 index 0000000000..c7d1b9a1b1 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/getnonactivesecondary/RouteDependentResource.java @@ -0,0 +1,27 @@ +package io.javaoperatorsdk.operator.workflow.getnonactivesecondary; + +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.fabric8.openshift.api.model.Route; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; + +public class RouteDependentResource + extends CRUDKubernetesDependentResource { + + public RouteDependentResource() { + super(Route.class); + } + + @Override + protected Route desired(GetNonActiveSecondaryCustomResource primary, + Context context) { + // basically does not matter since this should not be called + Route route = new Route(); + route.setMetadata(new ObjectMetaBuilder() + .withName(primary.getMetadata().getName()) + .withNamespace(primary.getMetadata().getNamespace()) + .build()); + + return route; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/getnonactivesecondary/WorkflowActivationConditionIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/getnonactivesecondary/WorkflowActivationConditionIT.java new file mode 100644 index 0000000000..c2c073df88 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/getnonactivesecondary/WorkflowActivationConditionIT.java @@ -0,0 +1,40 @@ +package io.javaoperatorsdk.operator.workflow.getnonactivesecondary; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public class WorkflowActivationConditionIT { + + public static final String TEST_RESOURCE_NAME = "test1"; + + @RegisterExtension + LocallyRunOperatorExtension extension = + LocallyRunOperatorExtension.builder() + .withReconciler(WorkflowActivationConditionReconciler.class) + .build(); + + @Test + void reconciledOnVanillaKubernetesDespiteRouteInWorkflow() { + extension.create(testResource()); + + await().untilAsserted(() -> { + assertThat(extension.getReconcilerOfType(WorkflowActivationConditionReconciler.class) + .getNumberOfReconciliationExecution()).isEqualTo(1); + }); + } + + private GetNonActiveSecondaryCustomResource testResource() { + var res = new GetNonActiveSecondaryCustomResource(); + res.setMetadata(new ObjectMetaBuilder() + .withName(TEST_RESOURCE_NAME) + .build()); + return res; + } + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/getnonactivesecondary/WorkflowActivationConditionReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/getnonactivesecondary/WorkflowActivationConditionReconciler.java new file mode 100644 index 0000000000..2d2d39274d --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/getnonactivesecondary/WorkflowActivationConditionReconciler.java @@ -0,0 +1,40 @@ +package io.javaoperatorsdk.operator.workflow.getnonactivesecondary; + +import java.util.concurrent.atomic.AtomicInteger; + +import io.fabric8.openshift.api.model.Route; +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 = ConfigMapDependentResource.class), + @Dependent(type = RouteDependentResource.class, + activationCondition = FalseActivationCondition.class) +}) +@ControllerConfiguration +public class WorkflowActivationConditionReconciler + implements Reconciler { + + private final AtomicInteger numberOfReconciliationExecution = new AtomicInteger(0); + + @Override + public UpdateControl reconcile( + GetNonActiveSecondaryCustomResource resource, + Context context) { + + // should not throw an exception even if the condition is false + var route = context.getSecondaryResource(Route.class); + + numberOfReconciliationExecution.incrementAndGet(); + + return UpdateControl.noUpdate(); + } + + public int getNumberOfReconciliationExecution() { + return numberOfReconciliationExecution.get(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/manageddependentdeletecondition/ConfigMapDependent.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/manageddependentdeletecondition/ConfigMapDependent.java similarity index 92% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/manageddependentdeletecondition/ConfigMapDependent.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/manageddependentdeletecondition/ConfigMapDependent.java index 63791417f6..af70b6842a 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/manageddependentdeletecondition/ConfigMapDependent.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/manageddependentdeletecondition/ConfigMapDependent.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.manageddependentdeletecondition; +package io.javaoperatorsdk.operator.workflow.manageddependentdeletecondition; import java.util.Map; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/manageddependentdeletecondition/ManagedDependentDefaultDeleteConditionCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/manageddependentdeletecondition/ManagedDependentDefaultDeleteConditionCustomResource.java similarity index 85% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/manageddependentdeletecondition/ManagedDependentDefaultDeleteConditionCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/manageddependentdeletecondition/ManagedDependentDefaultDeleteConditionCustomResource.java index 0922e8977e..01b995c061 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/manageddependentdeletecondition/ManagedDependentDefaultDeleteConditionCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/manageddependentdeletecondition/ManagedDependentDefaultDeleteConditionCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.manageddependentdeletecondition; +package io.javaoperatorsdk.operator.workflow.manageddependentdeletecondition; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/manageddependentdeletecondition/ManagedDependentDefaultDeleteConditionReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/manageddependentdeletecondition/ManagedDependentDefaultDeleteConditionReconciler.java similarity index 89% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/manageddependentdeletecondition/ManagedDependentDefaultDeleteConditionReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/manageddependentdeletecondition/ManagedDependentDefaultDeleteConditionReconciler.java index 8ef1035e9b..530f9b8146 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/manageddependentdeletecondition/ManagedDependentDefaultDeleteConditionReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/manageddependentdeletecondition/ManagedDependentDefaultDeleteConditionReconciler.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.manageddependentdeletecondition; +package io.javaoperatorsdk.operator.workflow.manageddependentdeletecondition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -7,11 +7,12 @@ import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; import io.javaoperatorsdk.operator.processing.dependent.workflow.KubernetesResourceDeletedCondition; -@ControllerConfiguration(dependents = { +@Workflow(dependents = { @Dependent(name = "ConfigMap", type = ConfigMapDependent.class), @Dependent(type = SecretDependent.class, dependsOn = "ConfigMap", deletePostcondition = KubernetesResourceDeletedCondition.class) }) +@ControllerConfiguration public class ManagedDependentDefaultDeleteConditionReconciler implements Reconciler { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ManagedDependentDeleteConditionIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/manageddependentdeletecondition/ManagedDependentDeleteConditionIT.java similarity index 88% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/ManagedDependentDeleteConditionIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/manageddependentdeletecondition/ManagedDependentDeleteConditionIT.java index b2ef89f0f9..4d688bf606 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/ManagedDependentDeleteConditionIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/manageddependentdeletecondition/ManagedDependentDeleteConditionIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.workflow.manageddependentdeletecondition; import java.time.Duration; import java.util.Set; @@ -10,8 +10,6 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.api.model.Secret; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.manageddependentdeletecondition.ManagedDependentDefaultDeleteConditionCustomResource; -import io.javaoperatorsdk.operator.sample.manageddependentdeletecondition.ManagedDependentDefaultDeleteConditionReconciler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/manageddependentdeletecondition/SecretDependent.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/manageddependentdeletecondition/SecretDependent.java similarity index 93% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/manageddependentdeletecondition/SecretDependent.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/manageddependentdeletecondition/SecretDependent.java index d1af07a2a5..6add6bf93b 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/manageddependentdeletecondition/SecretDependent.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/manageddependentdeletecondition/SecretDependent.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.manageddependentdeletecondition; +package io.javaoperatorsdk.operator.workflow.manageddependentdeletecondition; import java.nio.charset.StandardCharsets; import java.util.Base64; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/ActivationCondition.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/ActivationCondition.java new file mode 100644 index 0000000000..063bb6b72c --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/ActivationCondition.java @@ -0,0 +1,20 @@ +package io.javaoperatorsdk.operator.workflow.multipledependentwithactivation; + +import io.fabric8.openshift.api.model.Route; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; +import io.javaoperatorsdk.operator.processing.dependent.workflow.Condition; + +public class ActivationCondition + implements Condition { + + public static volatile boolean MET = false; + + @Override + public boolean isMet( + DependentResource dependentResource, + MultipleDependentActivationCustomResource primary, + Context context) { + return MET; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/ConfigMapDependentResource1.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/ConfigMapDependentResource1.java new file mode 100644 index 0000000000..a3198a3ca3 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/ConfigMapDependentResource1.java @@ -0,0 +1,35 @@ +package io.javaoperatorsdk.operator.workflow.multipledependentwithactivation; + +import java.util.Map; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.api.config.informer.Informer; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDNoGCKubernetesDependentResource; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; + +@KubernetesDependent(informer = @Informer(name = "configMapInformer")) +public class ConfigMapDependentResource1 + extends + CRUDNoGCKubernetesDependentResource { + + public static final String DATA_KEY = "data"; + public static final String SUFFIX = "1"; + + public ConfigMapDependentResource1() { + super(ConfigMap.class); + } + + @Override + protected ConfigMap desired(MultipleDependentActivationCustomResource primary, + Context context) { + ConfigMap configMap = new ConfigMap(); + configMap.setMetadata(new ObjectMetaBuilder() + .withName(primary.getMetadata().getName() + SUFFIX) + .withNamespace(primary.getMetadata().getNamespace()) + .build()); + configMap.setData(Map.of(DATA_KEY, primary.getSpec().getValue() + SUFFIX)); + return configMap; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/ConfigMapDependentResource2.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/ConfigMapDependentResource2.java new file mode 100644 index 0000000000..5fcead39a2 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/ConfigMapDependentResource2.java @@ -0,0 +1,35 @@ +package io.javaoperatorsdk.operator.workflow.multipledependentwithactivation; + +import java.util.Map; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.api.config.informer.Informer; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDNoGCKubernetesDependentResource; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; + +@KubernetesDependent(informer = @Informer(name = "configMapInformer")) +public class ConfigMapDependentResource2 + extends + CRUDNoGCKubernetesDependentResource { + + public static final String DATA_KEY = "data"; + public static final String SUFFIX = "2"; + + public ConfigMapDependentResource2() { + super(ConfigMap.class); + } + + @Override + protected ConfigMap desired(MultipleDependentActivationCustomResource primary, + Context context) { + ConfigMap configMap = new ConfigMap(); + configMap.setMetadata(new ObjectMetaBuilder() + .withName(primary.getMetadata().getName() + SUFFIX) + .withNamespace(primary.getMetadata().getNamespace()) + .build()); + configMap.setData(Map.of(DATA_KEY, primary.getSpec().getValue() + SUFFIX)); + return configMap; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/MultipleDependentActivationCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/MultipleDependentActivationCustomResource.java new file mode 100644 index 0000000000..1e99c1c4b1 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/MultipleDependentActivationCustomResource.java @@ -0,0 +1,17 @@ +package io.javaoperatorsdk.operator.workflow.multipledependentwithactivation; + +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("sample.javaoperatorsdk") +@Version("v1") +@ShortNames("mdar") +public class MultipleDependentActivationCustomResource + extends CustomResource + implements Namespaced { + + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/MultipleDependentActivationReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/MultipleDependentActivationReconciler.java new file mode 100644 index 0000000000..14e3ed9811 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/MultipleDependentActivationReconciler.java @@ -0,0 +1,34 @@ +package io.javaoperatorsdk.operator.workflow.multipledependentwithactivation; + +import java.util.concurrent.atomic.AtomicInteger; + +import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; + +@Workflow(dependents = { + @Dependent(type = ConfigMapDependentResource1.class, + activationCondition = ActivationCondition.class), + @Dependent(type = ConfigMapDependentResource2.class, + activationCondition = ActivationCondition.class), + @Dependent(type = SecretDependentResource.class) +}) +@ControllerConfiguration +public class MultipleDependentActivationReconciler + implements Reconciler { + + private final AtomicInteger numberOfReconciliationExecution = new AtomicInteger(0); + + @Override + public UpdateControl reconcile( + MultipleDependentActivationCustomResource resource, + Context context) { + + numberOfReconciliationExecution.incrementAndGet(); + + return UpdateControl.noUpdate(); + } + + public int getNumberOfReconciliationExecution() { + return numberOfReconciliationExecution.get(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/MultipleDependentActivationSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/MultipleDependentActivationSpec.java new file mode 100644 index 0000000000..76f39911fe --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/MultipleDependentActivationSpec.java @@ -0,0 +1,14 @@ +package io.javaoperatorsdk.operator.workflow.multipledependentwithactivation; + +public class MultipleDependentActivationSpec { + + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/MultipleDependentWithActivationIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/MultipleDependentWithActivationIT.java new file mode 100644 index 0000000000..b82fc369f9 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/MultipleDependentWithActivationIT.java @@ -0,0 +1,75 @@ +package io.javaoperatorsdk.operator.workflow.multipledependentwithactivation; + +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.ObjectMetaBuilder; +import io.fabric8.kubernetes.api.model.Secret; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public class MultipleDependentWithActivationIT { + + public static final String INITIAL_VALUE = "initial_value"; + public static final String CHANGED_VALUE = "changed_value"; + public static final String TEST_RESOURCE_NAME = "test1"; + + @RegisterExtension + LocallyRunOperatorExtension extension = + LocallyRunOperatorExtension.builder() + .withReconciler(new MultipleDependentActivationReconciler()) + .build(); + + @Test + void bothDependentsWithActivationAreHandled() { + var resource = extension.create(testResource()); + + await().untilAsserted(() -> { + var cm1 = + extension.get(ConfigMap.class, TEST_RESOURCE_NAME + ConfigMapDependentResource1.SUFFIX); + var cm2 = + extension.get(ConfigMap.class, TEST_RESOURCE_NAME + ConfigMapDependentResource2.SUFFIX); + var secret = extension.get(Secret.class, TEST_RESOURCE_NAME); + assertThat(secret).isNotNull(); + assertThat(cm1).isNull(); + assertThat(cm2).isNull(); + }); + + ActivationCondition.MET = true; + resource.getSpec().setValue(CHANGED_VALUE); + extension.replace(resource); + + await().untilAsserted(() -> { + var cm1 = + extension.get(ConfigMap.class, TEST_RESOURCE_NAME + ConfigMapDependentResource1.SUFFIX); + var cm2 = + extension.get(ConfigMap.class, TEST_RESOURCE_NAME + ConfigMapDependentResource2.SUFFIX); + var secret = extension.get(Secret.class, TEST_RESOURCE_NAME); + + assertThat(secret).isNotNull(); + assertThat(cm1).isNotNull(); + assertThat(cm2).isNotNull(); + assertThat(cm1.getData()).containsEntry(ConfigMapDependentResource1.DATA_KEY, + CHANGED_VALUE + ConfigMapDependentResource1.SUFFIX); + assertThat(cm2.getData()).containsEntry(ConfigMapDependentResource2.DATA_KEY, + CHANGED_VALUE + ConfigMapDependentResource2.SUFFIX); + }); + + } + + MultipleDependentActivationCustomResource testResource() { + var res = new MultipleDependentActivationCustomResource(); + res.setMetadata(new ObjectMetaBuilder() + .withName(TEST_RESOURCE_NAME) + .build()); + res.setSpec(new MultipleDependentActivationSpec()); + res.getSpec().setValue(INITIAL_VALUE); + + return res; + } + + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/SecretDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/SecretDependentResource.java new file mode 100644 index 0000000000..6340d07b58 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/multipledependentwithactivation/SecretDependentResource.java @@ -0,0 +1,31 @@ +package io.javaoperatorsdk.operator.workflow.multipledependentwithactivation; + +import java.util.Base64; +import java.util.Map; + +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.fabric8.kubernetes.api.model.Secret; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; + +public class SecretDependentResource + extends CRUDKubernetesDependentResource { + + public SecretDependentResource() { + super(Secret.class); + } + + @Override + protected Secret desired(MultipleDependentActivationCustomResource primary, + Context context) { + // basically does not matter since this should not be called + Secret secret = new Secret(); + secret.setMetadata(new ObjectMetaBuilder() + .withName(primary.getMetadata().getName()) + .withNamespace(primary.getMetadata().getNamespace()) + .build()); + secret.setData(Map.of("data", + Base64.getEncoder().encodeToString(primary.getSpec().getValue().getBytes()))); + return secret; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/orderedmanageddependent/ConfigMapDependentResource1.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/orderedmanageddependent/ConfigMapDependentResource1.java similarity index 71% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/orderedmanageddependent/ConfigMapDependentResource1.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/orderedmanageddependent/ConfigMapDependentResource1.java index bf8d60d9c4..0478fe4248 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/orderedmanageddependent/ConfigMapDependentResource1.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/orderedmanageddependent/ConfigMapDependentResource1.java @@ -1,19 +1,17 @@ -package io.javaoperatorsdk.operator.sample.orderedmanageddependent; +package io.javaoperatorsdk.operator.workflow.orderedmanageddependent; import java.util.HashMap; import java.util.Map; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMeta; +import io.javaoperatorsdk.operator.api.config.informer.Informer; import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.api.reconciler.ResourceIDMatcherDiscriminator; import io.javaoperatorsdk.operator.api.reconciler.dependent.ReconcileResult; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; -import io.javaoperatorsdk.operator.processing.event.ResourceID; -@KubernetesDependent(labelSelector = "dependent = cm1", - resourceDiscriminator = ConfigMapDependentResource1.CM1ResourceDiscriminator.class) +@KubernetesDependent(informer = @Informer(labelSelector = "dependent = cm1")) public class ConfigMapDependentResource1 extends CRUDKubernetesDependentResource { @@ -45,11 +43,4 @@ protected ConfigMap desired(OrderedManagedDependentCustomResource primary, return configMap; } - public static class CM1ResourceDiscriminator - extends ResourceIDMatcherDiscriminator { - public CM1ResourceDiscriminator() { - super(p -> new ResourceID(p.getMetadata().getName() + "1", p.getMetadata().getNamespace())); - } - } - } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/orderedmanageddependent/ConfigMapDependentResource2.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/orderedmanageddependent/ConfigMapDependentResource2.java similarity index 71% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/orderedmanageddependent/ConfigMapDependentResource2.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/orderedmanageddependent/ConfigMapDependentResource2.java index 2b17d615b9..efbd6ec450 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/orderedmanageddependent/ConfigMapDependentResource2.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/orderedmanageddependent/ConfigMapDependentResource2.java @@ -1,19 +1,17 @@ -package io.javaoperatorsdk.operator.sample.orderedmanageddependent; +package io.javaoperatorsdk.operator.workflow.orderedmanageddependent; import java.util.HashMap; import java.util.Map; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMeta; +import io.javaoperatorsdk.operator.api.config.informer.Informer; import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.api.reconciler.ResourceIDMatcherDiscriminator; import io.javaoperatorsdk.operator.api.reconciler.dependent.ReconcileResult; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; -import io.javaoperatorsdk.operator.processing.event.ResourceID; -@KubernetesDependent(labelSelector = "dependent = cm2", - resourceDiscriminator = ConfigMapDependentResource2.CM2ResourceDiscriminator.class) +@KubernetesDependent(informer = @Informer(labelSelector = "dependent = cm2")) public class ConfigMapDependentResource2 extends CRUDKubernetesDependentResource { @@ -45,11 +43,4 @@ protected ConfigMap desired(OrderedManagedDependentCustomResource primary, return configMap; } - public static class CM2ResourceDiscriminator - extends ResourceIDMatcherDiscriminator { - public CM2ResourceDiscriminator() { - super(p -> new ResourceID(p.getMetadata().getName() + "2", p.getMetadata().getNamespace())); - } - } - } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/orderedmanageddependent/OrderedManagedDependentCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/orderedmanageddependent/OrderedManagedDependentCustomResource.java similarity index 88% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/orderedmanageddependent/OrderedManagedDependentCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/orderedmanageddependent/OrderedManagedDependentCustomResource.java index 1e33bb2a5b..b73f92565d 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/orderedmanageddependent/OrderedManagedDependentCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/orderedmanageddependent/OrderedManagedDependentCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.orderedmanageddependent; +package io.javaoperatorsdk.operator.workflow.orderedmanageddependent; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/OrderedManagedDependentIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/orderedmanageddependent/OrderedManagedDependentIT.java similarity index 76% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/OrderedManagedDependentIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/orderedmanageddependent/OrderedManagedDependentIT.java index e7bb8fdd14..73ab6e65f6 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/OrderedManagedDependentIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/orderedmanageddependent/OrderedManagedDependentIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.workflow.orderedmanageddependent; import java.time.Duration; @@ -7,10 +7,6 @@ import io.fabric8.kubernetes.api.model.ObjectMeta; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.orderedmanageddependent.ConfigMapDependentResource1; -import io.javaoperatorsdk.operator.sample.orderedmanageddependent.ConfigMapDependentResource2; -import io.javaoperatorsdk.operator.sample.orderedmanageddependent.OrderedManagedDependentCustomResource; -import io.javaoperatorsdk.operator.sample.orderedmanageddependent.OrderedManagedDependentTestReconciler; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/orderedmanageddependent/OrderedManagedDependentTestReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/orderedmanageddependent/OrderedManagedDependentTestReconciler.java similarity index 61% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/orderedmanageddependent/OrderedManagedDependentTestReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/orderedmanageddependent/OrderedManagedDependentTestReconciler.java index f7172ca44d..4336d940b0 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/orderedmanageddependent/OrderedManagedDependentTestReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/orderedmanageddependent/OrderedManagedDependentTestReconciler.java @@ -1,24 +1,21 @@ -package io.javaoperatorsdk.operator.sample.orderedmanageddependent; +package io.javaoperatorsdk.operator.workflow.orderedmanageddependent; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; -import io.javaoperatorsdk.operator.api.reconciler.Constants; -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.config.informer.Informer; +import io.javaoperatorsdk.operator.api.reconciler.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; +@Workflow(dependents = { + @Dependent(type = ConfigMapDependentResource1.class, name = "cm1"), + @Dependent(type = ConfigMapDependentResource2.class, dependsOn = "cm1") +}) @ControllerConfiguration( - namespaces = Constants.WATCH_CURRENT_NAMESPACE, - dependents = { - @Dependent(type = ConfigMapDependentResource1.class, name = "cm1"), - @Dependent(type = ConfigMapDependentResource2.class, dependsOn = "cm1") - }) + informer = @Informer(namespaces = Constants.WATCH_CURRENT_NAMESPACE)) public class OrderedManagedDependentTestReconciler implements Reconciler, TestExecutionInfoProvider { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcleanup/ConfigMapDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcleanup/ConfigMapDependentResource.java similarity index 93% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcleanup/ConfigMapDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcleanup/ConfigMapDependentResource.java index 241bff64ce..a909a3a706 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcleanup/ConfigMapDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcleanup/ConfigMapDependentResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.workflowactivationcleanup; +package io.javaoperatorsdk.operator.workflow.workflowactivationcleanup; import java.util.Map; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcleanup/TestActivcationCondition.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcleanup/TestActivcationCondition.java similarity index 90% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcleanup/TestActivcationCondition.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcleanup/TestActivcationCondition.java index ff215b7d72..fd92065f15 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcleanup/TestActivcationCondition.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcleanup/TestActivcationCondition.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.workflowactivationcleanup; +package io.javaoperatorsdk.operator.workflow.workflowactivationcleanup; import io.fabric8.kubernetes.api.model.ConfigMap; import io.javaoperatorsdk.operator.api.reconciler.Context; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcleanup/WorkflowActivationCleanupCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcleanup/WorkflowActivationCleanupCustomResource.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcleanup/WorkflowActivationCleanupCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcleanup/WorkflowActivationCleanupCustomResource.java index f73b484d86..d98c9cd166 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcleanup/WorkflowActivationCleanupCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcleanup/WorkflowActivationCleanupCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.workflowactivationcleanup; +package io.javaoperatorsdk.operator.workflow.workflowactivationcleanup; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/WorkflowActivationCleanupIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcleanup/WorkflowActivationCleanupIT.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/WorkflowActivationCleanupIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcleanup/WorkflowActivationCleanupIT.java index fe1b72cc5a..f41d15ae27 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/WorkflowActivationCleanupIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcleanup/WorkflowActivationCleanupIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.workflow.workflowactivationcleanup; import org.junit.jupiter.api.*; @@ -8,10 +8,8 @@ import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.KubernetesClientBuilder; import io.fabric8.kubernetes.client.utils.KubernetesResourceUtil; +import io.javaoperatorsdk.operator.Operator; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.workflowactivationcleanup.WorkflowActivationCleanupCustomResource; -import io.javaoperatorsdk.operator.sample.workflowactivationcleanup.WorkflowActivationCleanupReconciler; -import io.javaoperatorsdk.operator.sample.workflowactivationcleanup.WorkflowActivationCleanupSpec; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcleanup/WorkflowActivationCleanupReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcleanup/WorkflowActivationCleanupReconciler.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcleanup/WorkflowActivationCleanupReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcleanup/WorkflowActivationCleanupReconciler.java index 3f2fba15c5..64a7a28a5c 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcleanup/WorkflowActivationCleanupReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcleanup/WorkflowActivationCleanupReconciler.java @@ -1,12 +1,13 @@ -package io.javaoperatorsdk.operator.sample.workflowactivationcleanup; +package io.javaoperatorsdk.operator.workflow.workflowactivationcleanup; import io.javaoperatorsdk.operator.api.reconciler.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; -@ControllerConfiguration(dependents = { +@Workflow(dependents = { @Dependent(type = ConfigMapDependentResource.class, activationCondition = TestActivcationCondition.class), }) +@ControllerConfiguration public class WorkflowActivationCleanupReconciler implements Reconciler, Cleaner { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcleanup/WorkflowActivationCleanupSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcleanup/WorkflowActivationCleanupSpec.java similarity index 72% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcleanup/WorkflowActivationCleanupSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcleanup/WorkflowActivationCleanupSpec.java index 23ea4cda3e..1719bb535f 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcleanup/WorkflowActivationCleanupSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcleanup/WorkflowActivationCleanupSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.workflowactivationcleanup; +package io.javaoperatorsdk.operator.workflow.workflowactivationcleanup; public class WorkflowActivationCleanupSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcondition/ConfigMapDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/ConfigMapDependentResource.java similarity index 93% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcondition/ConfigMapDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/ConfigMapDependentResource.java index 7433c31c73..a5b255b10f 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcondition/ConfigMapDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/ConfigMapDependentResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.workflowactivationcondition; +package io.javaoperatorsdk.operator.workflow.workflowactivationcondition; import java.util.Map; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcondition/IsOpenShiftCondition.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/IsOpenShiftCondition.java similarity index 90% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcondition/IsOpenShiftCondition.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/IsOpenShiftCondition.java index 79434409b8..5665590527 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcondition/IsOpenShiftCondition.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/IsOpenShiftCondition.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.workflowactivationcondition; +package io.javaoperatorsdk.operator.workflow.workflowactivationcondition; import io.fabric8.openshift.api.model.Route; import io.javaoperatorsdk.operator.api.reconciler.Context; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcondition/RouteDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/RouteDependentResource.java similarity index 92% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcondition/RouteDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/RouteDependentResource.java index de5d52f76a..92fe86d5db 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcondition/RouteDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/RouteDependentResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.workflowactivationcondition; +package io.javaoperatorsdk.operator.workflow.workflowactivationcondition; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.openshift.api.model.Route; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcondition/WorkflowActivationConditionCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/WorkflowActivationConditionCustomResource.java similarity index 86% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcondition/WorkflowActivationConditionCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/WorkflowActivationConditionCustomResource.java index 63d4bc343c..d04b3c08e0 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcondition/WorkflowActivationConditionCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/WorkflowActivationConditionCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.workflowactivationcondition; +package io.javaoperatorsdk.operator.workflow.workflowactivationcondition; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/WorkflowActivationConditionIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/WorkflowActivationConditionIT.java similarity index 75% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/WorkflowActivationConditionIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/WorkflowActivationConditionIT.java index 38a11e0438..355855e6c6 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/WorkflowActivationConditionIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/WorkflowActivationConditionIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.workflow.workflowactivationcondition; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -6,11 +6,8 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.workflowactivationcondition.WorkflowActivationConditionCustomResource; -import io.javaoperatorsdk.operator.sample.workflowactivationcondition.WorkflowActivationConditionReconciler; -import io.javaoperatorsdk.operator.sample.workflowactivationcondition.WorkflowActivationConditionSpec; -import static io.javaoperatorsdk.operator.sample.workflowactivationcondition.ConfigMapDependentResource.DATA_KEY; +import static io.javaoperatorsdk.operator.workflow.workflowactivationcondition.ConfigMapDependentResource.DATA_KEY; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcondition/WorkflowActivationConditionReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/WorkflowActivationConditionReconciler.java similarity index 84% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcondition/WorkflowActivationConditionReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/WorkflowActivationConditionReconciler.java index 33db3043ba..2ac931bcdb 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcondition/WorkflowActivationConditionReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/WorkflowActivationConditionReconciler.java @@ -1,13 +1,14 @@ -package io.javaoperatorsdk.operator.sample.workflowactivationcondition; +package io.javaoperatorsdk.operator.workflow.workflowactivationcondition; import io.javaoperatorsdk.operator.api.reconciler.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; -@ControllerConfiguration(dependents = { +@Workflow(dependents = { @Dependent(type = ConfigMapDependentResource.class), @Dependent(type = RouteDependentResource.class, activationCondition = IsOpenShiftCondition.class) }) +@ControllerConfiguration public class WorkflowActivationConditionReconciler implements Reconciler { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcondition/WorkflowActivationConditionSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/WorkflowActivationConditionSpec.java similarity index 72% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcondition/WorkflowActivationConditionSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/WorkflowActivationConditionSpec.java index 826fe04958..aa3b6b5f9c 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowactivationcondition/WorkflowActivationConditionSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowactivationcondition/WorkflowActivationConditionSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.workflowactivationcondition; +package io.javaoperatorsdk.operator.workflow.workflowactivationcondition; public class WorkflowActivationConditionSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/ConfigMapDeletePostCondition.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/ConfigMapDeletePostCondition.java similarity index 93% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/ConfigMapDeletePostCondition.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/ConfigMapDeletePostCondition.java index da6a693fe4..c9d9393ce1 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/ConfigMapDeletePostCondition.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/ConfigMapDeletePostCondition.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.workflowallfeature; +package io.javaoperatorsdk.operator.workflow.workflowallfeature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/ConfigMapDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/ConfigMapDependentResource.java similarity index 97% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/ConfigMapDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/ConfigMapDependentResource.java index 04876b7959..9bee03d474 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/ConfigMapDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/ConfigMapDependentResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.workflowallfeature; +package io.javaoperatorsdk.operator.workflow.workflowallfeature; import java.util.Map; import java.util.Optional; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/ConfigMapReconcileCondition.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/ConfigMapReconcileCondition.java new file mode 100644 index 0000000000..024e110edb --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/ConfigMapReconcileCondition.java @@ -0,0 +1,22 @@ +package io.javaoperatorsdk.operator.workflow.workflowallfeature; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; +import io.javaoperatorsdk.operator.processing.dependent.workflow.DetailedCondition; + +public class ConfigMapReconcileCondition + implements DetailedCondition { + + public static final String CREATE_SET = "create set"; + public static final String CREATE_NOT_SET = "create not set"; + public static final String NOT_RECONCILED_YET = "Not reconciled yet"; + + @Override + public Result detailedIsMet( + DependentResource dependentResource, + WorkflowAllFeatureCustomResource primary, Context context) { + final var createConfigMap = primary.getSpec().isCreateConfigMap(); + return Result.withResult(createConfigMap, createConfigMap ? CREATE_SET : CREATE_NOT_SET); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/DeploymentDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/DeploymentDependentResource.java similarity index 85% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/DeploymentDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/DeploymentDependentResource.java index 61cf18f57b..5abcf4c28c 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/DeploymentDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/DeploymentDependentResource.java @@ -1,8 +1,7 @@ -package io.javaoperatorsdk.operator.sample.workflowallfeature; +package io.javaoperatorsdk.operator.workflow.workflowallfeature; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.javaoperatorsdk.operator.ReconcilerUtils; -import io.javaoperatorsdk.operator.WorkflowAllFeatureIT; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDNoGCKubernetesDependentResource; @@ -18,12 +17,10 @@ protected Deployment desired(WorkflowAllFeatureCustomResource primary, Context context) { Deployment deployment = ReconcilerUtils.loadYaml(Deployment.class, WorkflowAllFeatureIT.class, - "nginx-deployment.yaml"); + "/io/javaoperatorsdk/operator/nginx-deployment.yaml"); deployment.getMetadata().setName(primary.getMetadata().getName()); deployment.getSpec().setReplicas(2); deployment.getMetadata().setNamespace(primary.getMetadata().getNamespace()); return deployment; } } - - diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/DeploymentReadyCondition.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/DeploymentReadyCondition.java similarity index 93% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/DeploymentReadyCondition.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/DeploymentReadyCondition.java index 0e6f5d8580..5e023a3d9d 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/DeploymentReadyCondition.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/DeploymentReadyCondition.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.workflowallfeature; +package io.javaoperatorsdk.operator.workflow.workflowallfeature; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.javaoperatorsdk.operator.api.reconciler.Context; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/WorkflowAllFeatureCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/WorkflowAllFeatureCustomResource.java similarity index 88% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/WorkflowAllFeatureCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/WorkflowAllFeatureCustomResource.java index ee764f4681..cc3987710b 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/WorkflowAllFeatureCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/WorkflowAllFeatureCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.workflowallfeature; +package io.javaoperatorsdk.operator.workflow.workflowallfeature; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/WorkflowAllFeatureIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/WorkflowAllFeatureIT.java similarity index 77% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/WorkflowAllFeatureIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/WorkflowAllFeatureIT.java index f60f2b6fde..20e5ea5ae3 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/WorkflowAllFeatureIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/WorkflowAllFeatureIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.workflow.workflowallfeature; import java.time.Duration; import java.util.HashMap; @@ -10,11 +10,8 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.workflowallfeature.WorkflowAllFeatureCustomResource; -import io.javaoperatorsdk.operator.sample.workflowallfeature.WorkflowAllFeatureReconciler; -import io.javaoperatorsdk.operator.sample.workflowallfeature.WorkflowAllFeatureSpec; -import static io.javaoperatorsdk.operator.sample.workflowallfeature.ConfigMapDependentResource.READY_TO_DELETE_ANNOTATION; +import static io.javaoperatorsdk.operator.workflow.workflowallfeature.ConfigMapDependentResource.READY_TO_DELETE_ANNOTATION; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; @@ -39,6 +36,8 @@ void configMapNotReconciledUntilDeploymentReady() { .isPositive(); assertThat(operator.get(Deployment.class, RESOURCE_NAME)).isNotNull(); assertThat(operator.get(ConfigMap.class, RESOURCE_NAME)).isNull(); + assertThat(getPrimaryStatus().getMsgFromCondition()) + .isEqualTo(ConfigMapReconcileCondition.NOT_RECONCILED_YET); }); await().atMost(ONE_MINUTE).untilAsserted(() -> { @@ -47,13 +46,20 @@ void configMapNotReconciledUntilDeploymentReady() { .getNumberOfReconciliationExecution()) .isGreaterThan(1); assertThat(operator.get(ConfigMap.class, RESOURCE_NAME)).isNotNull(); - assertThat(operator.get(WorkflowAllFeatureCustomResource.class, RESOURCE_NAME) - .getStatus().getReady()).isTrue(); + final var primaryStatus = getPrimaryStatus(); + assertThat(primaryStatus.getReady()).isTrue(); + assertThat(primaryStatus.getMsgFromCondition()) + .isEqualTo(ConfigMapReconcileCondition.CREATE_SET); }); markConfigMapForDelete(); } + private WorkflowAllFeatureStatus getPrimaryStatus() { + return operator.get(WorkflowAllFeatureCustomResource.class, RESOURCE_NAME) + .getStatus(); + } + @Test void configMapNotReconciledIfReconcileConditionNotMet() { @@ -61,8 +67,7 @@ void configMapNotReconciledIfReconcileConditionNotMet() { await().atMost(ONE_MINUTE).untilAsserted(() -> { assertThat(operator.get(ConfigMap.class, RESOURCE_NAME)).isNull(); - assertThat(operator.get(WorkflowAllFeatureCustomResource.class, RESOURCE_NAME) - .getStatus().getReady()).isTrue(); + assertThat(getPrimaryStatus().getReady()).isTrue(); }); resource.getSpec().setCreateConfigMap(true); @@ -70,8 +75,7 @@ void configMapNotReconciledIfReconcileConditionNotMet() { await().untilAsserted(() -> { assertThat(operator.get(ConfigMap.class, RESOURCE_NAME)).isNotNull(); - assertThat(operator.get(WorkflowAllFeatureCustomResource.class, RESOURCE_NAME) - .getStatus().getReady()).isTrue(); + assertThat(getPrimaryStatus().getReady()).isTrue(); }); } @@ -81,10 +85,9 @@ void configMapNotDeletedUntilNotMarked() { var resource = operator.create(customResource(true)); await().atMost(ONE_MINUTE).untilAsserted(() -> { - assertThat(operator.get(WorkflowAllFeatureCustomResource.class, RESOURCE_NAME).getStatus()) + assertThat(getPrimaryStatus()) .isNotNull(); - assertThat(operator.get(WorkflowAllFeatureCustomResource.class, RESOURCE_NAME) - .getStatus().getReady()).isTrue(); + assertThat(getPrimaryStatus().getReady()).isTrue(); assertThat(operator.get(ConfigMap.class, RESOURCE_NAME)).isNotNull(); }); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/WorkflowAllFeatureReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/WorkflowAllFeatureReconciler.java similarity index 56% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/WorkflowAllFeatureReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/WorkflowAllFeatureReconciler.java index 2c25d13924..c035a27375 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/WorkflowAllFeatureReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/WorkflowAllFeatureReconciler.java @@ -1,13 +1,21 @@ -package io.javaoperatorsdk.operator.sample.workflowallfeature; +package io.javaoperatorsdk.operator.workflow.workflowallfeature; import java.util.concurrent.atomic.AtomicInteger; -import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.reconciler.Cleaner; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.DeleteControl; +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.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; +import io.javaoperatorsdk.operator.processing.dependent.workflow.Condition; -import static io.javaoperatorsdk.operator.sample.workflowallfeature.WorkflowAllFeatureReconciler.DEPLOYMENT_NAME; +import static io.javaoperatorsdk.operator.workflow.workflowallfeature.WorkflowAllFeatureReconciler.DEPLOYMENT_NAME; -@ControllerConfiguration(dependents = { +@Workflow(dependents = { @Dependent(name = DEPLOYMENT_NAME, type = DeploymentDependentResource.class, readyPostcondition = DeploymentReadyCondition.class), @Dependent(type = ConfigMapDependentResource.class, @@ -15,6 +23,7 @@ deletePostcondition = ConfigMapDeletePostCondition.class, dependsOn = DEPLOYMENT_NAME) }) +@ControllerConfiguration public class WorkflowAllFeatureReconciler implements Reconciler, Cleaner { @@ -32,11 +41,15 @@ public UpdateControl reconcile( if (resource.getStatus() == null) { resource.setStatus(new WorkflowAllFeatureStatus()); } + final var reconcileResult = context.managedWorkflowAndDependentResourceContext() + .getWorkflowReconcileResult(); + final var msgFromCondition = reconcileResult.getDependentConditionResult( + DependentResource.defaultNameFor(ConfigMapDependentResource.class), + Condition.Type.RECONCILE, String.class) + .orElse(ConfigMapReconcileCondition.NOT_RECONCILED_YET); resource.getStatus() - .setReady( - context.managedDependentResourceContext() - .getWorkflowReconcileResult().orElseThrow() - .allDependentResourcesReady()); + .withReady(reconcileResult.allDependentResourcesReady()) + .withMsgFromCondition(msgFromCondition); return UpdateControl.patchStatus(resource); } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/WorkflowAllFeatureSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/WorkflowAllFeatureSpec.java similarity index 82% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/WorkflowAllFeatureSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/WorkflowAllFeatureSpec.java index 6d5cfd7a5a..fb7ced3753 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowallfeature/WorkflowAllFeatureSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/WorkflowAllFeatureSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.workflowallfeature; +package io.javaoperatorsdk.operator.workflow.workflowallfeature; public class WorkflowAllFeatureSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/WorkflowAllFeatureStatus.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/WorkflowAllFeatureStatus.java new file mode 100644 index 0000000000..a1a83e4abc --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowallfeature/WorkflowAllFeatureStatus.java @@ -0,0 +1,26 @@ +package io.javaoperatorsdk.operator.workflow.workflowallfeature; + +public class WorkflowAllFeatureStatus { + + private Boolean ready; + private String msgFromCondition; + + public Boolean getReady() { + return ready; + } + + public String getMsgFromCondition() { + return msgFromCondition; + } + + public WorkflowAllFeatureStatus withReady(Boolean ready) { + this.ready = ready; + return this; + } + + @SuppressWarnings("UnusedReturnValue") + public WorkflowAllFeatureStatus withMsgFromCondition(String msgFromCondition) { + this.msgFromCondition = msgFromCondition; + return this; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitcleanup/ConfigMapDependent.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitcleanup/ConfigMapDependent.java new file mode 100644 index 0000000000..228ed39564 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitcleanup/ConfigMapDependent.java @@ -0,0 +1,29 @@ +package io.javaoperatorsdk.operator.workflow.workflowexplicitcleanup; + +import java.util.Map; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDNoGCKubernetesDependentResource; + +public class ConfigMapDependent extends + CRUDNoGCKubernetesDependentResource { + + public ConfigMapDependent() { + super(ConfigMap.class); + } + + @Override + protected ConfigMap desired(WorkflowExplicitCleanupCustomResource primary, + Context context) { + return new ConfigMapBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName(primary.getMetadata().getName()) + .withNamespace(primary.getMetadata().getNamespace()) + .build()) + .withData(Map.of("key", "val")) + .build(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitcleanup/WorkflowExplicitCleanupCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitcleanup/WorkflowExplicitCleanupCustomResource.java new file mode 100644 index 0000000000..14ae6011a9 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitcleanup/WorkflowExplicitCleanupCustomResource.java @@ -0,0 +1,15 @@ +package io.javaoperatorsdk.operator.workflow.workflowexplicitcleanup; + +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("sample.javaoperatorsdk") +@Version("v1") +@ShortNames("wec") +public class WorkflowExplicitCleanupCustomResource + extends CustomResource + implements Namespaced { +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitcleanup/WorkflowExplicitCleanupIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitcleanup/WorkflowExplicitCleanupIT.java new file mode 100644 index 0000000000..e6a5b7a3cc --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitcleanup/WorkflowExplicitCleanupIT.java @@ -0,0 +1,48 @@ +package io.javaoperatorsdk.operator.workflow.workflowexplicitcleanup; + +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.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public class WorkflowExplicitCleanupIT { + + public static final String RESOURCE_NAME = "test1"; + + @RegisterExtension + LocallyRunOperatorExtension extension = + LocallyRunOperatorExtension.builder() + .withReconciler(WorkflowExplicitCleanupReconciler.class) + .build(); + + @Test + void workflowInvokedExplicitly() { + var res = extension.create(testResource()); + + await().untilAsserted(() -> { + assertThat(extension.get(ConfigMap.class, RESOURCE_NAME)).isNotNull(); + }); + + extension.delete(res); + + // The ConfigMap is not garbage collected, this tests that even if the cleaner is not + // implemented the workflow cleanup still called even if there is explicit invocation + await().untilAsserted(() -> { + assertThat(extension.get(ConfigMap.class, RESOURCE_NAME)).isNull(); + }); + } + + WorkflowExplicitCleanupCustomResource testResource() { + var res = new WorkflowExplicitCleanupCustomResource(); + res.setMetadata(new ObjectMetaBuilder() + .withName(RESOURCE_NAME) + .build()); + return res; + } + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitcleanup/WorkflowExplicitCleanupReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitcleanup/WorkflowExplicitCleanupReconciler.java new file mode 100644 index 0000000000..4361b5ac47 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitcleanup/WorkflowExplicitCleanupReconciler.java @@ -0,0 +1,32 @@ +package io.javaoperatorsdk.operator.workflow.workflowexplicitcleanup; + +import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; + +@Workflow(explicitInvocation = true, + dependents = @Dependent(type = ConfigMapDependent.class)) +@ControllerConfiguration +public class WorkflowExplicitCleanupReconciler + implements Reconciler, + Cleaner { + + @Override + public UpdateControl reconcile( + WorkflowExplicitCleanupCustomResource resource, + Context context) { + + context.managedWorkflowAndDependentResourceContext().reconcileManagedWorkflow(); + + return UpdateControl.noUpdate(); + } + + @Override + public DeleteControl cleanup(WorkflowExplicitCleanupCustomResource resource, + Context context) { + + context.managedWorkflowAndDependentResourceContext().cleanupManageWorkflow(); + // this can be checked + // context.managedWorkflowAndDependentResourceContext().getWorkflowCleanupResult() + return DeleteControl.defaultDelete(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitcleanup/WorkflowExplicitCleanupSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitcleanup/WorkflowExplicitCleanupSpec.java new file mode 100644 index 0000000000..93236cbf2c --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitcleanup/WorkflowExplicitCleanupSpec.java @@ -0,0 +1,15 @@ +package io.javaoperatorsdk.operator.workflow.workflowexplicitcleanup; + +public class WorkflowExplicitCleanupSpec { + + private String value; + + public String getValue() { + return value; + } + + public WorkflowExplicitCleanupSpec setValue(String value) { + this.value = value; + return this; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitinvocation/ConfigMapDependent.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitinvocation/ConfigMapDependent.java new file mode 100644 index 0000000000..1632de5bbd --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitinvocation/ConfigMapDependent.java @@ -0,0 +1,29 @@ +package io.javaoperatorsdk.operator.workflow.workflowexplicitinvocation; + +import java.util.Map; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDNoGCKubernetesDependentResource; + +public class ConfigMapDependent extends + CRUDNoGCKubernetesDependentResource { + + public ConfigMapDependent() { + super(ConfigMap.class); + } + + @Override + protected ConfigMap desired(WorkflowExplicitInvocationCustomResource primary, + Context context) { + return new ConfigMapBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName(primary.getMetadata().getName()) + .withNamespace(primary.getMetadata().getNamespace()) + .build()) + .withData(Map.of("key", primary.getSpec().getValue())) + .build(); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitinvocation/WorkflowExplicitInvocationCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitinvocation/WorkflowExplicitInvocationCustomResource.java new file mode 100644 index 0000000000..c64964b02b --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitinvocation/WorkflowExplicitInvocationCustomResource.java @@ -0,0 +1,15 @@ +package io.javaoperatorsdk.operator.workflow.workflowexplicitinvocation; + +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("sample.javaoperatorsdk") +@Version("v1") +@ShortNames("wei") +public class WorkflowExplicitInvocationCustomResource + extends CustomResource + implements Namespaced { +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitinvocation/WorkflowExplicitInvocationIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitinvocation/WorkflowExplicitInvocationIT.java new file mode 100644 index 0000000000..ba77057acc --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitinvocation/WorkflowExplicitInvocationIT.java @@ -0,0 +1,65 @@ +package io.javaoperatorsdk.operator.workflow.workflowexplicitinvocation; + +import java.time.Duration; + +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.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public class WorkflowExplicitInvocationIT { + + public static final String RESOURCE_NAME = "test1"; + + @RegisterExtension + LocallyRunOperatorExtension extension = + LocallyRunOperatorExtension.builder() + .withReconciler(WorkflowExplicitInvocationReconciler.class) + .build(); + + @Test + void workflowInvokedExplicitly() { + var res = extension.create(testResource()); + var reconciler = extension.getReconcilerOfType(WorkflowExplicitInvocationReconciler.class); + + await().untilAsserted(() -> { + assertThat(reconciler.getNumberOfExecutions()).isEqualTo(1); + assertThat(extension.get(ConfigMap.class, RESOURCE_NAME)).isNull(); + }); + + reconciler.setInvokeWorkflow(true); + + // trigger reconciliation + res.getSpec().setValue("changed value"); + res = extension.replace(res); + + await().untilAsserted(() -> { + assertThat(reconciler.getNumberOfExecutions()).isEqualTo(2); + assertThat(extension.get(ConfigMap.class, RESOURCE_NAME)).isNotNull(); + }); + + extension.delete(res); + + // The ConfigMap is not garbage collected, this tests that even if the cleaner is not + // implemented the workflow cleanup still called even if there is explicit invocation + await().timeout(Duration.ofSeconds(30)).untilAsserted(() -> { + assertThat(extension.get(ConfigMap.class, RESOURCE_NAME)).isNull(); + }); + } + + WorkflowExplicitInvocationCustomResource testResource() { + var res = new WorkflowExplicitInvocationCustomResource(); + res.setMetadata(new ObjectMetaBuilder() + .withName(RESOURCE_NAME) + .build()); + res.setSpec(new WorkflowExplicitInvocationSpec()); + res.getSpec().setValue("initial value"); + return res; + } + +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitinvocation/WorkflowExplicitInvocationReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitinvocation/WorkflowExplicitInvocationReconciler.java new file mode 100644 index 0000000000..4ac64b4cf8 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitinvocation/WorkflowExplicitInvocationReconciler.java @@ -0,0 +1,39 @@ +package io.javaoperatorsdk.operator.workflow.workflowexplicitinvocation; + +import java.util.concurrent.atomic.AtomicInteger; + +import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; + +@Workflow(explicitInvocation = true, + dependents = @Dependent(type = ConfigMapDependent.class)) +@ControllerConfiguration +public class WorkflowExplicitInvocationReconciler + implements Reconciler { + + private final AtomicInteger numberOfExecutions = new AtomicInteger(0); + + private volatile boolean invokeWorkflow = false; + + @Override + public UpdateControl reconcile( + WorkflowExplicitInvocationCustomResource resource, + Context context) { + + numberOfExecutions.addAndGet(1); + if (invokeWorkflow) { + context.managedWorkflowAndDependentResourceContext().reconcileManagedWorkflow(); + } + + + return UpdateControl.noUpdate(); + } + + public int getNumberOfExecutions() { + return numberOfExecutions.get(); + } + + public void setInvokeWorkflow(boolean invokeWorkflow) { + this.invokeWorkflow = invokeWorkflow; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitinvocation/WorkflowExplicitInvocationSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitinvocation/WorkflowExplicitInvocationSpec.java new file mode 100644 index 0000000000..a50af9a9db --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowexplicitinvocation/WorkflowExplicitInvocationSpec.java @@ -0,0 +1,15 @@ +package io.javaoperatorsdk.operator.workflow.workflowexplicitinvocation; + +public class WorkflowExplicitInvocationSpec { + + private String value; + + public String getValue() { + return value; + } + + public WorkflowExplicitInvocationSpec setValue(String value) { + this.value = value; + return this; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowmultipleactivation/ActivationCondition.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/ActivationCondition.java similarity index 90% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowmultipleactivation/ActivationCondition.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/ActivationCondition.java index c8be8467df..b69573c253 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowmultipleactivation/ActivationCondition.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/ActivationCondition.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.workflowmultipleactivation; +package io.javaoperatorsdk.operator.workflow.workflowmultipleactivation; import io.fabric8.openshift.api.model.Route; import io.javaoperatorsdk.operator.api.reconciler.Context; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowmultipleactivation/ConfigMapDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/ConfigMapDependentResource.java similarity index 93% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowmultipleactivation/ConfigMapDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/ConfigMapDependentResource.java index e245cb222d..82d8d9c236 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowmultipleactivation/ConfigMapDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/ConfigMapDependentResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.workflowmultipleactivation; +package io.javaoperatorsdk.operator.workflow.workflowmultipleactivation; import java.util.Map; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowmultipleactivation/SecretDependentResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/SecretDependentResource.java similarity index 93% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowmultipleactivation/SecretDependentResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/SecretDependentResource.java index decd5a346d..872a5b5770 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowmultipleactivation/SecretDependentResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/SecretDependentResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.workflowmultipleactivation; +package io.javaoperatorsdk.operator.workflow.workflowmultipleactivation; import java.util.Base64; import java.util.Map; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowmultipleactivation/WorkflowMultipleActivationCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/WorkflowMultipleActivationCustomResource.java similarity index 87% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowmultipleactivation/WorkflowMultipleActivationCustomResource.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/WorkflowMultipleActivationCustomResource.java index 9c642e9635..faf442b849 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowmultipleactivation/WorkflowMultipleActivationCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/WorkflowMultipleActivationCustomResource.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.workflowmultipleactivation; +package io.javaoperatorsdk.operator.workflow.workflowmultipleactivation; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/WorkflowMultipleActivationIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/WorkflowMultipleActivationIT.java similarity index 95% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/WorkflowMultipleActivationIT.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/WorkflowMultipleActivationIT.java index a7f93935ee..e793e9cb19 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/WorkflowMultipleActivationIT.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/WorkflowMultipleActivationIT.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator; +package io.javaoperatorsdk.operator.workflow.workflowmultipleactivation; import java.time.Duration; @@ -9,9 +9,8 @@ import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.api.model.Secret; import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; -import io.javaoperatorsdk.operator.sample.workflowmultipleactivation.*; -import static io.javaoperatorsdk.operator.sample.workflowactivationcondition.ConfigMapDependentResource.DATA_KEY; +import static io.javaoperatorsdk.operator.workflow.workflowactivationcondition.ConfigMapDependentResource.DATA_KEY; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowmultipleactivation/WorkflowMultipleActivationReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/WorkflowMultipleActivationReconciler.java similarity index 71% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowmultipleactivation/WorkflowMultipleActivationReconciler.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/WorkflowMultipleActivationReconciler.java index 8277e7f8e7..6018fb7112 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowmultipleactivation/WorkflowMultipleActivationReconciler.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/WorkflowMultipleActivationReconciler.java @@ -1,18 +1,16 @@ -package io.javaoperatorsdk.operator.sample.workflowmultipleactivation; +package io.javaoperatorsdk.operator.workflow.workflowmultipleactivation; import java.util.concurrent.atomic.AtomicInteger; -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.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; -@ControllerConfiguration(dependents = { +@Workflow(dependents = { @Dependent(type = ConfigMapDependentResource.class, activationCondition = ActivationCondition.class), @Dependent(type = SecretDependentResource.class) }) +@ControllerConfiguration public class WorkflowMultipleActivationReconciler implements Reconciler { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowmultipleactivation/WorkflowMultipleActivationSpec.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/WorkflowMultipleActivationSpec.java similarity index 72% rename from operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowmultipleactivation/WorkflowMultipleActivationSpec.java rename to operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/WorkflowMultipleActivationSpec.java index b342bb331f..c9c9cf3a15 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/workflowmultipleactivation/WorkflowMultipleActivationSpec.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowmultipleactivation/WorkflowMultipleActivationSpec.java @@ -1,4 +1,4 @@ -package io.javaoperatorsdk.operator.sample.workflowmultipleactivation; +package io.javaoperatorsdk.operator.workflow.workflowmultipleactivation; public class WorkflowMultipleActivationSpec { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowsilentexceptionhandling/ConfigMapDependent.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowsilentexceptionhandling/ConfigMapDependent.java new file mode 100644 index 0000000000..fcd817c4f7 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowsilentexceptionhandling/ConfigMapDependent.java @@ -0,0 +1,28 @@ +package io.javaoperatorsdk.operator.workflow.workflowsilentexceptionhandling; + + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.dependent.ReconcileResult; +import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDNoGCKubernetesDependentResource; + +public class ConfigMapDependent extends + CRUDNoGCKubernetesDependentResource { + + public ConfigMapDependent() { + super(ConfigMap.class); + } + + @Override + public ReconcileResult reconcile( + HandleWorkflowExceptionsInReconcilerCustomResource primary, + Context context) { + throw new RuntimeException("Exception thrown on purpose"); + } + + @Override + public void delete(HandleWorkflowExceptionsInReconcilerCustomResource primary, + Context context) { + throw new RuntimeException("Exception thrown on purpose"); + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowsilentexceptionhandling/HandleWorkflowExceptionsInReconcilerCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowsilentexceptionhandling/HandleWorkflowExceptionsInReconcilerCustomResource.java new file mode 100644 index 0000000000..db5e94e40b --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowsilentexceptionhandling/HandleWorkflowExceptionsInReconcilerCustomResource.java @@ -0,0 +1,15 @@ +package io.javaoperatorsdk.operator.workflow.workflowsilentexceptionhandling; + +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("sample.javaoperatorsdk") +@Version("v1") +@ShortNames("hweir") +public class HandleWorkflowExceptionsInReconcilerCustomResource + extends CustomResource + implements Namespaced { +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowsilentexceptionhandling/HandleWorkflowExceptionsInReconcilerReconciler.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowsilentexceptionhandling/HandleWorkflowExceptionsInReconcilerReconciler.java new file mode 100644 index 0000000000..d0a80d0be4 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowsilentexceptionhandling/HandleWorkflowExceptionsInReconcilerReconciler.java @@ -0,0 +1,50 @@ +package io.javaoperatorsdk.operator.workflow.workflowsilentexceptionhandling; + +import io.javaoperatorsdk.operator.api.reconciler.Cleaner; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.DeleteControl; +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(handleExceptionsInReconciler = true, + dependents = @Dependent(type = ConfigMapDependent.class)) +@ControllerConfiguration +public class HandleWorkflowExceptionsInReconcilerReconciler + implements Reconciler, + Cleaner { + + private volatile boolean errorsFoundInReconcilerResult = false; + private volatile boolean errorsFoundInCleanupResult = false; + + @Override + public UpdateControl reconcile( + HandleWorkflowExceptionsInReconcilerCustomResource resource, + Context context) { + + errorsFoundInReconcilerResult = context.managedWorkflowAndDependentResourceContext() + .getWorkflowReconcileResult().erroredDependentsExist(); + + + return UpdateControl.noUpdate(); + } + + @Override + public DeleteControl cleanup(HandleWorkflowExceptionsInReconcilerCustomResource resource, + Context context) { + + errorsFoundInCleanupResult = context.managedWorkflowAndDependentResourceContext() + .getWorkflowCleanupResult().erroredDependentsExist(); + return DeleteControl.defaultDelete(); + } + + public boolean isErrorsFoundInReconcilerResult() { + return errorsFoundInReconcilerResult; + } + + public boolean isErrorsFoundInCleanupResult() { + return errorsFoundInCleanupResult; + } +} diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowsilentexceptionhandling/WorkflowSilentExceptionHandlingIT.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowsilentexceptionhandling/WorkflowSilentExceptionHandlingIT.java new file mode 100644 index 0000000000..b23fee2d20 --- /dev/null +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/workflow/workflowsilentexceptionhandling/WorkflowSilentExceptionHandlingIT.java @@ -0,0 +1,45 @@ +package io.javaoperatorsdk.operator.workflow.workflowsilentexceptionhandling; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.junit.LocallyRunOperatorExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +public class WorkflowSilentExceptionHandlingIT { + + @RegisterExtension + LocallyRunOperatorExtension extension = + LocallyRunOperatorExtension.builder() + .withReconciler(HandleWorkflowExceptionsInReconcilerReconciler.class) + .build(); + + @Test + void handleExceptionsInReconciler() { + extension.create(testResource()); + var reconciler = + extension.getReconcilerOfType(HandleWorkflowExceptionsInReconcilerReconciler.class); + + await().untilAsserted(() -> { + assertThat(reconciler.isErrorsFoundInReconcilerResult()).isTrue(); + }); + + extension.delete(testResource()); + + await().untilAsserted(() -> { + assertThat(reconciler.isErrorsFoundInCleanupResult()).isTrue(); + }); + } + + HandleWorkflowExceptionsInReconcilerCustomResource testResource() { + var res = new HandleWorkflowExceptionsInReconcilerCustomResource(); + res.setMetadata(new ObjectMetaBuilder() + .withName("test1") + .build()); + return res; + } + +} diff --git a/operator-framework/src/test/resources/compile-fixtures/MultilevelReconciler.java b/operator-framework/src/test/resources/compile-fixtures/MultilevelReconciler.java index acea0a0db2..254d211bd0 100644 --- a/operator-framework/src/test/resources/compile-fixtures/MultilevelReconciler.java +++ b/operator-framework/src/test/resources/compile-fixtures/MultilevelReconciler.java @@ -17,7 +17,7 @@ public static class MyCustomResource extends CustomResource { public UpdateControl reconcile( MultilevelReconciler.MyCustomResource customResource, Context context) { - return UpdateControl.updateResource(null); + return UpdateControl.patchResource(null); } public DeleteControl cleanup(MultilevelReconciler.MyCustomResource customResource, diff --git a/operator-framework/src/test/resources/compile-fixtures/ReconcilerImplemented2Interfaces.java b/operator-framework/src/test/resources/compile-fixtures/ReconcilerImplemented2Interfaces.java index 0adc9aee09..bd1ba773be 100644 --- a/operator-framework/src/test/resources/compile-fixtures/ReconcilerImplemented2Interfaces.java +++ b/operator-framework/src/test/resources/compile-fixtures/ReconcilerImplemented2Interfaces.java @@ -14,7 +14,7 @@ public static class MyCustomResource extends CustomResource { @Override public UpdateControl reconcile(MyCustomResource customResource, Context context) { - return UpdateControl.updateResource(null); + return UpdateControl.patchResource(null); } @Override diff --git a/operator-framework/src/test/resources/compile-fixtures/ReconcilerImplementedIntermediateAbstractClass.java b/operator-framework/src/test/resources/compile-fixtures/ReconcilerImplementedIntermediateAbstractClass.java index b95495a614..ee291cf9ce 100644 --- a/operator-framework/src/test/resources/compile-fixtures/ReconcilerImplementedIntermediateAbstractClass.java +++ b/operator-framework/src/test/resources/compile-fixtures/ReconcilerImplementedIntermediateAbstractClass.java @@ -13,7 +13,7 @@ public class ReconcilerImplementedIntermediateAbstractClass extends public UpdateControl reconcile( AbstractReconciler.MyCustomResource customResource, Context context) { - return UpdateControl.updateResource(null); + return UpdateControl.patchResource(null); } public DeleteControl cleanup(AbstractReconciler.MyCustomResource customResource, diff --git a/operator-framework/src/test/resources/io/javaoperatorsdk/operator/leader-elector-stop-noaccess-role-binding.yaml b/operator-framework/src/test/resources/io/javaoperatorsdk/operator/baseapi/leader-elector-stop-noaccess-role-binding.yaml similarity index 100% rename from operator-framework/src/test/resources/io/javaoperatorsdk/operator/leader-elector-stop-noaccess-role-binding.yaml rename to operator-framework/src/test/resources/io/javaoperatorsdk/operator/baseapi/leader-elector-stop-noaccess-role-binding.yaml diff --git a/operator-framework/src/test/resources/io/javaoperatorsdk/operator/leader-elector-stop-role-noaccess.yaml b/operator-framework/src/test/resources/io/javaoperatorsdk/operator/baseapi/leader-elector-stop-role-noaccess.yaml similarity index 100% rename from operator-framework/src/test/resources/io/javaoperatorsdk/operator/leader-elector-stop-role-noaccess.yaml rename to operator-framework/src/test/resources/io/javaoperatorsdk/operator/baseapi/leader-elector-stop-role-noaccess.yaml diff --git a/operator-framework/src/test/resources/io/javaoperatorsdk/operator/rback-test-full-access-role.yaml b/operator-framework/src/test/resources/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/rback-test-full-access-role.yaml similarity index 100% rename from operator-framework/src/test/resources/io/javaoperatorsdk/operator/rback-test-full-access-role.yaml rename to operator-framework/src/test/resources/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/rback-test-full-access-role.yaml diff --git a/operator-framework/src/test/resources/io/javaoperatorsdk/operator/rback-test-no-configmap-access.yaml b/operator-framework/src/test/resources/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/rback-test-no-configmap-access.yaml similarity index 100% rename from operator-framework/src/test/resources/io/javaoperatorsdk/operator/rback-test-no-configmap-access.yaml rename to operator-framework/src/test/resources/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/rback-test-no-configmap-access.yaml diff --git a/operator-framework/src/test/resources/io/javaoperatorsdk/operator/rback-test-no-cr-access.yaml b/operator-framework/src/test/resources/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/rback-test-no-cr-access.yaml similarity index 100% rename from operator-framework/src/test/resources/io/javaoperatorsdk/operator/rback-test-no-cr-access.yaml rename to operator-framework/src/test/resources/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/rback-test-no-cr-access.yaml diff --git a/operator-framework/src/test/resources/io/javaoperatorsdk/operator/rback-test-only-main-ns-access-binding.yaml b/operator-framework/src/test/resources/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/rback-test-only-main-ns-access-binding.yaml similarity index 100% rename from operator-framework/src/test/resources/io/javaoperatorsdk/operator/rback-test-only-main-ns-access-binding.yaml rename to operator-framework/src/test/resources/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/rback-test-only-main-ns-access-binding.yaml diff --git a/operator-framework/src/test/resources/io/javaoperatorsdk/operator/rback-test-only-main-ns-access.yaml b/operator-framework/src/test/resources/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/rback-test-only-main-ns-access.yaml similarity index 100% rename from operator-framework/src/test/resources/io/javaoperatorsdk/operator/rback-test-only-main-ns-access.yaml rename to operator-framework/src/test/resources/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/rback-test-only-main-ns-access.yaml diff --git a/operator-framework/src/test/resources/io/javaoperatorsdk/operator/rback-test-role-binding.yaml b/operator-framework/src/test/resources/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/rback-test-role-binding.yaml similarity index 100% rename from operator-framework/src/test/resources/io/javaoperatorsdk/operator/rback-test-role-binding.yaml rename to operator-framework/src/test/resources/io/javaoperatorsdk/operator/dependent/informerrelatedbehavior/rback-test-role-binding.yaml diff --git a/operator-framework/src/test/resources/io/javaoperatorsdk/operator/sample/statefulsetdesiredsanitizer/statefulset.yaml b/operator-framework/src/test/resources/io/javaoperatorsdk/operator/statefulset.yaml similarity index 100% rename from operator-framework/src/test/resources/io/javaoperatorsdk/operator/sample/statefulsetdesiredsanitizer/statefulset.yaml rename to operator-framework/src/test/resources/io/javaoperatorsdk/operator/statefulset.yaml diff --git a/operator-framework/src/test/resources/io/javaoperatorsdk/operator/workflow/complexdependent/service.yaml b/operator-framework/src/test/resources/io/javaoperatorsdk/operator/workflow/complexdependent/service.yaml new file mode 100644 index 0000000000..736ef33178 --- /dev/null +++ b/operator-framework/src/test/resources/io/javaoperatorsdk/operator/workflow/complexdependent/service.yaml @@ -0,0 +1,16 @@ +apiVersion: v1 +kind: Service +metadata: + name: mongo-template + labels: + app.kubernetes.io/name: mongo-template + app.kubernetes.io/component: first-or-second +spec: + type: ClusterIP + selector: + app.kubernetes.io/name: mongo-template + clusterIP: None + ports: + - name: mongodb + port: 27017 + targetPort: 27017 \ No newline at end of file diff --git a/operator-framework/src/test/resources/io/javaoperatorsdk/operator/workflow/complexdependent/statefulset.yaml b/operator-framework/src/test/resources/io/javaoperatorsdk/operator/workflow/complexdependent/statefulset.yaml new file mode 100644 index 0000000000..a335a4aec7 --- /dev/null +++ b/operator-framework/src/test/resources/io/javaoperatorsdk/operator/workflow/complexdependent/statefulset.yaml @@ -0,0 +1,46 @@ +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: mongo-template + labels: + app.kubernetes.io/name: mongo-template + app.kubernetes.io/component: first-or-second +spec: + serviceName: mongo-template + replicas: 1 + selector: + matchLabels: + app.kubernetes.io/name: mongo-template + template: + metadata: + labels: + app.kubernetes.io/name: mongo-template + app.kubernetes.io/component: first-or-second + spec: + terminationGracePeriodSeconds: 10 + containers: + - name: mongo + image: mongo:4.4 + ports: + - name: mongodb + containerPort: 27017 + volumeMounts: + - name: data + mountPath: /data/db + volumeClaimTemplates: + - apiVersion: v1 + kind: PersistentVolumeClaim + metadata: + name: data + labels: + app.kubernetes.io/name: mongo-template + spec: + volumeMode: Filesystem + accessModes: + - ReadWriteOnce + resources: + requests: + storage: 1Gi + limits: + storage: 50Gi + diff --git a/pom.xml b/pom.xml index 179ef741d6..8d63726674 100644 --- a/pom.xml +++ b/pom.xml @@ -1,531 +1,611 @@ - - 4.0.0 + + 4.0.0 - io.javaoperatorsdk - java-operator-sdk - 4.9.7-SNAPSHOT - Operator SDK for Java - Java SDK for implementing Kubernetes operators - pom - https://github.com/operator-framework/java-operator-sdk + io.javaoperatorsdk + java-operator-sdk + 5.0.0-SNAPSHOT + pom + Operator SDK for Java + Java SDK for implementing Kubernetes operators + https://github.com/operator-framework/java-operator-sdk - - - Apache 2 License - https://www.apache.org/licenses/LICENSE-2.0.html - - - - - Adam Sandor - adam.sandor@container-solutions.com - - - Attila Meszaros - csviri@gmail.com - - + + + Apache 2 License + https://www.apache.org/licenses/LICENSE-2.0.html + + + + + Adam Sandor + adam.sandor@container-solutions.com + + + Attila Meszaros + csviri@gmail.com + + - - scm:git:git://github.com/java-operator-sdk/java-operator-sdk.git - scm:git:git@github.com/java-operator-sdk/java-operator-sdk.git - https://github.com/operator-framework/java-operator-sdk/tree/main - + + operator-framework-bom + operator-framework-core + operator-framework-junit5 + operator-framework + micrometer-support + sample-operators + caffeine-bounded-cache-support + bootstrapper-maven-plugin + - - UTF-8 - 11 - ${java.version} - ${java.version} - java-operator-sdk - https://sonarcloud.io - okhttp + + scm:git:git://github.com/operator-framework/java-operator-sdk.git + scm:git:git@github.com/operator-framework/java-operator-sdk.git + https://github.com/operator-framework/java-operator-sdk/tree/main + - 5.10.1 - 6.13.4 - 1.7.36 - 2.23.1 - 5.13.0 - 3.16.0 - 0.21.0 - 1.13.0 - 3.26.3 - 4.2.0 - 2.7.3 - 1.13.3 - 3.1.8 - 0.9.6 - 0.9.11 - 2.16.1 + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + - 2.11 - 3.12.1 - 3.5.0 - 3.10.0 - 3.3.1 - 3.3.1 - 3.4.2 - 3.4.0 - 3.2.5 - 1.7.0 - 3.0.0 - 3.1.3 - 9.0.1 - 2.23.0 - 1.0 - 1.9.0 - + + UTF-8 + 17 + ${java.version} + ${java.version} + java-operator-sdk + https://sonarcloud.io + jdk - - operator-framework-bom - operator-framework-core - operator-framework-junit5 - operator-framework - micrometer-support - sample-operators - caffeine-bounded-cache-support - bootstrapper-maven-plugin - + 5.10.1 + 6.13.4 + 2.0.12 + 2.23.1 + 5.13.0 + 3.16.0 + 0.21.0 + 1.13.0 + 3.26.3 + 4.2.0 + 2.7.3 + 1.13.3 + 3.1.8 + 0.9.11 + 2.16.1 + 4.12 + 2.11 + 3.12.1 + 3.5.0 + 3.10.0 + 3.3.1 + 3.3.1 + 3.4.2 + 3.4.0 + 3.2.5 + 1.7.0 + 3.0.0 + 3.1.3 + 9.0.1 + 3.4.1 + 2.43.0 + - - - - org.junit - junit-bom - ${junit.version} - pom - import - - - io.fabric8 - kubernetes-client-bom - ${fabric8-client.version} - pom - import - - - io.fabric8 - kubernetes-server-mock - ${fabric8-client.version} - test - - - io.fabric8 - kubernetes-client-api - ${fabric8-client.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - com.google.testing.compile - compile-testing - ${compile-testing.version} - - - io.micrometer - micrometer-core - ${micrometer-core.version} - - - com.squareup - javapoet - ${javapoet.version} - - - org.awaitility - awaitility - ${awaitility.version} - - - commons-io - commons-io - ${commons.io.version} - - - org.assertj - assertj-core - ${assertj.version} - - - org.mockito - mockito-core - ${mokito.version} - + + + + org.junit + junit-bom + ${junit.version} + pom + import + + + io.fabric8 + kubernetes-client-bom + ${fabric8-client.version} + pom + import + + + io.fabric8 + kubernetes-server-mock + ${fabric8-client.version} + test + + + io.fabric8 + kubernetes-client-api + ${fabric8-client.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + com.google.testing.compile + compile-testing + ${compile-testing.version} + + + io.micrometer + micrometer-core + ${micrometer-core.version} + + + com.squareup + javapoet + ${javapoet.version} + + + org.awaitility + awaitility + ${awaitility.version} + + + commons-io + commons-io + ${commons.io.version} + + + org.assertj + assertj-core + ${assertj.version} + + + org.mockito + mockito-core + ${mokito.version} + + + io.github.java-diff-utils + java-diff-utils + ${java.diff.version} + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.apache.logging.log4j + log4j-slf4j2-impl + ${log4j.version} + + + org.apache.logging.log4j + log4j-core + ${log4j.version} + test + + + org.apache.logging.log4j + log4j2-core + ${log4j.version} + + + com.github.spullara.mustache.java + compiler + ${mustache.version} + + + io.javaoperatorsdk + operator-framework-core + ${project.version} + + + io.javaoperatorsdk + operator-framework + ${project.version} + + + com.github.ben-manes.caffeine + caffeine + ${caffeine.version} + + + io.fabric8 + kube-api-test-client-inject + ${fabric8-client.version} + + + + + io.fabric8 + kubernetes-httpclient-okhttp + ${fabric8-client.version} + + + io.fabric8 + kubernetes-httpclient-vertx + ${fabric8-client.version} + + + io.fabric8 + kubernetes-httpclient-jdk + ${fabric8-client.version} + + + io.fabric8 + kubernetes-httpclient-jetty + ${fabric8-client.version} + + + + + + + + true + always + + ossrh + https://oss.sonatype.org/content/repositories/snapshots/ + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + + -Aio.fabric8.crd.generator.parallel=true + + + + + org.apache.maven.plugins + maven-resources-plugin + ${maven-resources-plugin.version} + + + org.apache.maven.plugins + maven-jar-plugin + ${maven-jar-plugin.version} + + + org.apache.maven.plugins + maven-clean-plugin + ${maven-clean-plugin.version} + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + plain + + true + + + UNICODE + + + - org.slf4j - slf4j-api - ${slf4j.version} - - - org.apache.logging.log4j - log4j-slf4j-impl - ${log4j.version} - - - org.apache.logging.log4j - log4j-core - ${log4j.version} - test - - - org.apache.logging.log4j - log4j2-core - ${log4j.version} - - - com.github.spullara.mustache.java - compiler - ${mustache.version} - - - io.javaoperatorsdk - operator-framework-core - ${project.version} - - - io.javaoperatorsdk - operator-framework - ${project.version} - - - com.github.ben-manes.caffeine - caffeine - ${caffeine.version} - - - io.javaoperatorsdk - jenvtest - ${jenvtest.version} - test - - - - io.fabric8 - kubernetes-httpclient-okhttp - ${fabric8-client.version} - - - io.fabric8 - kubernetes-httpclient-vertx - ${fabric8-client.version} - - - - io.fabric8 - kubernetes-httpclient-jdk - ${fabric8-client.version} - - - io.fabric8 - kubernetes-httpclient-jetty - ${fabric8-client.version} + me.fabriciorby + maven-surefire-junit5-tree-reporter + 1.3.0 - - - - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots/ - - true - always - - - - - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - - org.apache.maven.plugins - maven-resources-plugin - ${maven-resources-plugin.version} - - - org.apache.maven.plugins - maven-jar-plugin - ${maven-jar-plugin.version} - - - org.apache.maven.plugins - maven-clean-plugin - ${maven-clean-plugin.version} - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - org.apache.maven.plugins - maven-source-plugin - ${maven-source-plugin.version} - - - org.apache.maven.plugins - maven-gpg-plugin - ${maven-gpg-plugin.version} - - - org.apache.maven.plugins - maven-install-plugin - ${maven-install-plugin.version} - - - net.revelc.code.formatter - formatter-maven-plugin - ${formatter-maven-plugin.version} - - .cache - - - - net.revelc.code - impsort-maven-plugin - ${impsort-maven-plugin.version} - - .cache - java.,javax.,org.,io.,com. - * - true - true - - - - + + + + org.apache.maven.plugins + maven-source-plugin + ${maven-source-plugin.version} + + + org.apache.maven.plugins + maven-gpg-plugin + ${maven-gpg-plugin.version} + + + org.apache.maven.plugins + maven-install-plugin + ${maven-install-plugin.version} + + + com.diffplug.spotless + spotless-maven-plugin + ${spotless.version} + + + + + + com.diffplug.spotless + spotless-maven-plugin + + + + pom.xml + ./**/pom.xml + + + false + + + + + contributing/eclipse-google-style.xml + + + contributing/eclipse.importorder + + + + + + + + apply + + compile + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*Test.java + + + **/*IT.java + **/*E2E.java + + WatchPermissionAwareTest + + + + + + + integration-tests + + + io.fabric8 + crd-generator-apt + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IT.java + + + **/*Test.java + **/*E2E.java + + + + + + + + integration-tests-baseapi + + + io.fabric8 + crd-generator-apt + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + io/javaoperatorsdk/operator/baseapi/**/*IT.java + + + **/*Test.java + **/*E2E.java + + + + + + + + integration-tests-dependent + + + io.fabric8 + crd-generator-apt + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + io/javaoperatorsdk/operator/dependent/**/*IT.java + + + **/*Test.java + **/*E2E.java + + + + + + + + integration-tests-workflow + + + io.fabric8 + crd-generator-apt + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + io/javaoperatorsdk/operator/workflow/**/*IT.java + + + **/*Test.java + **/*E2E.java + + + + + + + + + minimal-watch-timeout-dependent-it + + + io.fabric8 + crd-generator-apt + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*ITS.java + + + **/*Test.java + **/*E2E.java + **/*IT.java + + + + + + + + end-to-end-tests + + + io.fabric8 + crd-generator-apt + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*E2E.java + + + **/*Test.java + **/*IT.java + + + + + + + + release + - - org.commonjava.maven.plugins - directory-maven-plugin - ${directory-maven-plugin.version} - - - directories - - highest-basedir - - initialize - - josdk.project.root - - - - - - org.apache.maven.plugins - maven-surefire-plugin + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IT.java + **/*E2E.java + **/InformerRelatedBehaviorTest.java + + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven-javadoc-plugin.version} + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-gpg-plugin + + + sign-artifacts + + sign + + verify - - **/*Test.java - - - **/*IT.java - **/*E2E.java - - WatchPermissionAwareTest + + --pinentry-mode + loopback + - - - net.revelc.code.formatter - formatter-maven-plugin - - - - format - - - - ${josdk.project.root}/contributing/eclipse-google-style.xml - - - - - - net.revelc.code - impsort-maven-plugin - - - sort - - sort - - - - + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + ${nexus-staging-maven-plugin.version} + true + + ossrh + https://oss.sonatype.org/ + true + + - - - - all-tests - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*Test.java - **/*IT.java - **/*E2E.java - - - - - - - - no-unit-tests - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*IT.java - - - **/*Test.java - **/*E2E.java - - - - - - - - - minimal-watch-timeout-dependent-it - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*ITS.java - - - **/*Test.java - **/*E2E.java - **/*IT.java - - - - - - - - end-to-end-tests - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*E2E.java - - - **/*Test.java - **/*IT.java - - - - - - - - release - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*IT.java - **/*E2E.java - **/InformerRelatedBehaviorTest.java - - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${maven-javadoc-plugin.version} - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-gpg-plugin - - - sign-artifacts - verify - - sign - - - - --pinentry-mode - loopback - - - - - - - org.sonatype.plugins - nexus-staging-maven-plugin - ${nexus-staging-maven-plugin.version} - true - - ossrh - https://oss.sonatype.org/ - true - - - - - - + + + diff --git a/sample-operators/controller-namespace-deletion/README.md b/sample-operators/controller-namespace-deletion/README.md new file mode 100644 index 0000000000..3ea02d1d36 --- /dev/null +++ b/sample-operators/controller-namespace-deletion/README.md @@ -0,0 +1,8 @@ +This sample demonstrates the workaround for problem when a namespace +is being deleted with a running controller, that watches resources +in its own namespace. If the pod or other underlying resources (role, +role binding, service account) are deleted before the cleanup of +the custom resource the namespace deletion is stuck. + +see also: https://github.com/operator-framework/java-operator-sdk/pull/2528 + diff --git a/sample-operators/controller-namespace-deletion/k8s/operator.yaml b/sample-operators/controller-namespace-deletion/k8s/operator.yaml new file mode 100644 index 0000000000..bc9eeb84ed --- /dev/null +++ b/sample-operators/controller-namespace-deletion/k8s/operator.yaml @@ -0,0 +1,62 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: operator + finalizers: + - controller.deletion/finalizer + +--- +apiVersion: v1 +kind: Pod +metadata: + name: operator +spec: + serviceAccountName: operator + containers: + - name: operator + image: controller-namespace-deletion-operator + imagePullPolicy: Never + env: + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + terminationGracePeriodSeconds: 30 + +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: operator + finalizers: + - controller.deletion/finalizer +subjects: + - kind: ServiceAccount + name: operator +roleRef: + kind: Role + name: operator + apiGroup: rbac.authorization.k8s.io + +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: operator + finalizers: + - controller.deletion/finalizer +rules: + - apiGroups: + - "apiextensions.k8s.io" + resources: + - customresourcedefinitions + verbs: + - '*' + - apiGroups: + - "namespacedeletion.io" + resources: + - controllernamespacedeletioncustomresources + - controllernamespacedeletioncustomresources/status + verbs: + - '*' + diff --git a/sample-operators/controller-namespace-deletion/pom.xml b/sample-operators/controller-namespace-deletion/pom.xml new file mode 100644 index 0000000000..4979eec0d1 --- /dev/null +++ b/sample-operators/controller-namespace-deletion/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + + io.javaoperatorsdk + sample-operators + 5.0.0-SNAPSHOT + + + sample-controller-namespace-deletion + jar + Operator SDK - Samples - Controller Namespace Deletion + Deleting namespace with controller and custom resources + + + + + io.javaoperatorsdk + operator-framework-bom + ${project.version} + pom + import + + + + + + + io.javaoperatorsdk + operator-framework + + + io.fabric8 + crd-generator-apt + provided + + + org.apache.logging.log4j + log4j-slf4j2-impl + compile + + + org.apache.logging.log4j + log4j-core + compile + + + org.takes + takes + 1.24.4 + + + org.awaitility + awaitility + compile + + + io.javaoperatorsdk + operator-framework-junit-5 + test + + + org.junit.jupiter + junit-jupiter-params + test + + + + + + com.google.cloud.tools + jib-maven-plugin + ${jib-maven-plugin.version} + + + gcr.io/distroless/java17-debian11 + + + controller-namespace-deletion-operator + + + + + + + diff --git a/sample-operators/controller-namespace-deletion/src/main/java/io/javaoperatorsdk/operator/sample/ControllerNamespaceDeletionCustomResource.java b/sample-operators/controller-namespace-deletion/src/main/java/io/javaoperatorsdk/operator/sample/ControllerNamespaceDeletionCustomResource.java new file mode 100644 index 0000000000..ae0f1034ee --- /dev/null +++ b/sample-operators/controller-namespace-deletion/src/main/java/io/javaoperatorsdk/operator/sample/ControllerNamespaceDeletionCustomResource.java @@ -0,0 +1,14 @@ +package io.javaoperatorsdk.operator.sample; + +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("namespacedeletion.io") +@Version("v1") +public class ControllerNamespaceDeletionCustomResource + extends CustomResource + implements Namespaced { + +} diff --git a/sample-operators/controller-namespace-deletion/src/main/java/io/javaoperatorsdk/operator/sample/ControllerNamespaceDeletionOperator.java b/sample-operators/controller-namespace-deletion/src/main/java/io/javaoperatorsdk/operator/sample/ControllerNamespaceDeletionOperator.java new file mode 100644 index 0000000000..5364852467 --- /dev/null +++ b/sample-operators/controller-namespace-deletion/src/main/java/io/javaoperatorsdk/operator/sample/ControllerNamespaceDeletionOperator.java @@ -0,0 +1,49 @@ +package io.javaoperatorsdk.operator.sample; + +import java.time.LocalTime; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.fabric8.kubernetes.client.KubernetesClientBuilder; +import io.javaoperatorsdk.operator.Operator; +import io.javaoperatorsdk.operator.api.config.ControllerConfigurationOverrider; + +import static java.time.temporal.ChronoUnit.SECONDS; + +public class ControllerNamespaceDeletionOperator { + + private static final Logger log = + LoggerFactory.getLogger(ControllerNamespaceDeletionOperator.class); + + public static void main(String[] args) { + + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + log.info("Shutting down..."); + boolean allResourcesDeleted = waitUntilResourcesDeleted(); + log.info("All resources within timeout: {}", allResourcesDeleted); + })); + + Operator operator = new Operator(); + operator.register(new ControllerNamespaceDeletionReconciler(), + ControllerConfigurationOverrider::watchingOnlyCurrentNamespace); + operator.start(); + } + + private static boolean waitUntilResourcesDeleted() { + try (var client = new KubernetesClientBuilder().build()) { + var startTime = LocalTime.now(); + while (startTime.until(LocalTime.now(), SECONDS) < 20) { + var items = + client.resources(ControllerNamespaceDeletionCustomResource.class) + .inNamespace(client.getConfiguration().getNamespace()) + .list().getItems(); + log.info("Custom resource in namespace: {}", items); + if (items.isEmpty()) { + return true; + } + } + return false; + } + } +} diff --git a/sample-operators/controller-namespace-deletion/src/main/java/io/javaoperatorsdk/operator/sample/ControllerNamespaceDeletionReconciler.java b/sample-operators/controller-namespace-deletion/src/main/java/io/javaoperatorsdk/operator/sample/ControllerNamespaceDeletionReconciler.java new file mode 100644 index 0000000000..7261f269b4 --- /dev/null +++ b/sample-operators/controller-namespace-deletion/src/main/java/io/javaoperatorsdk/operator/sample/ControllerNamespaceDeletionReconciler.java @@ -0,0 +1,59 @@ +package io.javaoperatorsdk.operator.sample; + +import java.time.Duration; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.api.reconciler.Cleaner; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.DeleteControl; +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; + +public class ControllerNamespaceDeletionReconciler + implements Reconciler, + Cleaner { + + private static final Logger log = + LoggerFactory.getLogger(ControllerNamespaceDeletionReconciler.class); + + public static final Duration CLEANUP_DELAY = Duration.ofSeconds(10); + + @Override + public UpdateControl reconcile( + ControllerNamespaceDeletionCustomResource resource, + Context context) { + log.info("Reconciling: {} in namespace: {}", resource.getMetadata().getName(), + resource.getMetadata().getNamespace()); + + var response = createResponseResource(resource); + response.getStatus().setValue(resource.getSpec().getValue()); + + return UpdateControl.patchStatus(response); + } + + private ControllerNamespaceDeletionCustomResource createResponseResource( + ControllerNamespaceDeletionCustomResource resource) { + var res = new ControllerNamespaceDeletionCustomResource(); + res.setMetadata(new ObjectMetaBuilder() + .withName(resource.getMetadata().getName()) + .withNamespace(resource.getMetadata().getNamespace()) + .build()); + res.setStatus(new ControllerNamespaceDeletionStatus()); + return res; + } + + @Override + public DeleteControl cleanup(ControllerNamespaceDeletionCustomResource resource, + Context context) { + log.info("Cleaning up resource"); + try { + Thread.sleep(CLEANUP_DELAY.toMillis()); + return DeleteControl.defaultDelete(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } +} diff --git a/sample-operators/controller-namespace-deletion/src/main/java/io/javaoperatorsdk/operator/sample/ControllerNamespaceDeletionSpec.java b/sample-operators/controller-namespace-deletion/src/main/java/io/javaoperatorsdk/operator/sample/ControllerNamespaceDeletionSpec.java new file mode 100644 index 0000000000..dc5092e7e5 --- /dev/null +++ b/sample-operators/controller-namespace-deletion/src/main/java/io/javaoperatorsdk/operator/sample/ControllerNamespaceDeletionSpec.java @@ -0,0 +1,15 @@ +package io.javaoperatorsdk.operator.sample; + + +public class ControllerNamespaceDeletionSpec { + + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/sample-operators/controller-namespace-deletion/src/main/java/io/javaoperatorsdk/operator/sample/ControllerNamespaceDeletionStatus.java b/sample-operators/controller-namespace-deletion/src/main/java/io/javaoperatorsdk/operator/sample/ControllerNamespaceDeletionStatus.java new file mode 100644 index 0000000000..732fa7d626 --- /dev/null +++ b/sample-operators/controller-namespace-deletion/src/main/java/io/javaoperatorsdk/operator/sample/ControllerNamespaceDeletionStatus.java @@ -0,0 +1,15 @@ +package io.javaoperatorsdk.operator.sample; + + +public class ControllerNamespaceDeletionStatus { + + private String value; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/sample-operators/controller-namespace-deletion/src/main/resources/log4j2.xml b/sample-operators/controller-namespace-deletion/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..0ec69bf713 --- /dev/null +++ b/sample-operators/controller-namespace-deletion/src/main/resources/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/sample-operators/controller-namespace-deletion/src/test/java/io/javaoperatorsdk/operator/sample/ControllerNamespaceDeletionE2E.java b/sample-operators/controller-namespace-deletion/src/test/java/io/javaoperatorsdk/operator/sample/ControllerNamespaceDeletionE2E.java new file mode 100644 index 0000000000..36c7f132ab --- /dev/null +++ b/sample-operators/controller-namespace-deletion/src/test/java/io/javaoperatorsdk/operator/sample/ControllerNamespaceDeletionE2E.java @@ -0,0 +1,144 @@ +package io.javaoperatorsdk.operator.sample; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.time.Duration; +import java.util.List; +import java.util.UUID; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.api.model.NamespaceBuilder; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.fabric8.kubernetes.api.model.rbac.RoleBinding; +import io.fabric8.kubernetes.client.ConfigBuilder; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClientBuilder; + +import static io.javaoperatorsdk.operator.junit.AbstractOperatorExtension.CRD_READY_WAIT; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + + +class ControllerNamespaceDeletionE2E { + + private static final Logger log = LoggerFactory.getLogger(ControllerNamespaceDeletionE2E.class); + + public static final String TEST_RESOURCE_NAME = "test1"; + public static final String INITIAL_VALUE = "initial value"; + public static final String ROLE_ROLE_BINDING_FINALIZER = "controller.deletion/finalizer"; + public static final String RESOURCE_NAME = "operator"; + + String namespace; + KubernetesClient client; + + // not for local mode by design + @EnabledIfSystemProperty(named = "test.deployment", matches = "remote") + @Test + void customResourceCleanedUpOnNamespaceDeletion() { + deployController(); + client.resource(testResource()).serverSideApply(); + + await().untilAsserted(() -> { + var res = client.resources(ControllerNamespaceDeletionCustomResource.class) + .inNamespace(namespace).withName(TEST_RESOURCE_NAME).get(); + assertThat(res.getStatus()).isNotNull(); + assertThat(res.getStatus().getValue()).isEqualTo(INITIAL_VALUE); + }); + + client.namespaces().withName(namespace).delete(); + + await().timeout(Duration.ofSeconds(20)).untilAsserted(() -> { + var ns = client.resources(ControllerNamespaceDeletionCustomResource.class) + .inNamespace(namespace).withName(TEST_RESOURCE_NAME).get(); + assertThat(ns).isNull(); + }); + + log.info("Removing finalizers from role and role bing and service account"); + removeRoleAndRoleBindingFinalizers(); + + await().timeout(Duration.ofSeconds(20)).untilAsserted(() -> { + var ns = client.namespaces().withName(namespace).get(); + assertThat(ns).isNull(); + }); + } + + private void removeRoleAndRoleBindingFinalizers() { + var rolebinding = + client.rbac().roleBindings().inNamespace(namespace).withName(RESOURCE_NAME).get(); + rolebinding.getFinalizers().clear(); + client.resource(rolebinding).update(); + + var role = client.rbac().roles().inNamespace(namespace).withName(RESOURCE_NAME).get(); + role.getFinalizers().clear(); + client.resource(role).update(); + + var sa = client.serviceAccounts().inNamespace(namespace).withName(RESOURCE_NAME).get(); + sa.getMetadata().getFinalizers().clear(); + client.resource(sa).update(); + } + + ControllerNamespaceDeletionCustomResource testResource() { + var cr = new ControllerNamespaceDeletionCustomResource(); + cr.setMetadata(new ObjectMetaBuilder() + .withName(TEST_RESOURCE_NAME) + .withNamespace(namespace) + .build()); + cr.setSpec(new ControllerNamespaceDeletionSpec()); + cr.getSpec().setValue(INITIAL_VALUE); + return cr; + } + + + @BeforeEach + void setup() { + namespace = "controller-namespace-" + UUID.randomUUID(); + client = new KubernetesClientBuilder().withConfig(new ConfigBuilder() + .withNamespace(namespace) + .build()).build(); + applyCRD(); + client.namespaces().resource(new NamespaceBuilder().withNewMetadata().withName(namespace) + .endMetadata().build()).create(); + } + + void deployController() { + try { + List resources = client.load(new FileInputStream("k8s/operator.yaml")).items(); + resources.forEach(hm -> { + hm.getMetadata().setNamespace(namespace); + if (hm.getKind().equalsIgnoreCase("rolebinding")) { + var crb = (RoleBinding) hm; + for (var subject : crb.getSubjects()) { + subject.setNamespace(namespace); + } + } + }); + client.resourceList(resources) + .inNamespace(namespace) + .createOrReplace(); + + } catch (FileNotFoundException e) { + throw new RuntimeException(e); + } + } + + void applyCRD() { + String path = + "target/classes/META-INF/fabric8/controllernamespacedeletioncustomresources.namespacedeletion.io-v1.yml"; + try (InputStream is = new FileInputStream(path)) { + final var crd = client.load(is); + crd.serverSideApply(); + Thread.sleep(CRD_READY_WAIT); + log.debug("Applied CRD with name: {}", crd.get().get(0).getMetadata().getName()); + } catch (InterruptedException | IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/sample-operators/controller-namespace-deletion/src/test/resources/log4j2.xml b/sample-operators/controller-namespace-deletion/src/test/resources/log4j2.xml new file mode 100644 index 0000000000..2b7fdd3479 --- /dev/null +++ b/sample-operators/controller-namespace-deletion/src/test/resources/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/sample-operators/leader-election/k8s/namespace-inferred-operator.yaml b/sample-operators/leader-election/k8s/namespace-inferred-operator.yaml index 13724a911a..cf8e743bd2 100644 --- a/sample-operators/leader-election/k8s/namespace-inferred-operator.yaml +++ b/sample-operators/leader-election/k8s/namespace-inferred-operator.yaml @@ -46,7 +46,7 @@ rules: verbs: - '*' - apiGroups: - - "sample.javaoperatorsdk" + - "sample.operator.javaoperatorsdk.io" resources: - leaderelections - leaderelections/status diff --git a/sample-operators/leader-election/k8s/operator.yaml b/sample-operators/leader-election/k8s/operator.yaml index 9d289a2d6c..eea9348072 100644 --- a/sample-operators/leader-election/k8s/operator.yaml +++ b/sample-operators/leader-election/k8s/operator.yaml @@ -50,7 +50,7 @@ rules: verbs: - '*' - apiGroups: - - "sample.javaoperatorsdk" + - "sample.operator.javaoperatorsdk.io" resources: - leaderelections - leaderelections/status diff --git a/sample-operators/leader-election/pom.xml b/sample-operators/leader-election/pom.xml index 2d54b84c09..d686634ad7 100644 --- a/sample-operators/leader-election/pom.xml +++ b/sample-operators/leader-election/pom.xml @@ -1,105 +1,98 @@ - - 4.0.0 + + 4.0.0 - - io.javaoperatorsdk - sample-operators - 4.9.7-SNAPSHOT - - - sample-leader-election - Operator SDK - Samples - Leader Election - An E2E test for leader election - jar - - - 11 - 11 - 3.4.3 - + + io.javaoperatorsdk + sample-operators + 5.0.0-SNAPSHOT + - - - - io.javaoperatorsdk - operator-framework-bom - ${project.version} - pom - import - - - + sample-leader-election + jar + Operator SDK - Samples - Leader Election + An E2E test for leader election + - - io.javaoperatorsdk - operator-framework - - - org.apache.logging.log4j - log4j-slf4j-impl - - - org.takes - takes - 1.24.4 - - - org.awaitility - awaitility - compile - - - io.javaoperatorsdk - operator-framework-junit-5 - test - - - org.junit.jupiter - junit-jupiter-params - test - + + io.javaoperatorsdk + operator-framework-bom + ${project.version} + pom + import + - - - - com.google.cloud.tools - jib-maven-plugin - ${jib-maven-plugin.version} - - - gcr.io/distroless/java:11 - - - leader-election-operator - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.12.1 - - - - io.fabric8 - java-generator-maven-plugin - ${fabric8-client.version} - - - - generate - - - - - src/main/resources/kubernetes - - - - + + + + + io.javaoperatorsdk + operator-framework + + + org.apache.logging.log4j + log4j-slf4j2-impl + compile + + + org.apache.logging.log4j + log4j-core + compile + + + org.takes + takes + 1.24.4 + + + org.awaitility + awaitility + compile + + + io.javaoperatorsdk + operator-framework-junit-5 + test + + + org.junit.jupiter + junit-jupiter-params + test + + + + + + com.google.cloud.tools + jib-maven-plugin + ${jib-maven-plugin.version} + + + gcr.io/distroless/java17-debian11 + + + leader-election-operator + + + + + + io.fabric8 + java-generator-maven-plugin + ${fabric8-client.version} + + src/main/resources/kubernetes + + + + + generate + + + + + + diff --git a/sample-operators/leader-election/src/main/java/io/javaoperatorsdk/operator/sample/LeaderElectionTestOperator.java b/sample-operators/leader-election/src/main/java/io/javaoperatorsdk/operator/sample/LeaderElectionTestOperator.java index 262c0a7c70..359272e0ef 100644 --- a/sample-operators/leader-election/src/main/java/io/javaoperatorsdk/operator/sample/LeaderElectionTestOperator.java +++ b/sample-operators/leader-election/src/main/java/io/javaoperatorsdk/operator/sample/LeaderElectionTestOperator.java @@ -3,7 +3,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.fabric8.kubernetes.client.KubernetesClientBuilder; import io.javaoperatorsdk.operator.Operator; import io.javaoperatorsdk.operator.api.config.LeaderElectionConfiguration; @@ -22,9 +21,8 @@ public static void main(String[] args) { ? new LeaderElectionConfiguration("leader-election-test") : new LeaderElectionConfiguration("leader-election-test", namespace, identity); - var client = new KubernetesClientBuilder().build(); Operator operator = - new Operator(client, c -> c.withLeaderElectionConfiguration(leaderElectionConfiguration)); + new Operator(c -> c.withLeaderElectionConfiguration(leaderElectionConfiguration)); operator.register(new LeaderElectionTestReconciler(identity)); operator.start(); diff --git a/sample-operators/leader-election/src/main/java/io/javaoperatorsdk/operator/sample/LeaderElectionTestReconciler.java b/sample-operators/leader-election/src/main/java/io/javaoperatorsdk/operator/sample/LeaderElectionTestReconciler.java index 4cd8627328..1e54ddd915 100644 --- a/sample-operators/leader-election/src/main/java/io/javaoperatorsdk/operator/sample/LeaderElectionTestReconciler.java +++ b/sample-operators/leader-election/src/main/java/io/javaoperatorsdk/operator/sample/LeaderElectionTestReconciler.java @@ -7,9 +7,8 @@ import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; - -import javaoperatorsdk.sample.v1.LeaderElection; -import javaoperatorsdk.sample.v1.LeaderElectionStatus; +import io.javaoperatorsdk.operator.sample.v1.LeaderElection; +import io.javaoperatorsdk.operator.sample.v1.LeaderElectionStatus; @ControllerConfiguration() public class LeaderElectionTestReconciler @@ -35,7 +34,7 @@ public UpdateControl reconcile( resource.getStatus().getReconciledBy().add(reconcilerName); // update status is with optimistic locking - return UpdateControl.updateStatus(resource).rescheduleAfter(Duration.ofSeconds(1)); + return UpdateControl.patchStatus(resource).rescheduleAfter(Duration.ofSeconds(1)); } } diff --git a/sample-operators/leader-election/src/main/resources/kubernetes/leaderelections.sample.javaoperatorsdk-v1.yml b/sample-operators/leader-election/src/main/resources/kubernetes/leaderelections.sample.javaoperatorsdk-v1.yml index cc9d8c3fc6..e0580f8901 100644 --- a/sample-operators/leader-election/src/main/resources/kubernetes/leaderelections.sample.javaoperatorsdk-v1.yml +++ b/sample-operators/leader-election/src/main/resources/kubernetes/leaderelections.sample.javaoperatorsdk-v1.yml @@ -4,9 +4,9 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: - name: leaderelections.sample.javaoperatorsdk + name: leaderelections.sample.operator.javaoperatorsdk.io spec: - group: sample.javaoperatorsdk + group: sample.operator.javaoperatorsdk.io names: kind: LeaderElection singular: leaderelection diff --git a/sample-operators/leader-election/src/test/java/io/javaoperatorsdk/operator/sample/LeaderElectionE2E.java b/sample-operators/leader-election/src/test/java/io/javaoperatorsdk/operator/sample/LeaderElectionE2E.java index 7932472aab..863407999d 100644 --- a/sample-operators/leader-election/src/test/java/io/javaoperatorsdk/operator/sample/LeaderElectionE2E.java +++ b/sample-operators/leader-election/src/test/java/io/javaoperatorsdk/operator/sample/LeaderElectionE2E.java @@ -26,8 +26,7 @@ import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.KubernetesClientBuilder; - -import javaoperatorsdk.sample.v1.LeaderElection; +import io.javaoperatorsdk.operator.sample.v1.LeaderElection; import static io.javaoperatorsdk.operator.junit.AbstractOperatorExtension.CRD_READY_WAIT; import static org.assertj.core.api.Assertions.assertThat; diff --git a/sample-operators/mysql-schema/pom.xml b/sample-operators/mysql-schema/pom.xml index 763bc21330..46d555966c 100644 --- a/sample-operators/mysql-schema/pom.xml +++ b/sample-operators/mysql-schema/pom.xml @@ -1,116 +1,108 @@ - - 4.0.0 + + 4.0.0 - - io.javaoperatorsdk - sample-operators - 4.9.7-SNAPSHOT - - - sample-mysql-schema-operator - Operator SDK - Samples - MySQL Schema - Provisions Schemas in a MySQL database - jar - - - 11 - 11 - 3.4.3 - + + io.javaoperatorsdk + sample-operators + 5.0.0-SNAPSHOT + - - - - io.javaoperatorsdk - operator-framework-bom - ${project.version} - pom - import - - - + sample-mysql-schema-operator + jar + Operator SDK - Samples - MySQL Schema + Provisions Schemas in a MySQL database + - - io.javaoperatorsdk - operator-framework - - - io.javaoperatorsdk - micrometer-support - - - org.takes - takes - 1.24.4 - - - mysql - mysql-connector-java - 8.0.30 - - - io.fabric8 - crd-generator-apt - provided - - - org.apache.logging.log4j - log4j-slf4j-impl - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.awaitility - awaitility - test - - - io.javaoperatorsdk - operator-framework-junit-5 - test - + + io.javaoperatorsdk + operator-framework-bom + ${project.version} + pom + import + + + + + + io.javaoperatorsdk + operator-framework + + + io.javaoperatorsdk + micrometer-support + + + org.takes + takes + 1.24.4 + + + mysql + mysql-connector-java + 8.0.30 + + + io.fabric8 + crd-generator-apt + provided + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-core + compile + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.awaitility + awaitility + test + + + io.javaoperatorsdk + operator-framework-junit-5 + test + + - - - - org.apache.maven.plugins - maven-surefire-plugin - - 0 - - - - com.google.cloud.tools - jib-maven-plugin - ${jib-maven-plugin.version} - - - gcr.io/distroless/java:11 - - - mysql-schema-operator - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.12.1 - - - + + + + org.apache.maven.plugins + maven-surefire-plugin + + 0 + + + + com.google.cloud.tools + jib-maven-plugin + ${jib-maven-plugin.version} + + + gcr.io/distroless/java17-debian11 + + + mysql-schema-operator + + + + + - \ No newline at end of file + diff --git a/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/MySQLDbConfig.java b/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/MySQLDbConfig.java index 7cc06dd373..0f63cc846a 100644 --- a/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/MySQLDbConfig.java +++ b/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/MySQLDbConfig.java @@ -43,4 +43,3 @@ public String getPassword() { return password; } } - diff --git a/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/MySQLSchemaOperator.java b/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/MySQLSchemaOperator.java index e9e1ac1d49..ce3595f0c3 100644 --- a/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/MySQLSchemaOperator.java +++ b/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/MySQLSchemaOperator.java @@ -1,6 +1,7 @@ package io.javaoperatorsdk.operator.sample; import java.io.IOException; +import java.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,7 +32,8 @@ public static void main(String[] args) throws IOException { operator.register(schemaReconciler, configOverrider -> configOverrider.replacingNamedDependentResourceConfig( SchemaDependentResource.NAME, - new ResourcePollerConfig(300, MySQLDbConfig.loadFromEnvironmentVars()))); + new ResourcePollerConfig(Duration.ofMillis(300), + MySQLDbConfig.loadFromEnvironmentVars()))); operator.start(); new FtBasic(new TkFork(new FkRegex("/health", "ALL GOOD!")), 8080).start(Exit.NEVER); diff --git a/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/MySQLSchemaReconciler.java b/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/MySQLSchemaReconciler.java index 95db43b228..7e229ca4bd 100644 --- a/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/MySQLSchemaReconciler.java +++ b/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/MySQLSchemaReconciler.java @@ -3,13 +3,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.api.model.Secret; -import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; -import io.javaoperatorsdk.operator.api.reconciler.ErrorStatusHandler; -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.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; import io.javaoperatorsdk.operator.sample.dependent.SchemaDependentResource; import io.javaoperatorsdk.operator.sample.dependent.SecretDependentResource; @@ -19,14 +15,14 @@ import static io.javaoperatorsdk.operator.sample.dependent.SecretDependentResource.MYSQL_SECRET_USERNAME; import static java.lang.String.format; -@ControllerConfiguration( - dependents = { - @Dependent(type = SecretDependentResource.class, name = SecretDependentResource.NAME), - @Dependent(type = SchemaDependentResource.class, name = SchemaDependentResource.NAME, - dependsOn = SecretDependentResource.NAME) - }) +@Workflow(dependents = { + @Dependent(type = SecretDependentResource.class, name = SecretDependentResource.NAME), + @Dependent(type = SchemaDependentResource.class, name = SchemaDependentResource.NAME, + dependsOn = SecretDependentResource.NAME) +}) +@ControllerConfiguration public class MySQLSchemaReconciler - implements Reconciler, ErrorStatusHandler { + implements Reconciler { static final Logger log = LoggerFactory.getLogger(MySQLSchemaReconciler.class); @@ -38,10 +34,10 @@ public UpdateControl reconcile(MySQLSchema schema, Context { - updateStatusPojo(schema, s, secret.getMetadata().getName(), + var statusUpdateResource = createForStatusUpdate(schema, s, secret.getMetadata().getName(), decode(secret.getData().get(MYSQL_SECRET_USERNAME))); log.info("Schema {} created - updating CR status", s.getName()); - return UpdateControl.patchStatus(schema); + return UpdateControl.patchStatus(statusUpdateResource); }).orElseGet(UpdateControl::noUpdate); } @@ -55,12 +51,18 @@ public ErrorStatusUpdateControl updateErrorStatus(MySQLSchema schem status.setSecretName(null); status.setStatus("ERROR: " + e.getMessage()); schema.setStatus(status); - return ErrorStatusUpdateControl.updateStatus(schema); + return ErrorStatusUpdateControl.patchStatus(schema); } - private void updateStatusPojo(MySQLSchema mySQLSchema, Schema schema, String secretName, + private MySQLSchema createForStatusUpdate(MySQLSchema mySQLSchema, Schema schema, + String secretName, String userName) { + MySQLSchema res = new MySQLSchema(); + res.setMetadata(new ObjectMetaBuilder() + .withName(mySQLSchema.getMetadata().getName()) + .withNamespace(mySQLSchema.getMetadata().getNamespace()) + .build()); SchemaStatus status = new SchemaStatus(); status.setUrl( format( @@ -69,6 +71,7 @@ private void updateStatusPojo(MySQLSchema mySQLSchema, Schema schema, String sec status.setUserName(userName); status.setSecretName(secretName); status.setStatus("CREATED"); - mySQLSchema.setStatus(status); + res.setStatus(status); + return res; } } diff --git a/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/SchemaStatus.java b/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/SchemaStatus.java index 92ddb67a63..168cd8db15 100644 --- a/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/SchemaStatus.java +++ b/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/SchemaStatus.java @@ -1,8 +1,6 @@ package io.javaoperatorsdk.operator.sample; -import io.javaoperatorsdk.operator.api.ObservedGenerationAwareStatus; - -public class SchemaStatus extends ObservedGenerationAwareStatus { +public class SchemaStatus { private String url; diff --git a/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/dependent/ResourcePollerConfig.java b/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/dependent/ResourcePollerConfig.java index 5e9cc3f964..44de818f88 100644 --- a/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/dependent/ResourcePollerConfig.java +++ b/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/dependent/ResourcePollerConfig.java @@ -1,19 +1,21 @@ package io.javaoperatorsdk.operator.sample.dependent; +import java.time.Duration; + import io.javaoperatorsdk.operator.sample.MySQLDbConfig; public class ResourcePollerConfig { - private final int pollPeriod; + private final Duration pollPeriod; private final MySQLDbConfig mySQLDbConfig; - public ResourcePollerConfig(int pollPeriod, MySQLDbConfig mySQLDbConfig) { + public ResourcePollerConfig(Duration pollPeriod, MySQLDbConfig mySQLDbConfig) { this.pollPeriod = pollPeriod; this.mySQLDbConfig = mySQLDbConfig; } - public int getPollPeriod() { + public Duration getPollPeriod() { return pollPeriod; } diff --git a/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/dependent/SchemaDependentResource.java b/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/dependent/SchemaDependentResource.java index 77d8932e58..60875e6ae3 100644 --- a/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/dependent/SchemaDependentResource.java +++ b/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/dependent/SchemaDependentResource.java @@ -3,6 +3,7 @@ import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; +import java.time.Duration; import java.util.Base64; import java.util.Collections; import java.util.Optional; @@ -15,9 +16,10 @@ import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.config.dependent.ConfigurationConverter; import io.javaoperatorsdk.operator.api.config.dependent.Configured; +import io.javaoperatorsdk.operator.api.config.dependent.DependentResourceSpec; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.dependent.Deleter; -import io.javaoperatorsdk.operator.api.reconciler.dependent.managed.DependentResourceConfigurator; +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.javaoperatorsdk.operator.sample.MySQLDbConfig; @@ -30,14 +32,14 @@ import static io.javaoperatorsdk.operator.sample.dependent.SecretDependentResource.MYSQL_SECRET_USERNAME; import static java.lang.String.format; -@SchemaConfig(pollPeriod = 700, host = "127.0.0.1", +@SchemaConfig(pollPeriod = 400, host = "127.0.0.1", port = SchemaDependentResource.LOCAL_PORT, user = "root", password = "password") // NOSONAR: password is only used locally, example only @Configured(by = SchemaConfig.class, with = ResourcePollerConfig.class, converter = ResourcePollerConfigConverter.class) public class SchemaDependentResource extends PerResourcePollingDependentResource - implements DependentResourceConfigurator, + implements ConfiguredDependentResource, Creator, Deleter { public static final String NAME = "schema"; @@ -52,7 +54,7 @@ public SchemaDependentResource() { @Override public Optional configuration() { - return Optional.of(new ResourcePollerConfig((int) getPollingPeriod(), dbConfig)); + return Optional.of(new ResourcePollerConfig(getPollingPeriod(), dbConfig)); } @Override @@ -63,7 +65,9 @@ public void configureWith(ResourcePollerConfig config) { @Override public Schema desired(MySQLSchema primary, Context context) { - return new Schema(primary.getMetadata().getName(), primary.getSpec().getEncoding()); + var desired = new Schema(primary.getMetadata().getName(), primary.getSpec().getEncoding()); + log.debug("Desired schema: {}", desired); + return desired; } @Override @@ -72,6 +76,7 @@ public Schema create(Schema target, MySQLSchema mySQLSchema, Context fetchResources(MySQLSchema primaryResource) { try (Connection connection = getConnection()) { - return SchemaService.getSchema(connection, primaryResource.getMetadata().getName()) + var schema = SchemaService.getSchema(connection, primaryResource.getMetadata().getName()) .map(Set::of).orElseGet(Collections::emptySet); + log.debug("Fetched schema: {}", schema); + return schema; } catch (SQLException e) { throw new RuntimeException("Error while trying read Schema", e); } } static class ResourcePollerConfigConverter implements - ConfigurationConverter { + ConfigurationConverter { @Override public ResourcePollerConfig configFrom(SchemaConfig configAnnotation, - ControllerConfiguration parentConfiguration, - Class originatingClass) { + DependentResourceSpec spec, + ControllerConfiguration parentConfiguration) { if (configAnnotation != null) { - return new ResourcePollerConfig(configAnnotation.pollPeriod(), + return new ResourcePollerConfig(Duration.ofMillis(configAnnotation.pollPeriod()), new MySQLDbConfig(configAnnotation.host(), String.valueOf(configAnnotation.port()), configAnnotation.user(), configAnnotation.password())); } - return new ResourcePollerConfig(SchemaConfig.DEFAULT_POLL_PERIOD, + return new ResourcePollerConfig(Duration.ofMillis(SchemaConfig.DEFAULT_POLL_PERIOD), MySQLDbConfig.loadFromEnvironmentVars()); } } diff --git a/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/dependent/SecretDependentResource.java b/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/dependent/SecretDependentResource.java index edaa5707ee..e6cf2a45e7 100644 --- a/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/dependent/SecretDependentResource.java +++ b/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/dependent/SecretDependentResource.java @@ -10,13 +10,16 @@ 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.KubernetesDependent; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; import io.javaoperatorsdk.operator.processing.event.ResourceID; import io.javaoperatorsdk.operator.processing.event.source.SecondaryToPrimaryMapper; import io.javaoperatorsdk.operator.sample.MySQLSchema; +@KubernetesDependent public class SecretDependentResource extends KubernetesDependentResource implements Creator, SecondaryToPrimaryMapper { + public static final String NAME = "secret"; public static final String SECRET_SUFFIX = "-secret"; public static final String SECRET_FORMAT = "%s" + SECRET_SUFFIX; @@ -60,10 +63,12 @@ public Result match(Secret actual, MySQLSchema primary, Context toPrimaryResourceIDs(Secret resource) { String name = resource.getMetadata().getName(); return Set.of(new ResourceID(name.substring(0, name.length() - SECRET_SUFFIX.length()), resource.getMetadata().getNamespace())); } + } diff --git a/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/schema/Schema.java b/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/schema/Schema.java index 34c1e54255..87fb88e9a4 100644 --- a/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/schema/Schema.java +++ b/sample-operators/mysql-schema/src/main/java/io/javaoperatorsdk/operator/sample/schema/Schema.java @@ -28,11 +28,19 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; Schema schema = (Schema) o; - return Objects.equals(name, schema.name) && Objects.equals(characterSet, schema.characterSet); + return Objects.equals(name, schema.name); } @Override public int hashCode() { return Objects.hash(name, characterSet); } + + @Override + public String toString() { + return "Schema{" + + "name='" + name + '\'' + + ", characterSet='" + characterSet + '\'' + + '}'; + } } diff --git a/sample-operators/pom.xml b/sample-operators/pom.xml index 2bac775237..478508f9d5 100644 --- a/sample-operators/pom.xml +++ b/sample-operators/pom.xml @@ -1,27 +1,22 @@ - - 4.0.0 + + 4.0.0 - - io.javaoperatorsdk - java-operator-sdk - 4.9.7-SNAPSHOT - + + io.javaoperatorsdk + java-operator-sdk + 5.0.0-SNAPSHOT + - sample-operators - Operator SDK - Samples - pom + sample-operators + pom + Operator SDK - Samples - - 3.1.4 - - - - tomcat-operator - webpage - mysql-schema - leader-election - + + tomcat-operator + webpage + mysql-schema + leader-election + controller-namespace-deletion + diff --git a/sample-operators/tomcat-operator/pom.xml b/sample-operators/tomcat-operator/pom.xml index 16bc0ed783..d22260c614 100644 --- a/sample-operators/tomcat-operator/pom.xml +++ b/sample-operators/tomcat-operator/pom.xml @@ -1,118 +1,110 @@ - - 4.0.0 + + 4.0.0 - - io.javaoperatorsdk - sample-operators - 4.9.7-SNAPSHOT - - - sample-tomcat-operator - Operator SDK - Samples - Tomcat - Provisions Tomcat Pods and deploys Webapplications in them - jar - - - 11 - 11 - 3.4.3 - + + io.javaoperatorsdk + sample-operators + 5.0.0-SNAPSHOT + - - - - io.javaoperatorsdk - operator-framework-bom - ${project.version} - pom - import - - - + sample-tomcat-operator + jar + Operator SDK - Samples - Tomcat + Provisions Tomcat Pods and deploys Webapplications in them + - - io.javaoperatorsdk - operator-framework - - - io.fabric8 - kubernetes-httpclient-okhttp - - - - - io.fabric8 - kubernetes-httpclient-vertx - - - io.fabric8 - crd-generator-apt - provided - - - org.apache.logging.log4j - log4j-slf4j-impl - - - org.takes - takes - 1.24.4 - - - org.junit.jupiter - junit-jupiter-api - test - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.awaitility - awaitility - 4.2.0 - test - - - io.javaoperatorsdk - operator-framework-junit-5 - test - + + io.javaoperatorsdk + operator-framework-bom + ${project.version} + pom + import + + + + + + io.javaoperatorsdk + operator-framework + + + io.fabric8 + kubernetes-httpclient-okhttp + + + + + io.fabric8 + kubernetes-httpclient-vertx + + + io.fabric8 + crd-generator-apt + provided + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-core + compile + + + org.takes + takes + 1.24.4 + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.awaitility + awaitility + 4.2.0 + test + + + io.javaoperatorsdk + operator-framework-junit-5 + test + + - - - - org.apache.maven.plugins - maven-surefire-plugin - - 0 - - - - com.google.cloud.tools - jib-maven-plugin - ${jib-maven-plugin.version} - - - gcr.io/distroless/java:11 - - - tomcat-operator - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.12.1 - - - + + + + org.apache.maven.plugins + maven-surefire-plugin + + 0 + + + + com.google.cloud.tools + jib-maven-plugin + ${jib-maven-plugin.version} + + + gcr.io/distroless/java17-debian11 + + + tomcat-operator + + + + + - \ No newline at end of file + diff --git a/sample-operators/tomcat-operator/src/main/java/io/javaoperatorsdk/operator/sample/DeploymentDependentResource.java b/sample-operators/tomcat-operator/src/main/java/io/javaoperatorsdk/operator/sample/DeploymentDependentResource.java index 25e46fad16..d6eaad24bb 100644 --- a/sample-operators/tomcat-operator/src/main/java/io/javaoperatorsdk/operator/sample/DeploymentDependentResource.java +++ b/sample-operators/tomcat-operator/src/main/java/io/javaoperatorsdk/operator/sample/DeploymentDependentResource.java @@ -4,11 +4,13 @@ import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder; import io.javaoperatorsdk.operator.ReconcilerUtils; +import io.javaoperatorsdk.operator.api.config.informer.Informer; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; -@KubernetesDependent(labelSelector = "app.kubernetes.io/managed-by=tomcat-operator") +@KubernetesDependent(informer = @Informer( + labelSelector = "app.kubernetes.io/managed-by=tomcat-operator")) public class DeploymentDependentResource extends CRUDKubernetesDependentResource { diff --git a/sample-operators/tomcat-operator/src/main/java/io/javaoperatorsdk/operator/sample/ServiceDependentResource.java b/sample-operators/tomcat-operator/src/main/java/io/javaoperatorsdk/operator/sample/ServiceDependentResource.java index 3b526d02bc..8a93b48804 100644 --- a/sample-operators/tomcat-operator/src/main/java/io/javaoperatorsdk/operator/sample/ServiceDependentResource.java +++ b/sample-operators/tomcat-operator/src/main/java/io/javaoperatorsdk/operator/sample/ServiceDependentResource.java @@ -4,11 +4,13 @@ import io.fabric8.kubernetes.api.model.Service; import io.fabric8.kubernetes.api.model.ServiceBuilder; import io.javaoperatorsdk.operator.ReconcilerUtils; +import io.javaoperatorsdk.operator.api.config.informer.Informer; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; -@KubernetesDependent(labelSelector = "app.kubernetes.io/managed-by=tomcat-operator") +@KubernetesDependent(informer = @Informer( + labelSelector = "app.kubernetes.io/managed-by=tomcat-operator")) public class ServiceDependentResource extends CRUDKubernetesDependentResource { public ServiceDependentResource() { diff --git a/sample-operators/tomcat-operator/src/main/java/io/javaoperatorsdk/operator/sample/TomcatReconciler.java b/sample-operators/tomcat-operator/src/main/java/io/javaoperatorsdk/operator/sample/TomcatReconciler.java index de4a63431b..f89a5f22e0 100644 --- a/sample-operators/tomcat-operator/src/main/java/io/javaoperatorsdk/operator/sample/TomcatReconciler.java +++ b/sample-operators/tomcat-operator/src/main/java/io/javaoperatorsdk/operator/sample/TomcatReconciler.java @@ -5,23 +5,21 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.apps.DeploymentStatus; -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.*; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; /** * Runs a specified number of Tomcat app server Pods. It uses a Deployment to create the Pods. Also * creates a Service over which the Pods can be accessed. */ -@ControllerConfiguration( - dependents = { - @Dependent(type = DeploymentDependentResource.class), - @Dependent(type = ServiceDependentResource.class) - }) +@Workflow(dependents = { + @Dependent(type = DeploymentDependentResource.class), + @Dependent(type = ServiceDependentResource.class) +}) +@ControllerConfiguration public class TomcatReconciler implements Reconciler { private final Logger log = LoggerFactory.getLogger(getClass()); @@ -29,23 +27,28 @@ public class TomcatReconciler implements Reconciler { @Override public UpdateControl reconcile(Tomcat tomcat, Context context) { return context.getSecondaryResource(Deployment.class).map(deployment -> { - Tomcat updatedTomcat = updateTomcatStatus(tomcat, deployment); + Tomcat updatedTomcat = createTomcatForStatusUpdate(tomcat, deployment); log.info( "Updating status of Tomcat {} in namespace {} to {} ready replicas", tomcat.getMetadata().getName(), tomcat.getMetadata().getNamespace(), - tomcat.getStatus().getReadyReplicas()); + tomcat.getStatus() == null ? 0 : tomcat.getStatus().getReadyReplicas()); return UpdateControl.patchStatus(updatedTomcat); }).orElseGet(UpdateControl::noUpdate); } - private Tomcat updateTomcatStatus(Tomcat tomcat, Deployment deployment) { + private Tomcat createTomcatForStatusUpdate(Tomcat tomcat, Deployment deployment) { + Tomcat res = new Tomcat(); + res.setMetadata(new ObjectMetaBuilder() + .withName(tomcat.getMetadata().getName()) + .withNamespace(tomcat.getMetadata().getNamespace()) + .build()); DeploymentStatus deploymentStatus = Objects.requireNonNullElse(deployment.getStatus(), new DeploymentStatus()); int readyReplicas = Objects.requireNonNullElse(deploymentStatus.getReadyReplicas(), 0); TomcatStatus status = new TomcatStatus(); status.setReadyReplicas(readyReplicas); - tomcat.setStatus(status); - return tomcat; + res.setStatus(status); + return res; } } diff --git a/sample-operators/tomcat-operator/src/main/java/io/javaoperatorsdk/operator/sample/WebappReconciler.java b/sample-operators/tomcat-operator/src/main/java/io/javaoperatorsdk/operator/sample/WebappReconciler.java index 5b87d23aac..82d0152b3c 100644 --- a/sample-operators/tomcat-operator/src/main/java/io/javaoperatorsdk/operator/sample/WebappReconciler.java +++ b/sample-operators/tomcat-operator/src/main/java/io/javaoperatorsdk/operator/sample/WebappReconciler.java @@ -2,7 +2,6 @@ import java.io.ByteArrayOutputStream; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.CompletableFuture; @@ -14,18 +13,18 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.dsl.ExecListener; import io.fabric8.kubernetes.client.dsl.ExecWatch; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; import io.javaoperatorsdk.operator.api.reconciler.Cleaner; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; import io.javaoperatorsdk.operator.api.reconciler.DeleteControl; import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; -import io.javaoperatorsdk.operator.api.reconciler.EventSourceInitializer; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.javaoperatorsdk.operator.processing.event.ResourceID; @@ -35,7 +34,7 @@ @ControllerConfiguration public class WebappReconciler - implements Reconciler, Cleaner, EventSourceInitializer { + implements Reconciler, Cleaner { private static final Logger log = LoggerFactory.getLogger(WebappReconciler.class); @@ -46,7 +45,7 @@ public WebappReconciler(KubernetesClient kubernetesClient) { } @Override - public Map prepareEventSources(EventSourceContext context) { + public List> prepareEventSources(EventSourceContext context) { /* * To create an event to a related WebApp resource and trigger the reconciliation we need to * find which WebApp this Tomcat custom resource is related to. To find the related @@ -59,15 +58,14 @@ public Map prepareEventSources(EventSourceContext c .map(ResourceID::fromResource) .collect(Collectors.toSet()); - InformerConfiguration configuration = - InformerConfiguration.from(Tomcat.class, context) + InformerEventSourceConfiguration configuration = + InformerEventSourceConfiguration.from(Tomcat.class, Webapp.class) .withSecondaryToPrimaryMapper(webappsMatchingTomcatName) .withPrimaryToSecondaryMapper( (Webapp primary) -> Set.of(new ResourceID(primary.getSpec().getTomcat(), primary.getMetadata().getNamespace()))) .build(); - return EventSourceInitializer - .nameEventSources(new InformerEventSource<>(configuration, context)); + return List.of(new InformerEventSource<>(configuration, context)); } /** @@ -101,12 +99,7 @@ public UpdateControl reconcile(Webapp webapp, Context context) { String[] commandStatusInAllPods = executeCommandInAllPods(kubernetesClient, webapp, command); - if (webapp.getStatus() == null) { - webapp.setStatus(new WebappStatus()); - } - webapp.getStatus().setDeployedArtifact(webapp.getSpec().getUrl()); - webapp.getStatus().setDeploymentStatus(commandStatusInAllPods); - return UpdateControl.patchStatus(webapp); + return UpdateControl.patchStatus(createWebAppForStatusUpdate(webapp, commandStatusInAllPods)); } else { log.info("WebappController invoked but Tomcat not ready yet ({}/{})", tomcat.getStatus() != null ? tomcat.getStatus().getReadyReplicas() : 0, @@ -115,6 +108,18 @@ public UpdateControl reconcile(Webapp webapp, Context context) { } } + private Webapp createWebAppForStatusUpdate(Webapp actual, String[] commandStatusInAllPods) { + var webapp = new Webapp(); + webapp.setMetadata(new ObjectMetaBuilder() + .withName(actual.getMetadata().getName()) + .withNamespace(actual.getMetadata().getNamespace()) + .build()); + webapp.setStatus(new WebappStatus()); + webapp.getStatus().setDeployedArtifact(actual.getSpec().getUrl()); + webapp.getStatus().setDeploymentStatus(commandStatusInAllPods); + return webapp; + } + @Override public DeleteControl cleanup(Webapp webapp, Context context) { @@ -157,14 +162,14 @@ private String[] executeCommandInAllPods( CompletableFuture data = new CompletableFuture<>(); try (ExecWatch execWatch = execCmd(pod, data, command)) { - status[i] = "" + pod.getMetadata().getName() + ":" + data.get(30, TimeUnit.SECONDS); + status[i] = pod.getMetadata().getName() + ":" + data.get(30, TimeUnit.SECONDS); } catch (ExecutionException e) { - status[i] = "" + pod.getMetadata().getName() + ": ExecutionException - " + e.getMessage(); + status[i] = pod.getMetadata().getName() + ": ExecutionException - " + e.getMessage(); } catch (InterruptedException e) { status[i] = - "" + pod.getMetadata().getName() + ": InterruptedException - " + e.getMessage(); + pod.getMetadata().getName() + ": InterruptedException - " + e.getMessage(); } catch (TimeoutException e) { - status[i] = "" + pod.getMetadata().getName() + ": TimeoutException - " + e.getMessage(); + status[i] = pod.getMetadata().getName() + ": TimeoutException - " + e.getMessage(); } } } diff --git a/sample-operators/webpage/pom.xml b/sample-operators/webpage/pom.xml index 10dba61c41..34b6846b94 100644 --- a/sample-operators/webpage/pom.xml +++ b/sample-operators/webpage/pom.xml @@ -1,89 +1,81 @@ - - 4.0.0 + + 4.0.0 - - io.javaoperatorsdk - sample-operators - 4.9.7-SNAPSHOT - - - sample-webpage-operator - Operator SDK - Samples - WebPage - Provisions an nginx Webserver based on a CRD with give html - jar - - - 11 - 11 - 3.4.3 - + + io.javaoperatorsdk + sample-operators + 5.0.0-SNAPSHOT + - - - - io.javaoperatorsdk - operator-framework-bom - ${project.version} - pom - import - - - + sample-webpage-operator + jar + Operator SDK - Samples - WebPage + Provisions an nginx Webserver based on a CRD with give html + - - io.javaoperatorsdk - operator-framework - - - org.apache.logging.log4j - log4j-slf4j-impl - - - org.takes - takes - 1.24.4 - - - io.fabric8 - crd-generator-apt - provided - - - org.awaitility - awaitility - compile - - - io.javaoperatorsdk - operator-framework-junit-5 - test - + + io.javaoperatorsdk + operator-framework-bom + ${project.version} + pom + import + - - - - com.google.cloud.tools - jib-maven-plugin - ${jib-maven-plugin.version} - - - gcr.io/distroless/java:11 - - - webpage-operator - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.12.1 - - - + + + + + io.javaoperatorsdk + operator-framework + + + org.apache.logging.log4j + log4j-slf4j2-impl + + + org.apache.logging.log4j + log4j-core + compile + + + org.takes + takes + 1.24.4 + + + io.fabric8 + crd-generator-apt + provided + + + org.awaitility + awaitility + compile + + + io.javaoperatorsdk + operator-framework-junit-5 + test + + + + + + com.google.cloud.tools + jib-maven-plugin + ${jib-maven-plugin.version} + + + gcr.io/distroless/java17-debian11 + + + webpage-operator + + + + + - \ No newline at end of file + diff --git a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/Utils.java b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/Utils.java index b37b98aa52..72d04b42ed 100644 --- a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/Utils.java +++ b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/Utils.java @@ -1,5 +1,6 @@ package io.javaoperatorsdk.operator.sample; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.api.model.networking.v1.Ingress; import io.javaoperatorsdk.operator.api.reconciler.ErrorStatusUpdateControl; import io.javaoperatorsdk.operator.sample.customresource.WebPage; @@ -11,6 +12,16 @@ public class Utils { private Utils() {} + public static WebPage createWebPageForStatusUpdate(WebPage webPage, String configMapName) { + WebPage res = new WebPage(); + res.setMetadata(new ObjectMetaBuilder() + .withName(webPage.getMetadata().getName()) + .withNamespace(webPage.getMetadata().getNamespace()) + .build()); + res.setStatus(createStatus(configMapName)); + return res; + } + public static WebPageStatus createStatus(String configMapName) { WebPageStatus status = new WebPageStatus(); status.setHtmlConfigMap(configMapName); @@ -33,7 +44,7 @@ public static String serviceName(WebPage webPage) { public static ErrorStatusUpdateControl handleError(WebPage resource, Exception e) { resource.getStatus().setErrorMessage("Error: " + e.getMessage()); - return ErrorStatusUpdateControl.updateStatus(resource); + return ErrorStatusUpdateControl.patchStatus(resource); } public static void simulateErrorIfRequested(WebPage webPage) throws ErrorSimulationException { diff --git a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageDependentsWorkflowReconciler.java b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageDependentsWorkflowReconciler.java index 8494af5402..4dc75122f2 100644 --- a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageDependentsWorkflowReconciler.java +++ b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageDependentsWorkflowReconciler.java @@ -1,13 +1,15 @@ package io.javaoperatorsdk.operator.sample; import java.util.Arrays; -import java.util.Map; +import java.util.List; import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.Service; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.networking.v1.Ingress; import io.fabric8.kubernetes.client.KubernetesClient; +import io.javaoperatorsdk.operator.api.config.informer.Informer; +import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; import io.javaoperatorsdk.operator.api.reconciler.*; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResourceConfigBuilder; @@ -23,10 +25,11 @@ * Shows how to implement reconciler using standalone dependent resources. */ @ControllerConfiguration( - labelSelector = WebPageDependentsWorkflowReconciler.DEPENDENT_RESOURCE_LABEL_SELECTOR) + informer = @Informer( + labelSelector = WebPageDependentsWorkflowReconciler.DEPENDENT_RESOURCE_LABEL_SELECTOR)) @SuppressWarnings("unused") public class WebPageDependentsWorkflowReconciler - implements Reconciler, ErrorStatusHandler, EventSourceInitializer { + implements Reconciler { public static final String DEPENDENT_RESOURCE_LABEL_SELECTOR = "!low-level"; @@ -43,13 +46,14 @@ public WebPageDependentsWorkflowReconciler(KubernetesClient kubernetesClient) { .addDependentResource(configMapDR) .addDependentResource(deploymentDR) .addDependentResource(serviceDR) - .addDependentResource(ingressDR).withReconcilePrecondition(new ExposedIngressCondition()) + .addDependentResourceAndConfigure(ingressDR) + .withReconcilePrecondition(new ExposedIngressCondition()) .build(); } @Override - public Map prepareEventSources(EventSourceContext context) { - return EventSourceInitializer.nameEventSourcesFromDependentResource(context, configMapDR, + public List> prepareEventSources(EventSourceContext context) { + return EventSourceUtils.dependentEventSources(context, configMapDR, deploymentDR, serviceDR, ingressDR); } @@ -61,10 +65,10 @@ public UpdateControl reconcile(WebPage webPage, Context contex workflow.reconcile(webPage, context); - webPage.setStatus( - createStatus( - context.getSecondaryResource(ConfigMap.class).orElseThrow().getMetadata().getName())); - return UpdateControl.patchStatus(webPage); + return UpdateControl + .patchStatus( + createWebPageForStatusUpdate(webPage, context.getSecondaryResource(ConfigMap.class) + .orElseThrow().getMetadata().getName())); } @Override @@ -80,10 +84,12 @@ private void initDependentResources(KubernetesClient client) { this.serviceDR = new ServiceDependentResource(); this.ingressDR = new IngressDependentResource(); - Arrays.asList(configMapDR, deploymentDR, serviceDR, ingressDR).forEach(dr -> { - dr.configureWith(new KubernetesDependentResourceConfigBuilder() - .withLabelSelector(DEPENDENT_RESOURCE_LABEL_SELECTOR).build()); - }); + Arrays.asList(configMapDR, deploymentDR, serviceDR, ingressDR) + .forEach(dr -> dr.configureWith(new KubernetesDependentResourceConfigBuilder() + .withKubernetesDependentInformerConfig(InformerConfiguration.builder(dr.resourceType()) + .withLabelSelector(DEPENDENT_RESOURCE_LABEL_SELECTOR) + .buildForInformerEventSource()) + .build())); } } diff --git a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageManagedDependentsReconciler.java b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageManagedDependentsReconciler.java index d370cd3315..e59f7fe0fc 100644 --- a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageManagedDependentsReconciler.java +++ b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageManagedDependentsReconciler.java @@ -6,23 +6,20 @@ import io.javaoperatorsdk.operator.sample.customresource.WebPage; import io.javaoperatorsdk.operator.sample.dependentresource.*; -import static io.javaoperatorsdk.operator.sample.Utils.createStatus; -import static io.javaoperatorsdk.operator.sample.Utils.handleError; -import static io.javaoperatorsdk.operator.sample.Utils.simulateErrorIfRequested; +import static io.javaoperatorsdk.operator.sample.Utils.*; /** * Shows how to implement a reconciler with managed dependent resources. */ -@ControllerConfiguration( - dependents = { - @Dependent(type = ConfigMapDependentResource.class), - @Dependent(type = DeploymentDependentResource.class), - @Dependent(type = ServiceDependentResource.class), - @Dependent(type = IngressDependentResource.class, - reconcilePrecondition = ExposedIngressCondition.class) - }) +@Workflow(dependents = { + @Dependent(type = ConfigMapDependentResource.class), + @Dependent(type = DeploymentDependentResource.class), + @Dependent(type = ServiceDependentResource.class), + @Dependent(type = IngressDependentResource.class, + reconcilePrecondition = ExposedIngressCondition.class) +}) public class WebPageManagedDependentsReconciler - implements Reconciler, ErrorStatusHandler, Cleaner { + implements Reconciler, Cleaner { public static final String SELECTOR = "managed"; @@ -39,8 +36,7 @@ public UpdateControl reconcile(WebPage webPage, Context contex final var name = context.getSecondaryResource(ConfigMap.class).orElseThrow() .getMetadata().getName(); - webPage.setStatus(createStatus(name)); - return UpdateControl.patchStatus(webPage); + return UpdateControl.patchStatus(createWebPageForStatusUpdate(webPage, name)); } @Override diff --git a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageOperator.java b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageOperator.java index e3ab63dc54..ff80cc5901 100644 --- a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageOperator.java +++ b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageOperator.java @@ -6,8 +6,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.fabric8.kubernetes.client.KubernetesClient; -import io.fabric8.kubernetes.client.KubernetesClientBuilder; import io.javaoperatorsdk.operator.Operator; import io.javaoperatorsdk.operator.sample.probes.LivenessHandler; import io.javaoperatorsdk.operator.sample.probes.StartupHandler; @@ -28,11 +26,10 @@ public class WebPageOperator { public static void main(String[] args) throws IOException { log.info("WebServer Operator starting!"); - KubernetesClient client = new KubernetesClientBuilder().build(); - Operator operator = new Operator(client, o -> o.withStopOnInformerErrorDuringStartup(false)); + Operator operator = new Operator(o -> o.withStopOnInformerErrorDuringStartup(false)); String reconcilerEnvVar = System.getenv(WEBPAGE_RECONCILER_ENV); if (WEBPAGE_CLASSIC_RECONCILER_ENV_VALUE.equals(reconcilerEnvVar)) { - operator.register(new WebPageReconciler(client)); + operator.register(new WebPageReconciler()); } else if (WEBPAGE_MANAGED_DEPENDENT_RESOURCE_ENV_VALUE .equals(reconcilerEnvVar)) { operator.register(new WebPageManagedDependentsReconciler()); diff --git a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageReconciler.java b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageReconciler.java index 4be2da11c7..56b66fbfb3 100644 --- a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageReconciler.java +++ b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageReconciler.java @@ -1,6 +1,7 @@ package io.javaoperatorsdk.operator.sample; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Objects; @@ -8,76 +9,62 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.fabric8.kubernetes.api.model.ConfigMap; -import io.fabric8.kubernetes.api.model.ConfigMapBuilder; -import io.fabric8.kubernetes.api.model.ConfigMapVolumeSourceBuilder; -import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; -import io.fabric8.kubernetes.api.model.Service; +import io.fabric8.kubernetes.api.model.*; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.networking.v1.Ingress; -import io.fabric8.kubernetes.client.KubernetesClient; -import io.fabric8.kubernetes.client.dsl.Replaceable; import io.javaoperatorsdk.operator.ReconcilerUtils; -import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.*; import io.javaoperatorsdk.operator.api.reconciler.Context; -import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; -import io.javaoperatorsdk.operator.api.reconciler.ErrorStatusHandler; -import io.javaoperatorsdk.operator.api.reconciler.ErrorStatusUpdateControl; -import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; -import io.javaoperatorsdk.operator.api.reconciler.EventSourceInitializer; -import io.javaoperatorsdk.operator.api.reconciler.Reconciler; -import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.javaoperatorsdk.operator.processing.event.rate.RateLimited; import io.javaoperatorsdk.operator.processing.event.source.EventSource; import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; import io.javaoperatorsdk.operator.sample.customresource.WebPage; -import static io.javaoperatorsdk.operator.sample.Utils.configMapName; -import static io.javaoperatorsdk.operator.sample.Utils.createStatus; -import static io.javaoperatorsdk.operator.sample.Utils.deploymentName; -import static io.javaoperatorsdk.operator.sample.Utils.handleError; -import static io.javaoperatorsdk.operator.sample.Utils.isValidHtml; -import static io.javaoperatorsdk.operator.sample.Utils.makeDesiredIngress; -import static io.javaoperatorsdk.operator.sample.Utils.serviceName; -import static io.javaoperatorsdk.operator.sample.Utils.setInvalidHtmlErrorMessage; -import static io.javaoperatorsdk.operator.sample.Utils.simulateErrorIfRequested; +import static io.javaoperatorsdk.operator.sample.Utils.*; import static io.javaoperatorsdk.operator.sample.WebPageManagedDependentsReconciler.SELECTOR; /** Shows how to implement reconciler using the low level api directly. */ @RateLimited(maxReconciliations = 2, within = 3) @ControllerConfiguration public class WebPageReconciler - implements Reconciler, ErrorStatusHandler, EventSourceInitializer { + implements Reconciler { public static final String INDEX_HTML = "index.html"; private static final Logger log = LoggerFactory.getLogger(WebPageReconciler.class); - private final KubernetesClient kubernetesClient; + public WebPageReconciler() { - public WebPageReconciler(KubernetesClient kubernetesClient) { - this.kubernetesClient = kubernetesClient; } @Override - public Map prepareEventSources(EventSourceContext context) { + public List> prepareEventSources(EventSourceContext context) { var configMapEventSource = - new InformerEventSource<>(InformerConfiguration.from(ConfigMap.class, context) - .withLabelSelector(SELECTOR) - .build(), context); + new InformerEventSource<>( + InformerEventSourceConfiguration.from(ConfigMap.class, WebPage.class) + .withInformerConfiguration(c -> c.withLabelSelector(SELECTOR)) + .build(), + context); var deploymentEventSource = - new InformerEventSource<>(InformerConfiguration.from(Deployment.class, context) - .withLabelSelector(SELECTOR) - .build(), context); + new InformerEventSource<>( + InformerEventSourceConfiguration.from(Deployment.class, WebPage.class) + .withInformerConfiguration(c -> c.withLabelSelector(SELECTOR)) + .build(), + context); var serviceEventSource = - new InformerEventSource<>(InformerConfiguration.from(Service.class, context) - .withLabelSelector(SELECTOR) - .build(), context); + new InformerEventSource<>( + InformerEventSourceConfiguration.from(Service.class, WebPage.class) + .withInformerConfiguration(c -> c.withLabelSelector(SELECTOR)) + .build(), + context); var ingressEventSource = - new InformerEventSource<>(InformerConfiguration.from(Ingress.class, context) - .withLabelSelector(SELECTOR) - .build(), context); - return EventSourceInitializer.nameEventSources(configMapEventSource, deploymentEventSource, + new InformerEventSource<>( + InformerEventSourceConfiguration.from(Ingress.class, WebPage.class) + .withInformerConfiguration(c -> c.withLabelSelector(SELECTOR)) + .build(), + context); + return List.of(configMapEventSource, deploymentEventSource, serviceEventSource, ingressEventSource); } @@ -107,8 +94,8 @@ public UpdateControl reconcile(WebPage webPage, Context contex "Creating or updating ConfigMap {} in {}", desiredHtmlConfigMap.getMetadata().getName(), ns); - kubernetesClient.configMaps().inNamespace(ns).resource(desiredHtmlConfigMap) - .createOr(Replaceable::update); + context.getClient().configMaps().inNamespace(ns).resource(desiredHtmlConfigMap) + .serverSideApply(); } var existingDeployment = context.getSecondaryResource(Deployment.class).orElse(null); @@ -117,8 +104,8 @@ public UpdateControl reconcile(WebPage webPage, Context contex "Creating or updating Deployment {} in {}", desiredDeployment.getMetadata().getName(), ns); - kubernetesClient.apps().deployments().inNamespace(ns).resource(desiredDeployment) - .createOr(Replaceable::update); + context.getClient().apps().deployments().inNamespace(ns).resource(desiredDeployment) + .serverSideApply(); } var existingService = context.getSecondaryResource(Service.class).orElse(null); @@ -127,19 +114,19 @@ public UpdateControl reconcile(WebPage webPage, Context contex "Creating or updating Deployment {} in {}", desiredDeployment.getMetadata().getName(), ns); - kubernetesClient.services().inNamespace(ns).resource(desiredService) - .createOr(Replaceable::update); + context.getClient().services().inNamespace(ns).resource(desiredService) + .serverSideApply(); } var existingIngress = context.getSecondaryResource(Ingress.class); if (Boolean.TRUE.equals(webPage.getSpec().getExposed())) { var desiredIngress = makeDesiredIngress(webPage); if (existingIngress.isEmpty() || !match(desiredIngress, existingIngress.get())) { - kubernetesClient.resource(desiredIngress).inNamespace(ns).createOr(Replaceable::update); + context.getClient().resource(desiredIngress).inNamespace(ns).serverSideApply(); } } else existingIngress.ifPresent( - ingress -> kubernetesClient.resource(ingress).delete()); + ingress -> context.getClient().resource(ingress).delete()); // not that this is not necessary, eventually mounted config map would be updated, just this way // is much faster; what is handy for demo purposes. @@ -148,10 +135,11 @@ public UpdateControl reconcile(WebPage webPage, Context contex previousConfigMap.getData().get(INDEX_HTML), desiredHtmlConfigMap.getData().get(INDEX_HTML))) { log.info("Restarting pods because HTML has changed in {}", ns); - kubernetesClient.pods().inNamespace(ns).withLabel("app", deploymentName(webPage)).delete(); + context.getClient().pods().inNamespace(ns).withLabel("app", deploymentName(webPage)).delete(); } - webPage.setStatus(createStatus(desiredHtmlConfigMap.getMetadata().getName())); - return UpdateControl.patchStatus(webPage); + + return UpdateControl.patchStatus( + createWebPageForStatusUpdate(webPage, desiredHtmlConfigMap.getMetadata().getName())); } private boolean match(Ingress desiredIngress, Ingress existingIngress) { diff --git a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageStandaloneDependentsReconciler.java b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageStandaloneDependentsReconciler.java index 1799d72cea..d2475b983f 100644 --- a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageStandaloneDependentsReconciler.java +++ b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/WebPageStandaloneDependentsReconciler.java @@ -1,55 +1,72 @@ package io.javaoperatorsdk.operator.sample; import java.util.Arrays; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.util.List; import io.fabric8.kubernetes.api.model.ConfigMap; -import io.javaoperatorsdk.operator.api.reconciler.*; +import io.javaoperatorsdk.operator.api.config.informer.InformerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.Context; +import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; +import io.javaoperatorsdk.operator.api.reconciler.ErrorStatusUpdateControl; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; +import io.javaoperatorsdk.operator.api.reconciler.EventSourceUtils; +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; +import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResourceConfigBuilder; import io.javaoperatorsdk.operator.processing.dependent.workflow.Workflow; import io.javaoperatorsdk.operator.processing.dependent.workflow.WorkflowBuilder; import io.javaoperatorsdk.operator.processing.event.source.EventSource; import io.javaoperatorsdk.operator.sample.customresource.WebPage; -import io.javaoperatorsdk.operator.sample.dependentresource.*; +import io.javaoperatorsdk.operator.sample.dependentresource.ConfigMapDependentResource; +import io.javaoperatorsdk.operator.sample.dependentresource.DeploymentDependentResource; +import io.javaoperatorsdk.operator.sample.dependentresource.ExposedIngressCondition; +import io.javaoperatorsdk.operator.sample.dependentresource.IngressDependentResource; +import io.javaoperatorsdk.operator.sample.dependentresource.ServiceDependentResource; import static io.javaoperatorsdk.operator.sample.Utils.*; import static io.javaoperatorsdk.operator.sample.WebPageManagedDependentsReconciler.SELECTOR; /** - * Shows how to implement reconciler using standalone dependent resources. + * Shows how to implement reconciler using standalone dependent resources and workflows. */ @ControllerConfiguration public class WebPageStandaloneDependentsReconciler - implements Reconciler, ErrorStatusHandler, EventSourceInitializer { - - private static final Logger log = - LoggerFactory.getLogger(WebPageStandaloneDependentsReconciler.class); + implements Reconciler { - private Workflow workflow; + private final Workflow workflow; public WebPageStandaloneDependentsReconciler() { + // initialize the workflow workflow = createDependentResourcesAndWorkflow(); } @Override - public Map prepareEventSources(EventSourceContext context) { - return EventSourceInitializer.eventSourcesFromWorkflow(context, workflow); + public List> prepareEventSources(EventSourceContext context) { + // initializes the dependents' event sources from the given context + return EventSourceUtils.eventSourcesFromWorkflow(context, workflow); } @Override public UpdateControl reconcile(WebPage webPage, Context context) throws Exception { + // for testing purposes simulateErrorIfRequested(webPage); + // validate the html page and update the status with an error message if it isn't valid if (!isValidHtml(webPage)) { return UpdateControl.patchStatus(setInvalidHtmlErrorMessage(webPage)); } + // Explicitly reconcile the dependent resources. + // Calling the workflow reconciliation explicitly allows control over the workflow customization + // but also *when* dependents are reconciled (as opposed to before the main reconciler's + // reconcile method in the managed case). + // With the default configuration, this will throw an exception if one of the dependents + // couldn't be properly reconciled workflow.reconcile(webPage, context); + // retrieve the name of the ConfigMap secondary resource to update the status if everything went + // well webPage.setStatus( createStatus( context.getSecondaryResource(ConfigMap.class).orElseThrow().getMetadata().getName())); @@ -62,25 +79,41 @@ public ErrorStatusUpdateControl updateErrorStatus( return handleError(resource, e); } + /** + * Initializes the dependent resources and connect them in the context of a {@link Workflow} + * + * @return the {@link Workflow} that will reconcile automatically secondary resources + */ @SuppressWarnings({"unchecked", "rawtypes"}) private Workflow createDependentResourcesAndWorkflow() { + // create the dependent resources var configMapDR = new ConfigMapDependentResource(); var deploymentDR = new DeploymentDependentResource(); var serviceDR = new ServiceDependentResource(); var ingressDR = new IngressDependentResource(); + + // configure them with our label selector Arrays.asList(configMapDR, deploymentDR, serviceDR, ingressDR) .forEach(dr -> dr.configureWith(new KubernetesDependentResourceConfigBuilder() - .withLabelSelector(SELECTOR + "=true").build())); - + .withKubernetesDependentInformerConfig(InformerConfiguration.builder(dr.resourceType()) + .withLabelSelector(SELECTOR + "=true") + .buildForInformerEventSource()) + .build())); + + // connect the dependent resources into a workflow, configuring them as we go + // Note the method call order is significant and configuration applies to the dependent being + // configured as defined by the method call order (in this example, the reconcile pre-condition + // that is added applies to the Ingress dependent) return new WorkflowBuilder() .addDependentResource(configMapDR) .addDependentResource(deploymentDR) .addDependentResource(serviceDR) - .addDependentResource(ingressDR) + .addDependentResourceAndConfigure(ingressDR) + // prevent the Ingress from being created based on the linked condition (here: only if the + // `exposed` flag is set in the primary resource), delete the Ingress if it already exists + // and the condition becomes false .withReconcilePrecondition(new ExposedIngressCondition()) .build(); } - - } diff --git a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/customresource/WebPageStatus.java b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/customresource/WebPageStatus.java index 7ab20c76be..36409ac7f9 100644 --- a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/customresource/WebPageStatus.java +++ b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/customresource/WebPageStatus.java @@ -1,8 +1,6 @@ package io.javaoperatorsdk.operator.sample.customresource; -import io.javaoperatorsdk.operator.api.ObservedGenerationAwareStatus; - -public class WebPageStatus extends ObservedGenerationAwareStatus { +public class WebPageStatus { private String htmlConfigMap; diff --git a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/dependentresource/ConfigMapDependentResource.java b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/dependentresource/ConfigMapDependentResource.java index 8641aa343b..816db3688e 100644 --- a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/dependentresource/ConfigMapDependentResource.java +++ b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/dependentresource/ConfigMapDependentResource.java @@ -6,6 +6,7 @@ import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.api.model.ConfigMapBuilder; import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.javaoperatorsdk.operator.api.config.informer.Informer; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; @@ -15,7 +16,7 @@ import static io.javaoperatorsdk.operator.sample.WebPageManagedDependentsReconciler.SELECTOR; // this annotation only activates when using managed dependents and is not otherwise needed -@KubernetesDependent(labelSelector = SELECTOR) +@KubernetesDependent(informer = @Informer(labelSelector = SELECTOR)) public class ConfigMapDependentResource extends CRUDKubernetesDependentResource { diff --git a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/dependentresource/DeploymentDependentResource.java b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/dependentresource/DeploymentDependentResource.java index 4b2e373260..b427e42d33 100644 --- a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/dependentresource/DeploymentDependentResource.java +++ b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/dependentresource/DeploymentDependentResource.java @@ -5,6 +5,7 @@ import io.fabric8.kubernetes.api.model.ConfigMapVolumeSourceBuilder; import io.fabric8.kubernetes.api.model.apps.Deployment; +import io.javaoperatorsdk.operator.api.config.informer.Informer; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; @@ -17,7 +18,7 @@ import static io.javaoperatorsdk.operator.sample.WebPageManagedDependentsReconciler.SELECTOR; // this annotation only activates when using managed dependents and is not otherwise needed -@KubernetesDependent(labelSelector = SELECTOR) +@KubernetesDependent(informer = @Informer(labelSelector = SELECTOR)) public class DeploymentDependentResource extends CRUDKubernetesDependentResource { diff --git a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/dependentresource/IngressDependentResource.java b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/dependentresource/IngressDependentResource.java index f3a3aa65ba..e680d10fcf 100644 --- a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/dependentresource/IngressDependentResource.java +++ b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/dependentresource/IngressDependentResource.java @@ -1,6 +1,7 @@ package io.javaoperatorsdk.operator.sample.dependentresource; import io.fabric8.kubernetes.api.model.networking.v1.Ingress; +import io.javaoperatorsdk.operator.api.config.informer.Informer; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; @@ -10,7 +11,8 @@ import static io.javaoperatorsdk.operator.sample.Utils.makeDesiredIngress; // this annotation only activates when using managed dependents and is not otherwise needed -@KubernetesDependent(labelSelector = WebPageManagedDependentsReconciler.SELECTOR) +@KubernetesDependent( + informer = @Informer(labelSelector = WebPageManagedDependentsReconciler.SELECTOR)) public class IngressDependentResource extends CRUDKubernetesDependentResource { public IngressDependentResource() { diff --git a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/dependentresource/ServiceDependentResource.java b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/dependentresource/ServiceDependentResource.java index 80d5073a6e..ff9e7a1a52 100644 --- a/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/dependentresource/ServiceDependentResource.java +++ b/sample-operators/webpage/src/main/java/io/javaoperatorsdk/operator/sample/dependentresource/ServiceDependentResource.java @@ -4,6 +4,7 @@ import java.util.Map; import io.fabric8.kubernetes.api.model.Service; +import io.javaoperatorsdk.operator.api.config.informer.Informer; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependent; import io.javaoperatorsdk.operator.sample.Utils; @@ -15,7 +16,7 @@ import static io.javaoperatorsdk.operator.sample.WebPageManagedDependentsReconciler.SELECTOR; // this annotation only activates when using managed dependents and is not otherwise needed -@KubernetesDependent(labelSelector = SELECTOR) +@KubernetesDependent(informer = @Informer(labelSelector = SELECTOR)) public class ServiceDependentResource extends io.javaoperatorsdk.operator.processing.dependent.kubernetes.CRUDKubernetesDependentResource { diff --git a/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorAbstractTest.java b/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorAbstractTest.java index 040b3b2f8f..6c9a5512bb 100644 --- a/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorAbstractTest.java +++ b/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorAbstractTest.java @@ -37,7 +37,7 @@ public abstract class WebPageOperatorAbstractTest { public static final String TEST_PAGE = "test-page"; public static final String TITLE1 = "Hello Operator World"; public static final String TITLE2 = "Hello Operator World Title 2"; - public static final int WAIT_SECONDS = 20; + public static final int WAIT_SECONDS = 360; public static final int LONG_WAIT_SECONDS = 120; public static final Duration POLL_INTERVAL = Duration.ofSeconds(1); diff --git a/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorE2E.java b/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorE2E.java index 03c3d2c2e0..45fc4cd5ba 100644 --- a/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorE2E.java +++ b/sample-operators/webpage/src/test/java/io/javaoperatorsdk/operator/sample/WebPageOperatorE2E.java @@ -27,7 +27,7 @@ public WebPageOperatorE2E() throws FileNotFoundException {} isLocal() ? LocallyRunOperatorExtension.builder() .waitForNamespaceDeletion(false) - .withReconciler(new WebPageReconciler(client)) + .withReconciler(new WebPageReconciler()) .build() : ClusterDeployedOperatorExtension.builder() .waitForNamespaceDeletion(false)