From d6a6d1c101bec20f88cd4d2719e5d1b91a3a0a53 Mon Sep 17 00:00:00 2001 From: Chris Laprun Date: Wed, 27 Oct 2021 20:19:41 +0200 Subject: [PATCH 1/8] refactor!: replace Closeable by explicit Stoppable interface This ensures that stoppable classes can also be started if needed. Fixes #629 --- .../java/io/javaoperatorsdk/operator/api/Stoppable.java | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/Stoppable.java diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/Stoppable.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/Stoppable.java new file mode 100644 index 0000000000..b6fc43a78d --- /dev/null +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/Stoppable.java @@ -0,0 +1,9 @@ +package io.javaoperatorsdk.operator.api; + +import io.javaoperatorsdk.operator.OperatorException; + +public interface Stoppable { + void start() throws OperatorException; + + void stop() throws OperatorException; +} From 6efa2cd6507968088ae2a937722c85a14bcf7553 Mon Sep 17 00:00:00 2001 From: Chris Laprun Date: Thu, 28 Oct 2021 10:21:41 +0200 Subject: [PATCH 2/8] refactor: rename Stoppable to LifecycleAware --- .../io/javaoperatorsdk/operator/Operator.java | 17 ++++++------- .../operator/api/Stoppable.java | 9 ------- .../processing/ConfiguredController.java | 10 ++++---- .../processing/DefaultEventHandler.java | 25 +++++++++---------- .../event/DefaultEventSourceManager.java | 2 +- .../processing/event/EventSource.java | 3 ++- 6 files changed, 28 insertions(+), 38 deletions(-) delete mode 100644 operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/Stoppable.java 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 c63dd6c972..08854168c7 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 @@ -1,14 +1,5 @@ package io.javaoperatorsdk.operator; -import java.net.ConnectException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; @@ -19,6 +10,14 @@ import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.config.ExecutorServiceManager; import io.javaoperatorsdk.operator.processing.ConfiguredController; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.net.ConnectException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @SuppressWarnings("rawtypes") public class Operator implements AutoCloseable, LifecycleAware { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/Stoppable.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/Stoppable.java deleted file mode 100644 index b6fc43a78d..0000000000 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/Stoppable.java +++ /dev/null @@ -1,9 +0,0 @@ -package io.javaoperatorsdk.operator.api; - -import io.javaoperatorsdk.operator.OperatorException; - -public interface Stoppable { - void start() throws OperatorException; - - void stop() throws OperatorException; -} diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/ConfiguredController.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/ConfiguredController.java index 7249dfe4aa..89c4b576a2 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/ConfiguredController.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/ConfiguredController.java @@ -1,7 +1,5 @@ package io.javaoperatorsdk.operator.processing; -import java.util.Objects; - import io.fabric8.kubernetes.api.model.KubernetesResourceList; import io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinition; import io.fabric8.kubernetes.client.CustomResource; @@ -22,16 +20,18 @@ import io.javaoperatorsdk.operator.processing.event.DefaultEventSourceManager; import io.javaoperatorsdk.operator.processing.event.EventSourceManager; +import java.util.Objects; + public class ConfiguredController> implements ResourceController, - LifecycleAware, EventSourceInitializer { + LifecycleAware, EventSourceInitializer { private final ResourceController controller; private final ControllerConfiguration configuration; private final KubernetesClient kubernetesClient; private DefaultEventSourceManager eventSourceManager; public ConfiguredController(ResourceController controller, - ControllerConfiguration configuration, - KubernetesClient kubernetesClient) { + ControllerConfiguration configuration, + KubernetesClient kubernetesClient) { this.controller = controller; this.configuration = configuration; this.kubernetesClient = kubernetesClient; diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/DefaultEventHandler.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/DefaultEventHandler.java index 212cd378d7..6a9fec7b71 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/DefaultEventHandler.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/DefaultEventHandler.java @@ -1,17 +1,5 @@ package io.javaoperatorsdk.operator.processing; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.locks.ReentrantLock; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.OperatorException; import io.javaoperatorsdk.operator.api.LifecycleAware; @@ -28,6 +16,17 @@ import io.javaoperatorsdk.operator.processing.retry.GenericRetry; import io.javaoperatorsdk.operator.processing.retry.Retry; import io.javaoperatorsdk.operator.processing.retry.RetryExecution; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.locks.ReentrantLock; import static io.javaoperatorsdk.operator.processing.KubernetesResourceUtils.getName; import static io.javaoperatorsdk.operator.processing.KubernetesResourceUtils.getVersion; @@ -37,7 +36,7 @@ * UID, while buffering events which are received during an execution. */ public class DefaultEventHandler> - implements EventHandler, LifecycleAware { + implements EventHandler, LifecycleAware { private static final Logger log = LoggerFactory.getLogger(DefaultEventHandler.class); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/DefaultEventSourceManager.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/DefaultEventSourceManager.java index dd8e7f19ce..bedda50df3 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/DefaultEventSourceManager.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/DefaultEventSourceManager.java @@ -19,7 +19,7 @@ import io.javaoperatorsdk.operator.processing.event.internal.TimerEventSource; public class DefaultEventSourceManager> - implements EventSourceManager, LifecycleAware { + implements EventSourceManager, LifecycleAware { private static final Logger log = LoggerFactory.getLogger(DefaultEventSourceManager.class); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSource.java index 7646dcc353..58bf357f49 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSource.java @@ -11,5 +11,6 @@ public interface EventSource extends LifecycleAware { * * @param customResourceUid - id of custom resource */ - default void cleanupForCustomResource(CustomResourceID customResourceUid) {} + default void cleanupForCustomResource(CustomResourceID customResourceUid) { + } } From 38d0a5f204081101a670fe1ede57d95871da18cb Mon Sep 17 00:00:00 2001 From: Chris Laprun Date: Wed, 27 Oct 2021 20:33:55 +0200 Subject: [PATCH 3/8] refactor: fix generics --- .../operator/ControllerUtils.java | 5 +- .../io/javaoperatorsdk/operator/Operator.java | 34 +++++----- .../operator/api/BaseControl.java | 16 ++--- .../javaoperatorsdk/operator/api/Context.java | 6 +- .../operator/api/DefaultContext.java | 18 +++-- .../operator/api/DeleteControl.java | 4 +- .../operator/api/ResourceController.java | 48 ++++++------- .../operator/api/UpdateControl.java | 13 ++-- .../config/AbstractConfigurationService.java | 39 +++++------ .../api/config/ConfigurationService.java | 19 +++--- .../config/ConfigurationServiceOverrider.java | 8 +-- .../api/config/ControllerConfiguration.java | 10 +-- .../processing/ConfiguredController.java | 50 +++++++------- .../operator/processing/EventDispatcher.java | 32 +++++---- .../internal/CustomResourceEventFilter.java | 20 +++--- .../internal/CustomResourceEventFilters.java | 68 +++++++++---------- .../processing/EventDispatcherTest.java | 44 ++++++------ .../internal/CustomResourceSelectorTest.java | 33 +++++---- .../simple/TestCustomResourceController.java | 39 ++++++----- .../runtime/AnnotationConfiguration.java | 10 +-- .../config/runtime/ClassMappingProvider.java | 43 ++++++------ .../runtime/DefaultConfigurationService.java | 28 ++++---- .../runtime/RuntimeControllerMetadata.java | 22 +++--- .../DefaultConfigurationServiceTest.java | 23 +++---- .../config/runtime/TestCustomResource.java | 2 +- ...bleUpdateTestCustomResourceController.java | 13 ++-- ...entSourceTestCustomResourceController.java | 16 +++-- ...entSourceTestCustomResourceController.java | 14 ++-- .../RetryTestCustomResourceController.java | 11 ++- .../simple/TestCustomResourceController.java | 39 ++++++----- ...bResourceTestCustomResourceController.java | 11 ++- .../ControllerImplemented2Interfaces.java | 4 +- ...rImplementedIntermediateAbstractClass.java | 4 +- .../MultilevelController.java | 4 +- .../sample/CustomServiceController.java | 41 ++++++----- 35 files changed, 395 insertions(+), 396 deletions(-) diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ControllerUtils.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ControllerUtils.java index 023b333758..d963b61e2a 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ControllerUtils.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ControllerUtils.java @@ -1,10 +1,11 @@ package io.javaoperatorsdk.operator; -import java.util.Locale; - import io.javaoperatorsdk.operator.api.Controller; import io.javaoperatorsdk.operator.api.ResourceController; +import java.util.Locale; + +@SuppressWarnings("rawtypes") public class ControllerUtils { private static final String FINALIZER_NAME_SUFFIX = "/finalizer"; 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 08854168c7..9198a30070 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 @@ -110,12 +110,12 @@ public void close() { * registration of the controller is delayed till the operator is started. * * @param controller the controller to register - * @param the {@code CustomResource} type associated with the controller + * @param the {@code CustomResource} type associated with the controller * @throws OperatorException if a problem occurred during the registration process */ - public void register(ResourceController controller) - throws OperatorException { - register(controller, null); + public > void register(ResourceController controller) + throws OperatorException { + register(controller, null); } /** @@ -131,23 +131,23 @@ public void register(ResourceController controller * @param the {@code CustomResource} type associated with the controller * @throws OperatorException if a problem occurred during the registration process */ - public void register( - ResourceController controller, ControllerConfiguration configuration) - throws OperatorException { - final var existing = configurationService.getConfigurationFor(controller); - if (existing == null) { - log.warn( - "Skipping registration of {} controller named {} because its configuration cannot be found.\n" - + "Known controllers are: {}", - controller.getClass().getCanonicalName(), - ControllerUtils.getNameFor(controller), - configurationService.getKnownControllerNames()); + public > void register( + ResourceController controller, ControllerConfiguration configuration) + throws OperatorException { + final var existing = configurationService.getConfigurationFor(controller); + if (existing == null) { + log.warn( + "Skipping registration of {} controller named {} because its configuration cannot be found.\n" + + "Known controllers are: {}", + controller.getClass().getCanonicalName(), + ControllerUtils.getNameFor(controller), + configurationService.getKnownControllerNames()); } else { if (configuration == null) { configuration = existing; } - final var configuredController = - new ConfiguredController(controller, configuration, kubernetesClient); + final var configuredController = + new ConfiguredController<>(controller, configuration, kubernetesClient); controllers.add(configuredController); final var watchedNS = diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/BaseControl.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/BaseControl.java index 327bc34791..72b16cda1c 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/BaseControl.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/BaseControl.java @@ -3,17 +3,17 @@ import java.util.Optional; import java.util.concurrent.TimeUnit; -public abstract class BaseControl { +public abstract class BaseControl> { - private Long scheduleDelay = null; + private Long scheduleDelay = null; - public T rescheduleAfter(long delay) { - this.scheduleDelay = delay; - return (T) this; - } + public T rescheduleAfter(long delay) { + this.scheduleDelay = delay; + return (T) this; + } - public T rescheduleAfter(long delay, TimeUnit timeUnit) { - return rescheduleAfter(timeUnit.toMillis(delay)); + public T rescheduleAfter(long delay, TimeUnit timeUnit) { + return rescheduleAfter(timeUnit.toMillis(delay)); } public Optional getScheduleDelay() { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/Context.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/Context.java index cc832a2e21..3883f496fa 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/Context.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/Context.java @@ -2,10 +2,8 @@ import java.util.Optional; -import io.fabric8.kubernetes.client.CustomResource; +public interface Context { -public interface Context { - - Optional getRetryInfo(); + Optional getRetryInfo(); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/DefaultContext.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/DefaultContext.java index f32a784e11..5a8b4fcbd4 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/DefaultContext.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/DefaultContext.java @@ -2,18 +2,16 @@ import java.util.Optional; -import io.fabric8.kubernetes.client.CustomResource; +public class DefaultContext implements Context { -public class DefaultContext implements Context { + private final RetryInfo retryInfo; - private final RetryInfo retryInfo; + public DefaultContext(RetryInfo retryInfo) { + this.retryInfo = retryInfo; + } - public DefaultContext(RetryInfo retryInfo) { - this.retryInfo = retryInfo; - } - - @Override - public Optional getRetryInfo() { - return Optional.ofNullable(retryInfo); + @Override + public Optional getRetryInfo() { + return Optional.ofNullable(retryInfo); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/DeleteControl.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/DeleteControl.java index b1ddac3df3..55631d5392 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/DeleteControl.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/DeleteControl.java @@ -22,8 +22,8 @@ public boolean isRemoveFinalizer() { @Override public DeleteControl rescheduleAfter(long delay) { - if (removeFinalizer == true) { - throw new IllegalStateException("Cannot reschedule deleteResource if removing finalizer"); + if (removeFinalizer) { + throw new IllegalStateException("Cannot reschedule deleteResource if removing finalizer"); } return super.rescheduleAfter(delay); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/ResourceController.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/ResourceController.java index 817cb554fc..b69149b1da 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/ResourceController.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/ResourceController.java @@ -2,35 +2,35 @@ import io.fabric8.kubernetes.client.CustomResource; -public interface ResourceController { +public interface ResourceController> { - /** - * Note that this method is used in combination of finalizers. If automatic finalizer handling is - * turned off for the controller, this method is not called. - * - * The implementation should delete the associated component(s). Note that this is method is - * called when an object is marked for deletion. After it's executed the custom resource finalizer - * is automatically removed by the framework; unless the return value is - * {@link DeleteControl#noFinalizerRemoval()}, which indicates that the controller has determined - * that the resource should not be deleted yet. This is usually a corner case, when a cleanup is + /** + * Note that this method is used in combination of finalizers. If automatic finalizer handling is + * turned off for the controller, this method is not called. + * + * The implementation should delete the associated component(s). Note that this is method is + * called when an object is marked for deletion. After it's executed the custom resource finalizer + * is automatically removed by the framework; unless the return value is + * {@link DeleteControl#noFinalizerRemoval()}, which indicates that the controller has determined + * that the resource should not be deleted yet. This is usually a corner case, when a cleanup is * tried again eventually. * *

* It's important that this method be idempotent, as it could be called several times, depending * on the conditions and the controller's configuration (for example, if the controller is - * configured to not use a finalizer but the resource does have finalizers, it might be be - * "offered" again for deletion several times until the finalizers are all removed. - * - * @param resource the resource that is marked for deletion - * @param context the context with which the operation is executed - * @return {@link DeleteControl#defaultDelete()} - so the finalizer is automatically removed after - * the call. {@link DeleteControl#noFinalizerRemoval()} if you don't want to remove the - * finalizer to indicate that the resource should not be deleted after all, in which case - * the controller should restore the resource's state appropriately. - */ - default DeleteControl deleteResource(R resource, Context context) { - return DeleteControl.defaultDelete(); - } + * configured to not use a finalizer but the resource does have finalizers, it might be be + * "offered" again for deletion several times until the finalizers are all removed. + * + * @param resource the resource that is marked for deletion + * @param context the context with which the operation is executed + * @return {@link DeleteControl#defaultDelete()} - so the finalizer is automatically removed after + * the call. {@link DeleteControl#noFinalizerRemoval()} if you don't want to remove the + * finalizer to indicate that the resource should not be deleted after all, in which case + * the controller should restore the resource's state appropriately. + */ + default DeleteControl deleteResource(R resource, Context context) { + return DeleteControl.defaultDelete(); + } /** * The implementation of this operation is required to be idempotent. Always use the UpdateControl @@ -46,6 +46,6 @@ default DeleteControl deleteResource(R resource, Context context) { * be skipped. However we will always call an update if there is no finalizer on object * and it's not marked for deletion. */ - UpdateControl createOrUpdateResource(R resource, Context context); + UpdateControl createOrUpdateResource(R resource, Context context); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/UpdateControl.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/UpdateControl.java index 18cc2ca4ee..0d374e1b9a 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/UpdateControl.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/UpdateControl.java @@ -2,6 +2,7 @@ import io.fabric8.kubernetes.client.CustomResource; +@SuppressWarnings("rawtypes") public class UpdateControl extends BaseControl> { private final T customResource; @@ -9,7 +10,7 @@ public class UpdateControl extends BaseControl UpdateControl updateCustomResource(T } public static UpdateControl updateStatusSubResource( - T customResource) { + T customResource) { return new UpdateControl<>(customResource, true, 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. - * + * * @param customResource - custom resource to use in both API calls * @return UpdateControl instance */ - public static UpdateControl updateCustomResourceAndStatus( - T customResource) { + public static > UpdateControl updateCustomResourceAndStatus( + T customResource) { return new UpdateControl<>(customResource, true, true); } - public static UpdateControl noUpdate() { + public static > UpdateControl noUpdate() { return new UpdateControl<>(null, false, false); } 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 1a37986d52..c68c68c4cc 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 @@ -1,14 +1,15 @@ package io.javaoperatorsdk.operator.api.config; +import io.fabric8.kubernetes.client.CustomResource; +import io.javaoperatorsdk.operator.ControllerUtils; +import io.javaoperatorsdk.operator.api.ResourceController; + import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Stream; -import io.fabric8.kubernetes.client.CustomResource; -import io.javaoperatorsdk.operator.ControllerUtils; -import io.javaoperatorsdk.operator.api.ResourceController; - +@SuppressWarnings("rawtypes") public class AbstractConfigurationService implements ConfigurationService { private final Map configurations = new ConcurrentHashMap<>(); private final Version version; @@ -17,16 +18,16 @@ public AbstractConfigurationService(Version version) { this.version = version; } - protected void register(ControllerConfiguration config) { + protected > void register(ControllerConfiguration config) { put(config, true); } - protected void replace(ControllerConfiguration config) { + protected > void replace(ControllerConfiguration config) { put(config, false); } - private void put( - ControllerConfiguration config, boolean failIfExisting) { + private > void put( + ControllerConfiguration config, boolean failIfExisting) { final var name = config.getName(); if (failIfExisting) { final var existing = configurations.get(name); @@ -38,20 +39,20 @@ private void put( config.setConfigurationService(this); } - protected void throwExceptionOnNameCollision( - String newControllerClassName, ControllerConfiguration existing) { + protected > void throwExceptionOnNameCollision( + String newControllerClassName, ControllerConfiguration existing) { throw new IllegalArgumentException( - "Controller name '" - + existing.getName() - + "' is used by both " - + existing.getAssociatedControllerClassName() - + " and " - + newControllerClassName); + "Controller name '" + + existing.getName() + + "' is used by both " + + existing.getAssociatedControllerClassName() + + " and " + + newControllerClassName); } @Override - public ControllerConfiguration getConfigurationFor( - ResourceController controller) { + public > ControllerConfiguration getConfigurationFor( + ResourceController controller) { final var key = keyFor(controller); final var configuration = configurations.get(key); if (configuration == null) { @@ -72,7 +73,7 @@ private String getControllersNameMessage() { + "."; } - protected String keyFor(ResourceController controller) { + protected > String keyFor(ResourceController controller) { return ControllerUtils.getNameFor(controller); } 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 fb53f7eaae..78e0952fee 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 @@ -1,16 +1,15 @@ package io.javaoperatorsdk.operator.api.config; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.api.ResourceController; import io.javaoperatorsdk.operator.api.monitoring.Metrics; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; /** An interface from which to retrieve configuration information. */ public interface ConfigurationService { @@ -32,12 +31,12 @@ public interface ConfigurationService { * Retrieves the configuration associated with the specified controller * * @param controller the controller we want the configuration of - * @param the {@code CustomResource} type associated with the specified controller + * @param the {@code CustomResource} type associated with the specified controller * @return the {@link ControllerConfiguration} associated with the specified controller or {@code - * null} if no configuration exists for the controller + * null} if no configuration exists for the controller */ - ControllerConfiguration getConfigurationFor( - ResourceController controller); + > ControllerConfiguration getConfigurationFor( + ResourceController controller); /** * Retrieves the Kubernetes client configuration 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 2cecfb552d..48d4f5b254 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 @@ -1,12 +1,12 @@ package io.javaoperatorsdk.operator.api.config; -import java.util.Set; - import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.api.ResourceController; import io.javaoperatorsdk.operator.api.monitoring.Metrics; +import java.util.Set; + public class ConfigurationServiceOverrider { private final ConfigurationService original; private Metrics metrics; @@ -61,8 +61,8 @@ public ConfigurationServiceOverrider withMetrics(Metrics metrics) { public ConfigurationService build() { return new ConfigurationService() { @Override - public ControllerConfiguration getConfigurationFor( - ResourceController controller) { + public > ControllerConfiguration getConfigurationFor( + ResourceController controller) { return original.getConfigurationFor(controller); } 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 a1d097daba..3a64c12ce1 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,16 +1,16 @@ package io.javaoperatorsdk.operator.api.config; -import java.lang.reflect.ParameterizedType; -import java.util.Collections; -import java.util.Set; - import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.ControllerUtils; import io.javaoperatorsdk.operator.api.Controller; import io.javaoperatorsdk.operator.processing.event.internal.CustomResourceEventFilter; import io.javaoperatorsdk.operator.processing.event.internal.CustomResourceEventFilters; -public interface ControllerConfiguration { +import java.lang.reflect.ParameterizedType; +import java.util.Collections; +import java.util.Set; + +public interface ControllerConfiguration> { default String getName() { return ControllerUtils.getDefaultResourceControllerName(getAssociatedControllerClassName()); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/ConfiguredController.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/ConfiguredController.java index 89c4b576a2..f15fa257b1 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/ConfiguredController.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/ConfiguredController.java @@ -23,11 +23,11 @@ import java.util.Objects; public class ConfiguredController> implements ResourceController, - LifecycleAware, EventSourceInitializer { + LifecycleAware, EventSourceInitializer { private final ResourceController controller; private final ControllerConfiguration configuration; private final KubernetesClient kubernetesClient; - private DefaultEventSourceManager eventSourceManager; + private DefaultEventSourceManager eventSourceManager; public ConfiguredController(ResourceController controller, ControllerConfiguration configuration, @@ -38,17 +38,17 @@ public ConfiguredController(ResourceController controller, } @Override - public DeleteControl deleteResource(R resource, Context context) { + public DeleteControl deleteResource(R resource, Context context) { return configuration.getConfigurationService().getMetrics().timeControllerExecution( - new ControllerExecution<>() { - @Override - public String name() { - return "delete"; - } - - @Override - public String controllerName() { - return configuration.getName(); + new ControllerExecution<>() { + @Override + public String name() { + return "delete"; + } + + @Override + public String controllerName() { + return configuration.getName(); } @Override @@ -64,17 +64,17 @@ public DeleteControl execute() { } @Override - public UpdateControl createOrUpdateResource(R resource, Context context) { + public UpdateControl createOrUpdateResource(R resource, Context context) { return configuration.getConfigurationService().getMetrics().timeControllerExecution( - new ControllerExecution<>() { - @Override - public String name() { - return "createOrUpdate"; - } - - @Override - public String controllerName() { - return configuration.getName(); + new ControllerExecution<>() { + @Override + public String name() { + return "createOrUpdate"; + } + + @Override + public String controllerName() { + return configuration.getName(); } @Override @@ -97,7 +97,7 @@ public UpdateControl execute() { } @Override - public void prepareEventSources(EventSourceManager eventSourceManager) { + public void prepareEventSources(EventSourceManager eventSourceManager) { throw new UnsupportedOperationException("This method should never be called directly"); } @@ -170,7 +170,7 @@ public void start() throws OperatorException { try { eventSourceManager = new DefaultEventSourceManager<>(this); if (controller instanceof EventSourceInitializer) { - ((EventSourceInitializer) controller).prepareEventSources(eventSourceManager); + ((EventSourceInitializer) controller).prepareEventSources(eventSourceManager); } } catch (MissingCRDException e) { throwMissingCRDException(crdName, specVersion, controllerName); @@ -213,7 +213,7 @@ private boolean failOnMissingCurrentNS() { return false; } - public EventSourceManager getEventSourceManager() { + public EventSourceManager getEventSourceManager() { return eventSourceManager; } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/EventDispatcher.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/EventDispatcher.java index 3000e463b6..5aeb71fecb 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/EventDispatcher.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/EventDispatcher.java @@ -1,15 +1,19 @@ package io.javaoperatorsdk.operator.processing; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import io.fabric8.kubernetes.api.model.KubernetesResourceList; import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; -import io.javaoperatorsdk.operator.api.*; +import io.javaoperatorsdk.operator.api.BaseControl; +import io.javaoperatorsdk.operator.api.DefaultContext; +import io.javaoperatorsdk.operator.api.DeleteControl; +import io.javaoperatorsdk.operator.api.ObservedGenerationAware; +import io.javaoperatorsdk.operator.api.ResourceController; +import io.javaoperatorsdk.operator.api.UpdateControl; import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import static io.javaoperatorsdk.operator.processing.KubernetesResourceUtils.getName; import static io.javaoperatorsdk.operator.processing.KubernetesResourceUtils.getUID; @@ -58,14 +62,14 @@ private PostExecutionControl handleDispatch(ExecutionScope executionScope) final var markedForDeletion = resource.isMarkedForDeletion(); if (markedForDeletion && shouldNotDispatchToDelete(resource)) { log.debug( - "Skipping delete of resource {} because finalizer(s) {} don't allow processing yet", - getName(resource), - resource.getMetadata().getFinalizers()); + "Skipping delete of resource {} because finalizer(s) {} don't allow processing yet", + getName(resource), + resource.getMetadata().getFinalizers()); return PostExecutionControl.defaultDispatch(); } - Context context = - new DefaultContext<>(executionScope.getRetryInfo()); + Context context = + new DefaultContext(executionScope.getRetryInfo()); if (markedForDeletion) { return handleDelete(resource, context); } else { @@ -92,7 +96,7 @@ private boolean shouldNotDispatchToDelete(R resource) { } private PostExecutionControl handleCreateOrUpdate( - ExecutionScope executionScope, R resource, Context context) { + ExecutionScope executionScope, R resource, Context context) { if (configuration().useFinalizer() && !resource.hasFinalizer(configuration().getFinalizer())) { /* * We always add the finalizer if missing and the controller is configured to use a finalizer. @@ -161,11 +165,11 @@ private void updatePostExecutionControlWithReschedule( baseControl.getScheduleDelay().ifPresent(postExecutionControl::withReSchedule); } - private PostExecutionControl handleDelete(R resource, Context context) { + private PostExecutionControl handleDelete(R resource, Context context) { log.debug( - "Executing delete for resource: {} with version: {}", - getName(resource), - getVersion(resource)); + "Executing delete for resource: {} with version: {}", + getName(resource), + getVersion(resource)); DeleteControl deleteControl = controller.deleteResource(resource, context); final var useFinalizer = configuration().useFinalizer(); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceEventFilter.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceEventFilter.java index bae73dc3c3..ef78dd3fbd 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceEventFilter.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceEventFilter.java @@ -11,17 +11,17 @@ * @param the type of custom resources handled by this filter */ @FunctionalInterface -public interface CustomResourceEventFilter { +public interface CustomResourceEventFilter> { - /** - * 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 configuration the target controller's configuration - * @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 + /** + * 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 configuration the target controller's configuration + * @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(ControllerConfiguration configuration, T oldResource, T newResource); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceEventFilters.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceEventFilters.java index 7de41c455d..c257678382 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceEventFilters.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceEventFilters.java @@ -8,41 +8,41 @@ */ public final class CustomResourceEventFilters { - private static final CustomResourceEventFilter USE_FINALIZER = - (configuration, oldResource, newResource) -> { - if (configuration.useFinalizer()) { - final var finalizer = configuration.getFinalizer(); - boolean oldFinalizer = oldResource == null || oldResource.hasFinalizer(finalizer); - boolean newFinalizer = newResource.hasFinalizer(finalizer); - - return !newFinalizer || !oldFinalizer; - } else { - return false; - } + private static final CustomResourceEventFilter> USE_FINALIZER = + (configuration, oldResource, newResource) -> { + if (configuration.useFinalizer()) { + final var finalizer = configuration.getFinalizer(); + boolean oldFinalizer = oldResource == null || oldResource.hasFinalizer(finalizer); + boolean newFinalizer = newResource.hasFinalizer(finalizer); + + return !newFinalizer || !oldFinalizer; + } else { + return false; + } }; - private static final CustomResourceEventFilter GENERATION_AWARE = - (configuration, oldResource, newResource) -> { - final var status = newResource.getStatus(); - final var generationAware = configuration.isGenerationAware(); - if (generationAware && status instanceof ObservedGenerationAware) { - var actualGeneration = newResource.getMetadata().getGeneration(); - var observedGeneration = ((ObservedGenerationAware) status) - .getObservedGeneration(); - return observedGeneration.map(aLong -> actualGeneration > aLong).orElse(true); - } - return oldResource == null || !generationAware || + private static final CustomResourceEventFilter> GENERATION_AWARE = + (configuration, oldResource, newResource) -> { + final var status = newResource.getStatus(); + final var generationAware = configuration.isGenerationAware(); + if (generationAware && status instanceof ObservedGenerationAware) { + var actualGeneration = newResource.getMetadata().getGeneration(); + var observedGeneration = ((ObservedGenerationAware) status) + .getObservedGeneration(); + return observedGeneration.map(aLong -> actualGeneration > aLong).orElse(true); + } + return oldResource == null || !generationAware || oldResource.getMetadata().getGeneration() < newResource.getMetadata().getGeneration(); }; - private static final CustomResourceEventFilter PASSTHROUGH = - (configuration, oldResource, newResource) -> true; + private static final CustomResourceEventFilter> PASSTHROUGH = + (configuration, oldResource, newResource) -> true; - private static final CustomResourceEventFilter NONE = - (configuration, oldResource, newResource) -> false; + private static final CustomResourceEventFilter> NONE = + (configuration, oldResource, newResource) -> false; - private static final CustomResourceEventFilter MARKED_FOR_DELETION = - (configuration, oldResource, newResource) -> newResource.isMarkedForDeletion(); + private static final CustomResourceEventFilter> MARKED_FOR_DELETION = + (configuration, oldResource, newResource) -> newResource.isMarkedForDeletion(); private CustomResourceEventFilters() {} @@ -53,7 +53,7 @@ private CustomResourceEventFilters() {} * @return a filter that accepts all events */ @SuppressWarnings("unchecked") - public static CustomResourceEventFilter passthrough() { + public static > CustomResourceEventFilter passthrough() { return (CustomResourceEventFilter) PASSTHROUGH; } @@ -64,7 +64,7 @@ public static CustomResourceEventFilter passthroug * @return a filter that reject all events */ @SuppressWarnings("unchecked") - public static CustomResourceEventFilter none() { + public static > CustomResourceEventFilter none() { return (CustomResourceEventFilter) NONE; } @@ -76,7 +76,7 @@ public static CustomResourceEventFilter none() { * @return a filter accepting changes based on generation information */ @SuppressWarnings("unchecked") - public static CustomResourceEventFilter generationAware() { + public static > CustomResourceEventFilter generationAware() { return (CustomResourceEventFilter) GENERATION_AWARE; } @@ -86,10 +86,10 @@ public static CustomResourceEventFilter generation * * @param the type of custom resource the filter should handle * @return a filter accepting changes based on whether the finalizer is needed and has been - * applied + * applied */ @SuppressWarnings("unchecked") - public static CustomResourceEventFilter finalizerNeededAndApplied() { + public static > CustomResourceEventFilter finalizerNeededAndApplied() { return (CustomResourceEventFilter) USE_FINALIZER; } @@ -100,7 +100,7 @@ public static CustomResourceEventFilter finalizerN * @return a filter accepting changes based on whether the Custom Resource is marked for deletion. */ @SuppressWarnings("unchecked") - public static CustomResourceEventFilter markedForDeletion() { + public static > CustomResourceEventFilter markedForDeletion() { return (CustomResourceEventFilter) MARKED_FOR_DELETION; } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/EventDispatcherTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/EventDispatcherTest.java index 87385e61d2..c03c9b42cb 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/EventDispatcherTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/EventDispatcherTest.java @@ -1,14 +1,5 @@ package io.javaoperatorsdk.operator.processing; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.ArgumentMatchers; - import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.TestUtils; @@ -25,13 +16,19 @@ import io.javaoperatorsdk.operator.processing.event.internal.CustomResourceEvent; import io.javaoperatorsdk.operator.processing.event.internal.ResourceAction; import io.javaoperatorsdk.operator.sample.observedgeneration.ObservedGenCustomResource; +import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.ArgumentMatchers; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import static io.javaoperatorsdk.operator.processing.event.internal.ResourceAction.ADDED; import static io.javaoperatorsdk.operator.processing.event.internal.ResourceAction.UPDATED; 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.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.eq; @@ -44,16 +41,16 @@ class EventDispatcherTest { private static final String DEFAULT_FINALIZER = "javaoperatorsdk.io/finalizer"; - private CustomResource testCustomResource; + private TestCustomResource testCustomResource; private EventDispatcher eventDispatcher; - private final ResourceController controller = mock(ResourceController.class); - private final ControllerConfiguration configuration = - mock(ControllerConfiguration.class); + private final ResourceController controller = mock(ResourceController.class); + private final ControllerConfiguration configuration = + mock(ControllerConfiguration.class); private final ConfigurationService configService = mock(ConfigurationService.class); private final ConfiguredController> configuredController = - new ConfiguredController(controller, configuration, null); + new ConfiguredController(controller, configuration, null); private final EventDispatcher.CustomResourceFacade customResourceFacade = - mock(EventDispatcher.CustomResourceFacade.class); + mock(EventDispatcher.CustomResourceFacade.class); @BeforeEach void setup() { @@ -169,13 +166,14 @@ void doNotCallDeleteIfMarkedForDeletionWhenFinalizerHasAlreadyBeenRemoved() { } private void configureToNotUseFinalizer() { - ControllerConfiguration configuration = mock(ControllerConfiguration.class); + ControllerConfiguration> configuration = + mock(ControllerConfiguration.class); when(configuration.getName()).thenReturn("EventDispatcherTestController"); when(configService.getMetrics()).thenReturn(Metrics.NOOP); when(configuration.getConfigurationService()).thenReturn(configService); when(configuration.useFinalizer()).thenReturn(false); eventDispatcher = new EventDispatcher(new ConfiguredController(controller, configuration, null), - customResourceFacade); + customResourceFacade); } @Test @@ -283,11 +281,11 @@ public boolean isLastAttempt() { } })); - ArgumentCaptor> contextArgumentCaptor = - ArgumentCaptor.forClass(Context.class); + ArgumentCaptor contextArgumentCaptor = + ArgumentCaptor.forClass(Context.class); verify(controller, times(1)) .createOrUpdateResource(eq(testCustomResource), contextArgumentCaptor.capture()); - Context context = contextArgumentCaptor.getValue(); + Context context = contextArgumentCaptor.getValue(); final var retryInfo = context.getRetryInfo().get(); assertThat(retryInfo.getAttemptCount()).isEqualTo(2); assertThat(retryInfo.isLastAttempt()).isEqualTo(true); diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceSelectorTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceSelectorTest.java index 7556d2412a..0600a2ddcb 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceSelectorTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceSelectorTest.java @@ -1,21 +1,5 @@ package io.javaoperatorsdk.operator.processing.event.internal; -import java.text.ParseException; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Date; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Consumer; - -import org.awaitility.core.ConditionTimeoutException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.internal.util.collections.Sets; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.VersionInfo; @@ -30,6 +14,21 @@ import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.config.Version; import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; +import org.awaitility.core.ConditionTimeoutException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.internal.util.collections.Sets; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.text.ParseException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; @@ -187,7 +186,7 @@ public MyController(Consumer consumer) { @Override public UpdateControl createOrUpdateResource( - TestCustomResource resource, Context context) { + TestCustomResource resource, Context context) { LOGGER.info("Received event on: {}", resource); diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceController.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceController.java index 2cef04a09a..80e0a04d87 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceController.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceController.java @@ -1,11 +1,5 @@ package io.javaoperatorsdk.operator.sample.simple; -import java.util.HashMap; -import java.util.Map; - -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.ObjectMetaBuilder; @@ -16,6 +10,11 @@ import io.javaoperatorsdk.operator.api.DeleteControl; import io.javaoperatorsdk.operator.api.ResourceController; import io.javaoperatorsdk.operator.api.UpdateControl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.Map; @Controller(generationAwareEventProcessing = false) public class TestCustomResourceController implements ResourceController { @@ -39,17 +38,17 @@ public TestCustomResourceController(KubernetesClient kubernetesClient, boolean u @Override public DeleteControl deleteResource( - TestCustomResource resource, Context context) { + TestCustomResource resource, Context context) { Boolean delete = - kubernetesClient - .configMaps() - .inNamespace(resource.getMetadata().getNamespace()) - .withName(resource.getSpec().getConfigMapName()) - .delete(); + kubernetesClient + .configMaps() + .inNamespace(resource.getMetadata().getNamespace()) + .withName(resource.getSpec().getConfigMapName()) + .delete(); if (delete) { log.info( - "Deleted ConfigMap {} for resource: {}", - resource.getSpec().getConfigMapName(), + "Deleted ConfigMap {} for resource: {}", + resource.getSpec().getConfigMapName(), resource.getMetadata().getName()); } else { log.error( @@ -62,17 +61,17 @@ public DeleteControl deleteResource( @Override public UpdateControl createOrUpdateResource( - TestCustomResource resource, Context context) { + TestCustomResource resource, Context context) { if (!resource.getMetadata().getFinalizers().contains(FINALIZER_NAME)) { throw new IllegalStateException("Finalizer is not present."); } ConfigMap existingConfigMap = - kubernetesClient - .configMaps() - .inNamespace(resource.getMetadata().getNamespace()) - .withName(resource.getSpec().getConfigMapName()) - .get(); + kubernetesClient + .configMaps() + .inNamespace(resource.getMetadata().getNamespace()) + .withName(resource.getSpec().getConfigMapName()) + .get(); if (existingConfigMap != null) { existingConfigMap.setData(configMapData(resource)); diff --git a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/AnnotationConfiguration.java b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/AnnotationConfiguration.java index ba4cf40250..c6de06dc2a 100644 --- a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/AnnotationConfiguration.java +++ b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/AnnotationConfiguration.java @@ -1,8 +1,5 @@ package io.javaoperatorsdk.operator.config.runtime; -import java.util.Set; -import java.util.function.Function; - import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.ControllerUtils; import io.javaoperatorsdk.operator.api.Controller; @@ -12,8 +9,11 @@ import io.javaoperatorsdk.operator.processing.event.internal.CustomResourceEventFilter; import io.javaoperatorsdk.operator.processing.event.internal.CustomResourceEventFilters; -public class AnnotationConfiguration - implements ControllerConfiguration { +import java.util.Set; +import java.util.function.Function; + +public class AnnotationConfiguration> + implements ControllerConfiguration { private final ResourceController controller; private final Controller annotation; diff --git a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/ClassMappingProvider.java b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/ClassMappingProvider.java index d76db8fbcd..788bf28f09 100644 --- a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/ClassMappingProvider.java +++ b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/ClassMappingProvider.java @@ -1,5 +1,9 @@ package io.javaoperatorsdk.operator.config.runtime; +import org.apache.commons.lang3.ClassUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -11,16 +15,13 @@ import java.util.Map; import java.util.stream.Collectors; -import org.apache.commons.lang3.ClassUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - class ClassMappingProvider { private static final Logger log = LoggerFactory.getLogger(ClassMappingProvider.class); + @SuppressWarnings("unchecked") static Map provide(final String resourcePath, T key, V value) { - Map result = new HashMap(); + Map result = new HashMap<>(); try { final var classLoader = Thread.currentThread().getContextClassLoader(); final Enumeration customResourcesMetadataList = classLoader.getResources(resourcePath); @@ -29,22 +30,22 @@ static Map provide(final String resourcePath, T key, V value) { List classNamePairs = retrieveClassNamePairs(url); classNamePairs.forEach( - clazzPair -> { - try { - final String[] classNames = clazzPair.split(","); - if (classNames.length != 2) { - throw new IllegalStateException( - String.format( - "%s is not valid Mapping metadata, defined in %s", - clazzPair, url)); - } - - result.put( - (T) ClassUtils.getClass(classNames[0]), (V) ClassUtils.getClass(classNames[1])); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - }); + clazzPair -> { + try { + final String[] classNames = clazzPair.split(","); + if (classNames.length != 2) { + throw new IllegalStateException( + String.format( + "%s is not valid Mapping metadata, defined in %s", + clazzPair, url)); + } + + result.put( + (T) ClassUtils.getClass(classNames[0]), (V) ClassUtils.getClass(classNames[1])); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + }); } log.debug("Loaded Controller to CustomResource mappings {}", result); return result; 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 099754acd1..982ac9bb9b 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 @@ -19,22 +19,22 @@ public static DefaultConfigurationService instance() { } @Override - public ControllerConfiguration getConfigurationFor( - ResourceController controller) { - return getConfigurationFor(controller, true); + public > ControllerConfiguration getConfigurationFor( + ResourceController controller) { + return getConfigurationFor(controller, true); } - ControllerConfiguration getConfigurationFor( - ResourceController controller, boolean createIfNeeded) { - var config = super.getConfigurationFor(controller); - if (config == null) { - if (createIfNeeded) { - // create the configuration on demand and register it - config = new AnnotationConfiguration<>(controller); - register(config); - getLogger().info( - "Created configuration for controller {} with name {}", - controller.getClass().getName(), + > ControllerConfiguration getConfigurationFor( + ResourceController controller, boolean createIfNeeded) { + var config = super.getConfigurationFor(controller); + if (config == null) { + if (createIfNeeded) { + // create the configuration on demand and register it + config = new AnnotationConfiguration<>(controller); + register(config); + getLogger().info( + "Created configuration for controller {} with name {}", + controller.getClass().getName(), config.getName()); } } else { diff --git a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/RuntimeControllerMetadata.java b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/RuntimeControllerMetadata.java index 913bab6624..446ea85260 100644 --- a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/RuntimeControllerMetadata.java +++ b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/RuntimeControllerMetadata.java @@ -1,31 +1,31 @@ package io.javaoperatorsdk.operator.config.runtime; -import java.util.Map; - import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.api.ResourceController; +import java.util.Map; + +@SuppressWarnings("rawtypes") public class RuntimeControllerMetadata { public static final String CONTROLLERS_RESOURCE_PATH = "javaoperatorsdk/controllers"; - public static final String DONEABLES_RESOURCE_PATH = "javaoperatorsdk/doneables"; private static final Map, Class> controllerToCustomResourceMappings; static { controllerToCustomResourceMappings = - ClassMappingProvider.provide( - CONTROLLERS_RESOURCE_PATH, ResourceController.class, CustomResource.class); + ClassMappingProvider.provide( + CONTROLLERS_RESOURCE_PATH, ResourceController.class, CustomResource.class); } - static Class getCustomResourceClass( - ResourceController controller) { + static > Class getCustomResourceClass( + ResourceController controller) { final Class customResourceClass = - controllerToCustomResourceMappings.get(controller.getClass()); + controllerToCustomResourceMappings.get(controller.getClass()); if (customResourceClass == null) { throw new IllegalArgumentException( - String.format( - "No custom resource has been found for controller %s", - controller.getClass().getCanonicalName())); + String.format( + "No custom resource has been found for controller %s", + controller.getClass().getCanonicalName())); } return (Class) customResourceClass; } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/runtime/DefaultConfigurationServiceTest.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/runtime/DefaultConfigurationServiceTest.java index 56f1d8ee2e..52fa097920 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/runtime/DefaultConfigurationServiceTest.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/runtime/DefaultConfigurationServiceTest.java @@ -1,13 +1,5 @@ package io.javaoperatorsdk.operator.config.runtime; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.config.AppenderRef; -import org.apache.logging.log4j.core.config.LoggerConfig; -import org.apache.logging.log4j.core.layout.PatternLayout; -import org.apache.logging.log4j.test.appender.ListAppender; -import org.junit.jupiter.api.Test; - import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.model.annotation.Group; import io.fabric8.kubernetes.model.annotation.Version; @@ -16,6 +8,13 @@ import io.javaoperatorsdk.operator.api.Controller; import io.javaoperatorsdk.operator.api.ResourceController; import io.javaoperatorsdk.operator.api.UpdateControl; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.config.AppenderRef; +import org.apache.logging.log4j.core.config.LoggerConfig; +import org.apache.logging.log4j.core.layout.PatternLayout; +import org.apache.logging.log4j.test.appender.ListAppender; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @@ -110,13 +109,13 @@ static class TestCustomFinalizerController @Override public UpdateControl createOrUpdateResource( - InnerCustomResource resource, Context context) { + InnerCustomResource resource, Context context) { return null; } @Group("test.crd") @Version("v1") - public class InnerCustomResource extends CustomResource { + public static class InnerCustomResource extends CustomResource { } } @@ -127,7 +126,7 @@ static class NotAutomaticallyCreated implements ResourceController createOrUpdateResource( - TestCustomResource resource, Context context) { + TestCustomResource resource, Context context) { return null; } } @@ -137,7 +136,7 @@ static class TestCustomResourceController implements ResourceController createOrUpdateResource( - TestCustomResource resource, Context context) { + TestCustomResource resource, Context context) { return null; } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/runtime/TestCustomResource.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/runtime/TestCustomResource.java index 190b73690f..0f94ae92e4 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/runtime/TestCustomResource.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/runtime/TestCustomResource.java @@ -7,5 +7,5 @@ @Group("sample.javaoperatorsdk") @Version("v1") -class TestCustomResource extends CustomResource implements Namespaced { +class TestCustomResource extends CustomResource implements Namespaced { } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomResourceController.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomResourceController.java index 74c313e87d..84f21f6742 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomResourceController.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomResourceController.java @@ -1,13 +1,14 @@ package io.javaoperatorsdk.operator.sample.doubleupdate; -import java.util.HashMap; -import java.util.concurrent.atomic.AtomicInteger; - +import io.javaoperatorsdk.operator.api.Controller; +import io.javaoperatorsdk.operator.api.ResourceController; +import io.javaoperatorsdk.operator.api.UpdateControl; +import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.javaoperatorsdk.operator.api.*; -import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; +import java.util.HashMap; +import java.util.concurrent.atomic.AtomicInteger; @Controller public class DoubleUpdateTestCustomResourceController @@ -21,7 +22,7 @@ public class DoubleUpdateTestCustomResourceController @Override public UpdateControl createOrUpdateResource( - DoubleUpdateTestCustomResource resource, Context context) { + DoubleUpdateTestCustomResource resource, Context context) { numberOfExecutions.addAndGet(1); log.info("Value: " + resource.getSpec().getValue()); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomResourceController.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomResourceController.java index caa5ad9fda..cfb55ef751 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomResourceController.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomResourceController.java @@ -1,16 +1,18 @@ package io.javaoperatorsdk.operator.sample.event; -import java.util.concurrent.atomic.AtomicInteger; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.ControllerUtils; -import io.javaoperatorsdk.operator.api.*; +import io.javaoperatorsdk.operator.api.Controller; +import io.javaoperatorsdk.operator.api.EventSourceInitializer; +import io.javaoperatorsdk.operator.api.ResourceController; +import io.javaoperatorsdk.operator.api.UpdateControl; import io.javaoperatorsdk.operator.processing.event.EventSourceManager; import io.javaoperatorsdk.operator.processing.event.internal.TimerEventSource; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.atomic.AtomicInteger; @Controller public class EventSourceTestCustomResourceController @@ -35,7 +37,7 @@ public void prepareEventSources(EventSourceManager eventSourceManager) { @Override public UpdateControl createOrUpdateResource( - EventSourceTestCustomResource resource, Context context) { + EventSourceTestCustomResource resource, Context context) { timerEventSource.schedule(resource, TIMER_DELAY, TIMER_PERIOD); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informereventsource/InformerEventSourceTestCustomResourceController.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informereventsource/InformerEventSourceTestCustomResourceController.java index 772c93cac3..0f5a820081 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informereventsource/InformerEventSourceTestCustomResourceController.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informereventsource/InformerEventSourceTestCustomResourceController.java @@ -1,15 +1,17 @@ package io.javaoperatorsdk.operator.sample.informereventsource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.client.KubernetesClient; -import io.javaoperatorsdk.operator.api.*; +import io.javaoperatorsdk.operator.api.Controller; +import io.javaoperatorsdk.operator.api.EventSourceInitializer; +import io.javaoperatorsdk.operator.api.ResourceController; +import io.javaoperatorsdk.operator.api.UpdateControl; import io.javaoperatorsdk.operator.junit.KubernetesClientAware; import io.javaoperatorsdk.operator.processing.event.EventSourceManager; import io.javaoperatorsdk.operator.processing.event.internal.InformerEventSource; import io.javaoperatorsdk.operator.processing.event.internal.Mappers; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import static io.javaoperatorsdk.operator.api.Controller.NO_FINALIZER; @@ -40,8 +42,8 @@ public void prepareEventSources(EventSourceManager eventSourceManager) { @Override public UpdateControl createOrUpdateResource( - InformerEventSourceTestCustomResource resource, - Context context) { + InformerEventSourceTestCustomResource resource, + Context context) { // Reading the config map from the informer not from the API // name of the config map same as custom resource for sake of simplicity diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomResourceController.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomResourceController.java index 9c5e363bc5..e31100597b 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomResourceController.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomResourceController.java @@ -1,10 +1,5 @@ package io.javaoperatorsdk.operator.sample.retry; -import java.util.concurrent.atomic.AtomicInteger; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.ControllerUtils; import io.javaoperatorsdk.operator.api.Context; @@ -12,6 +7,10 @@ import io.javaoperatorsdk.operator.api.ResourceController; import io.javaoperatorsdk.operator.api.UpdateControl; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.atomic.AtomicInteger; @Controller public class RetryTestCustomResourceController @@ -28,7 +27,7 @@ public class RetryTestCustomResourceController @Override public UpdateControl createOrUpdateResource( - RetryTestCustomResource resource, Context context) { + RetryTestCustomResource resource, Context context) { numberOfExecutions.addAndGet(1); if (!resource.getMetadata().getFinalizers().contains(FINALIZER_NAME)) { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceController.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceController.java index b6aabd1e67..cd9670f6ec 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceController.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceController.java @@ -1,12 +1,5 @@ package io.javaoperatorsdk.operator.sample.simple; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; - -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.ObjectMetaBuilder; @@ -20,6 +13,12 @@ import io.javaoperatorsdk.operator.api.UpdateControl; import io.javaoperatorsdk.operator.junit.KubernetesClientAware; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; @Controller(generationAwareEventProcessing = false) public class TestCustomResourceController @@ -63,17 +62,17 @@ public void setKubernetesClient(KubernetesClient kubernetesClient) { @Override public DeleteControl deleteResource( - TestCustomResource resource, Context context) { + TestCustomResource resource, Context context) { Boolean delete = - kubernetesClient - .configMaps() - .inNamespace(resource.getMetadata().getNamespace()) - .withName(resource.getSpec().getConfigMapName()) - .delete(); + kubernetesClient + .configMaps() + .inNamespace(resource.getMetadata().getNamespace()) + .withName(resource.getSpec().getConfigMapName()) + .delete(); if (delete) { log.info( - "Deleted ConfigMap {} for resource: {}", - resource.getSpec().getConfigMapName(), + "Deleted ConfigMap {} for resource: {}", + resource.getSpec().getConfigMapName(), resource.getMetadata().getName()); } else { log.error( @@ -86,17 +85,17 @@ public DeleteControl deleteResource( @Override public UpdateControl createOrUpdateResource( - TestCustomResource resource, Context context) { + TestCustomResource resource, Context context) { numberOfExecutions.addAndGet(1); if (!resource.getMetadata().getFinalizers().contains(FINALIZER_NAME)) { throw new IllegalStateException("Finalizer is not present."); } ConfigMap existingConfigMap = - kubernetesClient - .configMaps() - .inNamespace(resource.getMetadata().getNamespace()) - .withName(resource.getSpec().getConfigMapName()) + kubernetesClient + .configMaps() + .inNamespace(resource.getMetadata().getNamespace()) + .withName(resource.getSpec().getConfigMapName()) .get(); if (existingConfigMap != null) { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomResourceController.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomResourceController.java index 82157cf229..845bd6ef21 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomResourceController.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomResourceController.java @@ -1,10 +1,5 @@ package io.javaoperatorsdk.operator.sample.subresource; -import java.util.concurrent.atomic.AtomicInteger; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.ControllerUtils; import io.javaoperatorsdk.operator.api.Context; @@ -12,6 +7,10 @@ import io.javaoperatorsdk.operator.api.ResourceController; import io.javaoperatorsdk.operator.api.UpdateControl; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.atomic.AtomicInteger; @Controller(generationAwareEventProcessing = false) public class SubResourceTestCustomResourceController @@ -26,7 +25,7 @@ public class SubResourceTestCustomResourceController @Override public UpdateControl createOrUpdateResource( - SubResourceTestCustomResource resource, Context context) { + SubResourceTestCustomResource resource, Context context) { numberOfExecutions.addAndGet(1); if (!resource.getMetadata().getFinalizers().contains(FINALIZER_NAME)) { throw new IllegalStateException("Finalizer is not present."); diff --git a/operator-framework/src/test/resources/compile-fixtures/ControllerImplemented2Interfaces.java b/operator-framework/src/test/resources/compile-fixtures/ControllerImplemented2Interfaces.java index e56943fa30..40f0b68126 100644 --- a/operator-framework/src/test/resources/compile-fixtures/ControllerImplemented2Interfaces.java +++ b/operator-framework/src/test/resources/compile-fixtures/ControllerImplemented2Interfaces.java @@ -15,12 +15,12 @@ public static class MyCustomResource extends CustomResource { } @Override - public UpdateControl createOrUpdateResource(MyCustomResource customResource, Context context) { + public UpdateControl createOrUpdateResource(MyCustomResource customResource, Context context) { return UpdateControl.updateCustomResource(null); } @Override - public DeleteControl deleteResource(MyCustomResource customResource, Context context) { + public DeleteControl deleteResource(MyCustomResource customResource, Context context) { return DeleteControl.defaultDelete(); } } diff --git a/operator-framework/src/test/resources/compile-fixtures/ControllerImplementedIntermediateAbstractClass.java b/operator-framework/src/test/resources/compile-fixtures/ControllerImplementedIntermediateAbstractClass.java index 4f5619b4a4..5674a3ed81 100644 --- a/operator-framework/src/test/resources/compile-fixtures/ControllerImplementedIntermediateAbstractClass.java +++ b/operator-framework/src/test/resources/compile-fixtures/ControllerImplementedIntermediateAbstractClass.java @@ -12,12 +12,12 @@ public class ControllerImplementedIntermediateAbstractClass extends public UpdateControl createOrUpdateResource( AbstractController.MyCustomResource customResource, - Context context) { + Context context) { return UpdateControl.updateCustomResource(null); } public DeleteControl deleteResource(AbstractController.MyCustomResource customResource, - Context context) { + Context context) { return DeleteControl.defaultDelete(); } } diff --git a/operator-framework/src/test/resources/compile-fixtures/MultilevelController.java b/operator-framework/src/test/resources/compile-fixtures/MultilevelController.java index d941a16d9d..679fc2f3d0 100644 --- a/operator-framework/src/test/resources/compile-fixtures/MultilevelController.java +++ b/operator-framework/src/test/resources/compile-fixtures/MultilevelController.java @@ -16,12 +16,12 @@ public static class MyCustomResource extends CustomResource { public UpdateControl createOrUpdateResource( MultilevelController.MyCustomResource customResource, - Context context) { + Context context) { return UpdateControl.updateCustomResource(null); } public DeleteControl deleteResource(MultilevelController.MyCustomResource customResource, - Context context) { + Context context) { return DeleteControl.defaultDelete(); } diff --git a/samples/common/src/main/java/io/javaoperatorsdk/operator/sample/CustomServiceController.java b/samples/common/src/main/java/io/javaoperatorsdk/operator/sample/CustomServiceController.java index 67fb81dbd7..8ed1eb854a 100644 --- a/samples/common/src/main/java/io/javaoperatorsdk/operator/sample/CustomServiceController.java +++ b/samples/common/src/main/java/io/javaoperatorsdk/operator/sample/CustomServiceController.java @@ -1,10 +1,5 @@ package io.javaoperatorsdk.operator.sample; -import java.util.Collections; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import io.fabric8.kubernetes.api.model.ServiceBuilder; import io.fabric8.kubernetes.api.model.ServicePort; import io.fabric8.kubernetes.api.model.ServiceSpec; @@ -15,6 +10,10 @@ import io.javaoperatorsdk.operator.api.DeleteControl; import io.javaoperatorsdk.operator.api.ResourceController; import io.javaoperatorsdk.operator.api.UpdateControl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Collections; /** A very simple sample controller that creates a service with a label. */ @Controller @@ -33,25 +32,25 @@ public CustomServiceController(KubernetesClient kubernetesClient) { this.kubernetesClient = kubernetesClient; } - @Override - public DeleteControl deleteResource(CustomService resource, Context context) { - log.info("Execution deleteResource for: {}", resource.getMetadata().getName()); - return DeleteControl.defaultDelete(); - } + @Override + public DeleteControl deleteResource(CustomService resource, Context context) { + log.info("Execution deleteResource for: {}", resource.getMetadata().getName()); + return DeleteControl.defaultDelete(); + } - @Override - public UpdateControl createOrUpdateResource( - CustomService resource, Context context) { - log.info("Execution createOrUpdateResource for: {}", resource.getMetadata().getName()); + @Override + public UpdateControl createOrUpdateResource( + CustomService resource, Context context) { + log.info("Execution createOrUpdateResource for: {}", resource.getMetadata().getName()); - ServicePort servicePort = new ServicePort(); - servicePort.setPort(8080); - ServiceSpec serviceSpec = new ServiceSpec(); - serviceSpec.setPorts(Collections.singletonList(servicePort)); + ServicePort servicePort = new ServicePort(); + servicePort.setPort(8080); + ServiceSpec serviceSpec = new ServiceSpec(); + serviceSpec.setPorts(Collections.singletonList(servicePort)); - kubernetesClient - .services() - .inNamespace(resource.getMetadata().getNamespace()) + kubernetesClient + .services() + .inNamespace(resource.getMetadata().getNamespace()) .createOrReplace( new ServiceBuilder() .withNewMetadata() From fcef33ce4f59304756ca6bddd3687367c3428176 Mon Sep 17 00:00:00 2001 From: Chris Laprun Date: Wed, 27 Oct 2021 22:05:56 +0200 Subject: [PATCH 4/8] chore: clean-up --- .../io/javaoperatorsdk/operator/api/monitoring/Metrics.java | 4 ++-- .../io/javaoperatorsdk/operator/api/DeleteControlTest.java | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) 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 1c3fced1f5..5544bc542e 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 @@ -17,9 +17,9 @@ default void reconcileCustomResource(CustomResourceID customResourceID, default void failedReconciliation(CustomResourceID customResourceID, RuntimeException exception) {} - default void cleanupDoneFor(CustomResourceID customResourceUid) {}; + default void cleanupDoneFor(CustomResourceID customResourceUid) {} - default void finishedReconciliation(CustomResourceID resourceID) {}; + default void finishedReconciliation(CustomResourceID resourceID) {} interface ControllerExecution { diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/DeleteControlTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/DeleteControlTest.java index 645c997285..eb0fddd849 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/DeleteControlTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/api/DeleteControlTest.java @@ -7,9 +7,8 @@ class DeleteControlTest { @Test void cannotReScheduleForDefaultDelete() { - Assertions.assertThrows(IllegalStateException.class, () -> { - DeleteControl.defaultDelete().rescheduleAfter(1000L); - }); + Assertions.assertThrows(IllegalStateException.class, + () -> DeleteControl.defaultDelete().rescheduleAfter(1000L)); } } From 9df916f10cf1e07c2b3600c3e434094714aa68af Mon Sep 17 00:00:00 2001 From: Chris Laprun Date: Wed, 27 Oct 2021 22:21:53 +0200 Subject: [PATCH 5/8] fix: potential performance issue --- .../operator/api/config/ControllerConfigurationOverrider.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 f85870ac76..b9e4f9b7e6 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 @@ -48,7 +48,7 @@ public ControllerConfigurationOverrider addingNamespaces(String... namespaces } public ControllerConfigurationOverrider removingNamespaces(String... namespaces) { - this.namespaces.removeAll(List.of(namespaces)); + List.of(namespaces).forEach(this.namespaces::remove); return this; } From 574bfda148c73be9fea0e7eeff3d8c7a1707fb24 Mon Sep 17 00:00:00 2001 From: Chris Laprun Date: Wed, 27 Oct 2021 22:22:25 +0200 Subject: [PATCH 6/8] chore: clean-up --- .../processing/EventDispatcherTest.java | 66 ++++++++----------- operator-framework-junit5/pom.xml | 2 - .../config/runtime/TypeParameterResolver.java | 15 ++--- pom.xml | 1 + 4 files changed, 34 insertions(+), 50 deletions(-) diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/EventDispatcherTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/EventDispatcherTest.java index c03c9b42cb..b6a81fbf63 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/EventDispatcherTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/EventDispatcherTest.java @@ -11,10 +11,6 @@ import io.javaoperatorsdk.operator.api.config.ConfigurationService; import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.monitoring.Metrics; -import io.javaoperatorsdk.operator.processing.event.CustomResourceID; -import io.javaoperatorsdk.operator.processing.event.Event; -import io.javaoperatorsdk.operator.processing.event.internal.CustomResourceEvent; -import io.javaoperatorsdk.operator.processing.event.internal.ResourceAction; import io.javaoperatorsdk.operator.sample.observedgeneration.ObservedGenCustomResource; import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; import org.junit.jupiter.api.BeforeEach; @@ -23,11 +19,7 @@ import org.mockito.ArgumentMatchers; import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import static io.javaoperatorsdk.operator.processing.event.internal.ResourceAction.ADDED; -import static io.javaoperatorsdk.operator.processing.event.internal.ResourceAction.UPDATED; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.any; @@ -74,9 +66,9 @@ void setup() { void addFinalizerOnNewResource() { assertFalse(testCustomResource.hasFinalizer(DEFAULT_FINALIZER)); eventDispatcher.handleExecution( - executionScopeWithCREvent(ADDED, testCustomResource)); + executionScopeWithCREvent(testCustomResource)); verify(controller, never()) - .createOrUpdateResource(ArgumentMatchers.eq(testCustomResource), any()); + .createOrUpdateResource(ArgumentMatchers.eq(testCustomResource), any()); verify(customResourceFacade, times(1)) .replaceWithLock( argThat(testCustomResource -> testCustomResource.hasFinalizer(DEFAULT_FINALIZER))); @@ -87,9 +79,9 @@ void addFinalizerOnNewResource() { void callCreateOrUpdateOnNewResourceIfFinalizerSet() { testCustomResource.addFinalizer(DEFAULT_FINALIZER); eventDispatcher.handleExecution( - executionScopeWithCREvent(ADDED, testCustomResource)); + executionScopeWithCREvent(testCustomResource)); verify(controller, times(1)) - .createOrUpdateResource(ArgumentMatchers.eq(testCustomResource), any()); + .createOrUpdateResource(ArgumentMatchers.eq(testCustomResource), any()); } @Test @@ -100,7 +92,7 @@ void updatesOnlyStatusSubResourceIfFinalizerSet() { .thenReturn(UpdateControl.updateStatusSubResource(testCustomResource)); eventDispatcher.handleExecution( - executionScopeWithCREvent(ADDED, testCustomResource)); + executionScopeWithCREvent(testCustomResource)); verify(customResourceFacade, times(1)).updateStatus(testCustomResource); verify(customResourceFacade, never()).replaceWithLock(any()); @@ -115,7 +107,7 @@ void updatesBothResourceAndStatusIfFinalizerSet() { when(customResourceFacade.replaceWithLock(testCustomResource)).thenReturn(testCustomResource); eventDispatcher.handleExecution( - executionScopeWithCREvent(UPDATED, testCustomResource)); + executionScopeWithCREvent(testCustomResource)); verify(customResourceFacade, times(1)).replaceWithLock(testCustomResource); verify(customResourceFacade, times(1)).updateStatus(testCustomResource); @@ -126,9 +118,9 @@ void callCreateOrUpdateOnModifiedResourceIfFinalizerSet() { testCustomResource.addFinalizer(DEFAULT_FINALIZER); eventDispatcher.handleExecution( - executionScopeWithCREvent(UPDATED, testCustomResource)); + executionScopeWithCREvent(testCustomResource)); verify(controller, times(1)) - .createOrUpdateResource(ArgumentMatchers.eq(testCustomResource), any()); + .createOrUpdateResource(ArgumentMatchers.eq(testCustomResource), any()); } @Test @@ -138,7 +130,7 @@ void callsDeleteIfObjectHasFinalizerAndMarkedForDelete() { markForDeletion(testCustomResource); eventDispatcher.handleExecution( - executionScopeWithCREvent(UPDATED, testCustomResource)); + executionScopeWithCREvent(testCustomResource)); verify(controller, times(1)).deleteResource(eq(testCustomResource), any()); } @@ -150,7 +142,7 @@ void callDeleteOnControllerIfMarkedForDeletionWhenNoFinalizerIsConfigured() { markForDeletion(testCustomResource); eventDispatcher.handleExecution( - executionScopeWithCREvent(UPDATED, testCustomResource)); + executionScopeWithCREvent(testCustomResource)); verify(controller).deleteResource(eq(testCustomResource), any()); } @@ -160,7 +152,7 @@ void doNotCallDeleteIfMarkedForDeletionWhenFinalizerHasAlreadyBeenRemoved() { markForDeletion(testCustomResource); eventDispatcher.handleExecution( - executionScopeWithCREvent(UPDATED, testCustomResource)); + executionScopeWithCREvent(testCustomResource)); verify(controller, never()).deleteResource(eq(testCustomResource), any()); } @@ -181,7 +173,7 @@ void doesNotAddFinalizerIfConfiguredNotTo() { configureToNotUseFinalizer(); eventDispatcher.handleExecution( - executionScopeWithCREvent(UPDATED, testCustomResource)); + executionScopeWithCREvent(testCustomResource)); assertEquals(0, testCustomResource.getMetadata().getFinalizers().size()); } @@ -192,7 +184,7 @@ void removesDefaultFinalizerOnDeleteIfSet() { markForDeletion(testCustomResource); eventDispatcher.handleExecution( - executionScopeWithCREvent(UPDATED, testCustomResource)); + executionScopeWithCREvent(testCustomResource)); assertEquals(0, testCustomResource.getMetadata().getFinalizers().size()); verify(customResourceFacade, times(1)).replaceWithLock(any()); @@ -207,7 +199,7 @@ void doesNotRemovesTheSetFinalizerIfTheDeleteNotMethodInstructsIt() { markForDeletion(testCustomResource); eventDispatcher.handleExecution( - executionScopeWithCREvent(UPDATED, testCustomResource)); + executionScopeWithCREvent(testCustomResource)); assertEquals(1, testCustomResource.getMetadata().getFinalizers().size()); verify(customResourceFacade, never()).replaceWithLock(any()); @@ -221,7 +213,7 @@ void doesNotUpdateTheResourceIfNoUpdateUpdateControlIfFinalizerSet() { .thenReturn(UpdateControl.noUpdate()); eventDispatcher.handleExecution( - executionScopeWithCREvent(UPDATED, testCustomResource)); + executionScopeWithCREvent(testCustomResource)); verify(customResourceFacade, never()).replaceWithLock(any()); verify(customResourceFacade, never()).updateStatus(testCustomResource); } @@ -233,7 +225,7 @@ void addsFinalizerIfNotMarkedForDeletionAndEmptyCustomResourceReturned() { .thenReturn(UpdateControl.noUpdate()); eventDispatcher.handleExecution( - executionScopeWithCREvent(UPDATED, testCustomResource)); + executionScopeWithCREvent(testCustomResource)); assertEquals(1, testCustomResource.getMetadata().getFinalizers().size()); verify(customResourceFacade, times(1)).replaceWithLock(any()); @@ -245,7 +237,7 @@ void doesNotCallDeleteIfMarkedForDeletionButNotOurFinalizer() { markForDeletion(testCustomResource); eventDispatcher.handleExecution( - executionScopeWithCREvent(UPDATED, testCustomResource)); + executionScopeWithCREvent(testCustomResource)); verify(customResourceFacade, never()).replaceWithLock(any()); verify(controller, never()).deleteResource(eq(testCustomResource), any()); @@ -255,9 +247,9 @@ void doesNotCallDeleteIfMarkedForDeletionButNotOurFinalizer() { void executeControllerRegardlessGenerationInNonGenerationAwareModeIfFinalizerSet() { testCustomResource.addFinalizer(DEFAULT_FINALIZER); eventDispatcher.handleExecution( - executionScopeWithCREvent(UPDATED, testCustomResource)); + executionScopeWithCREvent(testCustomResource)); eventDispatcher.handleExecution( - executionScopeWithCREvent(UPDATED, testCustomResource)); + executionScopeWithCREvent(testCustomResource)); verify(controller, times(2)).createOrUpdateResource(eq(testCustomResource), any()); } @@ -300,7 +292,7 @@ void setReScheduleToPostExecutionControlFromUpdateControl() { UpdateControl.updateStatusSubResource(testCustomResource).rescheduleAfter(1000L)); PostExecutionControl control = eventDispatcher.handleExecution( - executionScopeWithCREvent(ADDED, testCustomResource)); + executionScopeWithCREvent(testCustomResource)); assertThat(control.getReScheduleDelay().get()).isEqualTo(1000L); } @@ -311,11 +303,11 @@ void reScheduleOnDeleteWithoutFinalizerRemoval() { markForDeletion(testCustomResource); when(controller.deleteResource(eq(testCustomResource), any())) - .thenReturn( - DeleteControl.noFinalizerRemoval().rescheduleAfter(1000L)); + .thenReturn( + DeleteControl.noFinalizerRemoval().rescheduleAfter(1000L)); - PostExecutionControl control = eventDispatcher.handleExecution( - executionScopeWithCREvent(UPDATED, testCustomResource)); + PostExecutionControl control = + eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); assertThat(control.getReScheduleDelay().get()).isEqualTo(1000L); } @@ -355,13 +347,7 @@ private void removeFinalizers(CustomResource customResource) { customResource.getMetadata().getFinalizers().clear(); } - public ExecutionScope executionScopeWithCREvent( - ResourceAction action, CustomResource resource, Event... otherEvents) { - CustomResourceEvent event = - new CustomResourceEvent(action, CustomResourceID.fromResource(resource)); - List eventList = new ArrayList<>(1 + otherEvents.length); - eventList.add(event); - eventList.addAll(Arrays.asList(otherEvents)); - return new ExecutionScope(resource, null); + public > ExecutionScope executionScopeWithCREvent(T resource) { + return new ExecutionScope<>(resource, null); } } diff --git a/operator-framework-junit5/pom.xml b/operator-framework-junit5/pom.xml index 5ffef0d184..7a9977ded0 100644 --- a/operator-framework-junit5/pom.xml +++ b/operator-framework-junit5/pom.xml @@ -34,12 +34,10 @@ org.assertj assertj-core - 3.20.2 org.awaitility awaitility - 4.1.0 diff --git a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/TypeParameterResolver.java b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/TypeParameterResolver.java index 8ef145d8b9..bc9b3a0679 100644 --- a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/TypeParameterResolver.java +++ b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/TypeParameterResolver.java @@ -1,10 +1,5 @@ package io.javaoperatorsdk.operator.config.runtime; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.type.DeclaredType; @@ -12,6 +7,10 @@ import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; import javax.lang.model.util.Types; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import static javax.lang.model.type.TypeKind.DECLARED; import static javax.lang.model.type.TypeKind.TYPEVAR; @@ -75,9 +74,9 @@ public TypeMirror resolve(Types typeUtils, DeclaredType declaredType) { private int getTypeIndexWithName( String typeName, List typeParameters) { return IntStream.range(0, typeParameters.size()) - .filter(i -> typeParameters.get(i).getSimpleName().toString().equals(typeName)) - .findFirst() - .getAsInt(); + .filter(i -> typeParameters.get(i).getSimpleName().toString().equals(typeName)) + .findFirst() + .orElseThrow(); } private List findChain(Types typeUtils, DeclaredType declaredType) { diff --git a/pom.xml b/pom.xml index def68a848c..3efc3b0f38 100644 --- a/pom.xml +++ b/pom.xml @@ -301,6 +301,7 @@ format + ${josdk.project.root}/contributing/eclipse-google-style.xml From 685ee12e6b904fab46763084dc50936aed55ee20 Mon Sep 17 00:00:00 2001 From: Chris Laprun Date: Wed, 27 Oct 2021 22:29:52 +0200 Subject: [PATCH 7/8] fix: more generics fixes --- .../test/resources/compile-fixtures/AbstractController.java | 4 ++-- .../compile-fixtures/AdditionalControllerInterface.java | 2 +- .../compile-fixtures/ControllerImplemented2Interfaces.java | 2 +- .../compile-fixtures/MultilevelAbstractController.java | 2 +- .../test/resources/compile-fixtures/MultilevelController.java | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/operator-framework/src/test/resources/compile-fixtures/AbstractController.java b/operator-framework/src/test/resources/compile-fixtures/AbstractController.java index 0acdf6be15..d35a18c070 100644 --- a/operator-framework/src/test/resources/compile-fixtures/AbstractController.java +++ b/operator-framework/src/test/resources/compile-fixtures/AbstractController.java @@ -5,10 +5,10 @@ import java.io.Serializable; -public abstract class AbstractController implements Serializable, +public abstract class AbstractController> implements Serializable, ResourceController { - public static class MyCustomResource extends CustomResource { + public static class MyCustomResource extends CustomResource { } } diff --git a/operator-framework/src/test/resources/compile-fixtures/AdditionalControllerInterface.java b/operator-framework/src/test/resources/compile-fixtures/AdditionalControllerInterface.java index e5d95ab57a..01077510f5 100644 --- a/operator-framework/src/test/resources/compile-fixtures/AdditionalControllerInterface.java +++ b/operator-framework/src/test/resources/compile-fixtures/AdditionalControllerInterface.java @@ -5,7 +5,7 @@ import java.io.Serializable; -public interface AdditionalControllerInterface extends +public interface AdditionalControllerInterface> extends Serializable, ResourceController { } diff --git a/operator-framework/src/test/resources/compile-fixtures/ControllerImplemented2Interfaces.java b/operator-framework/src/test/resources/compile-fixtures/ControllerImplemented2Interfaces.java index 40f0b68126..2b0fa58a8f 100644 --- a/operator-framework/src/test/resources/compile-fixtures/ControllerImplemented2Interfaces.java +++ b/operator-framework/src/test/resources/compile-fixtures/ControllerImplemented2Interfaces.java @@ -11,7 +11,7 @@ @Controller public class ControllerImplemented2Interfaces implements Serializable, ResourceController { - public static class MyCustomResource extends CustomResource { + public static class MyCustomResource extends CustomResource { } @Override diff --git a/operator-framework/src/test/resources/compile-fixtures/MultilevelAbstractController.java b/operator-framework/src/test/resources/compile-fixtures/MultilevelAbstractController.java index 604652e879..4fe30adfe3 100644 --- a/operator-framework/src/test/resources/compile-fixtures/MultilevelAbstractController.java +++ b/operator-framework/src/test/resources/compile-fixtures/MultilevelAbstractController.java @@ -4,7 +4,7 @@ import java.io.Serializable; -public abstract class MultilevelAbstractController implements +public abstract class MultilevelAbstractController> implements Serializable, AdditionalControllerInterface { diff --git a/operator-framework/src/test/resources/compile-fixtures/MultilevelController.java b/operator-framework/src/test/resources/compile-fixtures/MultilevelController.java index 679fc2f3d0..0c07065337 100644 --- a/operator-framework/src/test/resources/compile-fixtures/MultilevelController.java +++ b/operator-framework/src/test/resources/compile-fixtures/MultilevelController.java @@ -10,7 +10,7 @@ public class MultilevelController extends MultilevelAbstractController { - public static class MyCustomResource extends CustomResource { + public static class MyCustomResource extends CustomResource { } From 4b5eff8d8b284717f6660c4d390a4239b3b7f4db Mon Sep 17 00:00:00 2001 From: Chris Laprun Date: Thu, 28 Oct 2021 12:22:23 +0200 Subject: [PATCH 8/8] fix: format and EventDispatcherTest --- .../operator/ControllerUtils.java | 4 +- .../io/javaoperatorsdk/operator/Operator.java | 47 +++--- .../operator/api/BaseControl.java | 14 +- .../javaoperatorsdk/operator/api/Context.java | 2 +- .../operator/api/DefaultContext.java | 14 +- .../operator/api/DeleteControl.java | 2 +- .../operator/api/ResourceController.java | 44 +++--- .../operator/api/UpdateControl.java | 6 +- .../config/AbstractConfigurationService.java | 26 ++-- .../api/config/ConfigurationService.java | 15 +- .../config/ConfigurationServiceOverrider.java | 6 +- .../api/config/ControllerConfiguration.java | 8 +- .../processing/ConfiguredController.java | 46 +++--- .../processing/DefaultEventHandler.java | 25 ++-- .../operator/processing/EventDispatcher.java | 22 +-- .../event/DefaultEventSourceManager.java | 2 +- .../processing/event/EventSource.java | 3 +- .../internal/CustomResourceEventFilter.java | 18 +-- .../internal/CustomResourceEventFilters.java | 48 +++--- .../processing/EventDispatcherTest.java | 137 +++++++++--------- .../internal/CustomResourceSelectorTest.java | 33 +++-- .../simple/TestCustomResourceController.java | 39 ++--- .../runtime/AnnotationConfiguration.java | 8 +- .../config/runtime/ClassMappingProvider.java | 40 ++--- .../runtime/DefaultConfigurationService.java | 26 ++-- .../runtime/RuntimeControllerMetadata.java | 18 +-- .../config/runtime/TypeParameterResolver.java | 15 +- .../DefaultConfigurationServiceTest.java | 21 +-- ...bleUpdateTestCustomResourceController.java | 14 +- ...entSourceTestCustomResourceController.java | 12 +- ...entSourceTestCustomResourceController.java | 10 +- .../RetryTestCustomResourceController.java | 11 +- .../simple/TestCustomResourceController.java | 39 ++--- ...bResourceTestCustomResourceController.java | 11 +- .../sample/CustomServiceController.java | 41 +++--- 35 files changed, 422 insertions(+), 405 deletions(-) diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ControllerUtils.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ControllerUtils.java index d963b61e2a..b525055a81 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ControllerUtils.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/ControllerUtils.java @@ -1,10 +1,10 @@ package io.javaoperatorsdk.operator; +import java.util.Locale; + import io.javaoperatorsdk.operator.api.Controller; import io.javaoperatorsdk.operator.api.ResourceController; -import java.util.Locale; - @SuppressWarnings("rawtypes") public class ControllerUtils { 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 9198a30070..ae094b25c6 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 @@ -1,5 +1,14 @@ package io.javaoperatorsdk.operator; +import java.net.ConnectException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient; @@ -10,14 +19,6 @@ import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.config.ExecutorServiceManager; import io.javaoperatorsdk.operator.processing.ConfiguredController; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.net.ConnectException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; @SuppressWarnings("rawtypes") public class Operator implements AutoCloseable, LifecycleAware { @@ -110,12 +111,12 @@ public void close() { * registration of the controller is delayed till the operator is started. * * @param controller the controller to register - * @param the {@code CustomResource} type associated with the controller + * @param the {@code CustomResource} type associated with the controller * @throws OperatorException if a problem occurred during the registration process */ public > void register(ResourceController controller) - throws OperatorException { - register(controller, null); + throws OperatorException { + register(controller, null); } /** @@ -132,22 +133,22 @@ public void close() { * @throws OperatorException if a problem occurred during the registration process */ public > void register( - ResourceController controller, ControllerConfiguration configuration) - throws OperatorException { - final var existing = configurationService.getConfigurationFor(controller); - if (existing == null) { - log.warn( - "Skipping registration of {} controller named {} because its configuration cannot be found.\n" - + "Known controllers are: {}", - controller.getClass().getCanonicalName(), - ControllerUtils.getNameFor(controller), - configurationService.getKnownControllerNames()); + ResourceController controller, ControllerConfiguration configuration) + throws OperatorException { + final var existing = configurationService.getConfigurationFor(controller); + if (existing == null) { + log.warn( + "Skipping registration of {} controller named {} because its configuration cannot be found.\n" + + "Known controllers are: {}", + controller.getClass().getCanonicalName(), + ControllerUtils.getNameFor(controller), + configurationService.getKnownControllerNames()); } else { if (configuration == null) { configuration = existing; } - final var configuredController = - new ConfiguredController<>(controller, configuration, kubernetesClient); + final var configuredController = + new ConfiguredController<>(controller, configuration, kubernetesClient); controllers.add(configuredController); final var watchedNS = diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/BaseControl.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/BaseControl.java index 72b16cda1c..aeca177cae 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/BaseControl.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/BaseControl.java @@ -5,15 +5,15 @@ public abstract class BaseControl> { - private Long scheduleDelay = null; + private Long scheduleDelay = null; - public T rescheduleAfter(long delay) { - this.scheduleDelay = delay; - return (T) this; - } + public T rescheduleAfter(long delay) { + this.scheduleDelay = delay; + return (T) this; + } - public T rescheduleAfter(long delay, TimeUnit timeUnit) { - return rescheduleAfter(timeUnit.toMillis(delay)); + public T rescheduleAfter(long delay, TimeUnit timeUnit) { + return rescheduleAfter(timeUnit.toMillis(delay)); } public Optional getScheduleDelay() { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/Context.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/Context.java index 3883f496fa..3651414c16 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/Context.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/Context.java @@ -4,6 +4,6 @@ public interface Context { - Optional getRetryInfo(); + Optional getRetryInfo(); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/DefaultContext.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/DefaultContext.java index 5a8b4fcbd4..b74793d25c 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/DefaultContext.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/DefaultContext.java @@ -4,14 +4,14 @@ public class DefaultContext implements Context { - private final RetryInfo retryInfo; + private final RetryInfo retryInfo; - public DefaultContext(RetryInfo retryInfo) { - this.retryInfo = retryInfo; - } + public DefaultContext(RetryInfo retryInfo) { + this.retryInfo = retryInfo; + } - @Override - public Optional getRetryInfo() { - return Optional.ofNullable(retryInfo); + @Override + public Optional getRetryInfo() { + return Optional.ofNullable(retryInfo); } } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/DeleteControl.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/DeleteControl.java index 55631d5392..0c2c3c87e5 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/DeleteControl.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/DeleteControl.java @@ -23,7 +23,7 @@ public boolean isRemoveFinalizer() { @Override public DeleteControl rescheduleAfter(long delay) { if (removeFinalizer) { - throw new IllegalStateException("Cannot reschedule deleteResource if removing finalizer"); + throw new IllegalStateException("Cannot reschedule deleteResource if removing finalizer"); } return super.rescheduleAfter(delay); } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/ResourceController.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/ResourceController.java index b69149b1da..7fe27ec908 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/ResourceController.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/ResourceController.java @@ -4,33 +4,33 @@ public interface ResourceController> { - /** - * Note that this method is used in combination of finalizers. If automatic finalizer handling is - * turned off for the controller, this method is not called. - * - * The implementation should delete the associated component(s). Note that this is method is - * called when an object is marked for deletion. After it's executed the custom resource finalizer - * is automatically removed by the framework; unless the return value is - * {@link DeleteControl#noFinalizerRemoval()}, which indicates that the controller has determined - * that the resource should not be deleted yet. This is usually a corner case, when a cleanup is + /** + * Note that this method is used in combination of finalizers. If automatic finalizer handling is + * turned off for the controller, this method is not called. + * + * The implementation should delete the associated component(s). Note that this is method is + * called when an object is marked for deletion. After it's executed the custom resource finalizer + * is automatically removed by the framework; unless the return value is + * {@link DeleteControl#noFinalizerRemoval()}, which indicates that the controller has determined + * that the resource should not be deleted yet. This is usually a corner case, when a cleanup is * tried again eventually. * *

* It's important that this method be idempotent, as it could be called several times, depending * on the conditions and the controller's configuration (for example, if the controller is - * configured to not use a finalizer but the resource does have finalizers, it might be be - * "offered" again for deletion several times until the finalizers are all removed. - * - * @param resource the resource that is marked for deletion - * @param context the context with which the operation is executed - * @return {@link DeleteControl#defaultDelete()} - so the finalizer is automatically removed after - * the call. {@link DeleteControl#noFinalizerRemoval()} if you don't want to remove the - * finalizer to indicate that the resource should not be deleted after all, in which case - * the controller should restore the resource's state appropriately. - */ - default DeleteControl deleteResource(R resource, Context context) { - return DeleteControl.defaultDelete(); - } + * configured to not use a finalizer but the resource does have finalizers, it might be be + * "offered" again for deletion several times until the finalizers are all removed. + * + * @param resource the resource that is marked for deletion + * @param context the context with which the operation is executed + * @return {@link DeleteControl#defaultDelete()} - so the finalizer is automatically removed after + * the call. {@link DeleteControl#noFinalizerRemoval()} if you don't want to remove the + * finalizer to indicate that the resource should not be deleted after all, in which case + * the controller should restore the resource's state appropriately. + */ + default DeleteControl deleteResource(R resource, Context context) { + return DeleteControl.defaultDelete(); + } /** * The implementation of this operation is required to be idempotent. Always use the UpdateControl diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/UpdateControl.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/UpdateControl.java index 0d374e1b9a..2c9531ca06 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/UpdateControl.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/UpdateControl.java @@ -10,7 +10,7 @@ public class UpdateControl extends BaseControl UpdateControl updateCustomResource(T } public static UpdateControl updateStatusSubResource( - T customResource) { + T customResource) { return new UpdateControl<>(customResource, true, false); } @@ -36,7 +36,7 @@ public static UpdateControl updateStatusSubResourc * @return UpdateControl instance */ public static > UpdateControl updateCustomResourceAndStatus( - T customResource) { + T customResource) { return new UpdateControl<>(customResource, true, true); } 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 c68c68c4cc..af9c7856b8 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 @@ -1,14 +1,14 @@ package io.javaoperatorsdk.operator.api.config; -import io.fabric8.kubernetes.client.CustomResource; -import io.javaoperatorsdk.operator.ControllerUtils; -import io.javaoperatorsdk.operator.api.ResourceController; - import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Stream; +import io.fabric8.kubernetes.client.CustomResource; +import io.javaoperatorsdk.operator.ControllerUtils; +import io.javaoperatorsdk.operator.api.ResourceController; + @SuppressWarnings("rawtypes") public class AbstractConfigurationService implements ConfigurationService { private final Map configurations = new ConcurrentHashMap<>(); @@ -27,7 +27,7 @@ public AbstractConfigurationService(Version version) { } private > void put( - ControllerConfiguration config, boolean failIfExisting) { + ControllerConfiguration config, boolean failIfExisting) { final var name = config.getName(); if (failIfExisting) { final var existing = configurations.get(name); @@ -40,19 +40,19 @@ public AbstractConfigurationService(Version version) { } protected > void throwExceptionOnNameCollision( - String newControllerClassName, ControllerConfiguration existing) { + String newControllerClassName, ControllerConfiguration existing) { throw new IllegalArgumentException( - "Controller name '" - + existing.getName() - + "' is used by both " - + existing.getAssociatedControllerClassName() - + " and " - + newControllerClassName); + "Controller name '" + + existing.getName() + + "' is used by both " + + existing.getAssociatedControllerClassName() + + " and " + + newControllerClassName); } @Override public > ControllerConfiguration getConfigurationFor( - ResourceController controller) { + ResourceController controller) { final var key = keyFor(controller); final var configuration = configurations.get(key); if (configuration == null) { 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 78e0952fee..b65115ec56 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 @@ -1,15 +1,16 @@ package io.javaoperatorsdk.operator.api.config; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.api.ResourceController; import io.javaoperatorsdk.operator.api.monitoring.Metrics; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; /** An interface from which to retrieve configuration information. */ public interface ConfigurationService { @@ -31,12 +32,12 @@ public interface ConfigurationService { * Retrieves the configuration associated with the specified controller * * @param controller the controller we want the configuration of - * @param the {@code CustomResource} type associated with the specified controller + * @param the {@code CustomResource} type associated with the specified controller * @return the {@link ControllerConfiguration} associated with the specified controller or {@code * null} if no configuration exists for the controller */ > ControllerConfiguration getConfigurationFor( - ResourceController controller); + ResourceController controller); /** * Retrieves the Kubernetes client configuration 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 48d4f5b254..62630f3ce2 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 @@ -1,12 +1,12 @@ package io.javaoperatorsdk.operator.api.config; +import java.util.Set; + import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.api.ResourceController; import io.javaoperatorsdk.operator.api.monitoring.Metrics; -import java.util.Set; - public class ConfigurationServiceOverrider { private final ConfigurationService original; private Metrics metrics; @@ -62,7 +62,7 @@ public ConfigurationService build() { return new ConfigurationService() { @Override public > ControllerConfiguration getConfigurationFor( - ResourceController controller) { + ResourceController controller) { return original.getConfigurationFor(controller); } 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 3a64c12ce1..65ec26964b 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,15 +1,15 @@ package io.javaoperatorsdk.operator.api.config; +import java.lang.reflect.ParameterizedType; +import java.util.Collections; +import java.util.Set; + import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.ControllerUtils; import io.javaoperatorsdk.operator.api.Controller; import io.javaoperatorsdk.operator.processing.event.internal.CustomResourceEventFilter; import io.javaoperatorsdk.operator.processing.event.internal.CustomResourceEventFilters; -import java.lang.reflect.ParameterizedType; -import java.util.Collections; -import java.util.Set; - public interface ControllerConfiguration> { default String getName() { diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/ConfiguredController.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/ConfiguredController.java index f15fa257b1..a22d135317 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/ConfiguredController.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/ConfiguredController.java @@ -1,5 +1,7 @@ package io.javaoperatorsdk.operator.processing; +import java.util.Objects; + import io.fabric8.kubernetes.api.model.KubernetesResourceList; import io.fabric8.kubernetes.api.model.apiextensions.v1.CustomResourceDefinition; import io.fabric8.kubernetes.client.CustomResource; @@ -20,18 +22,16 @@ import io.javaoperatorsdk.operator.processing.event.DefaultEventSourceManager; import io.javaoperatorsdk.operator.processing.event.EventSourceManager; -import java.util.Objects; - public class ConfiguredController> implements ResourceController, - LifecycleAware, EventSourceInitializer { + LifecycleAware, EventSourceInitializer { private final ResourceController controller; private final ControllerConfiguration configuration; private final KubernetesClient kubernetesClient; private DefaultEventSourceManager eventSourceManager; public ConfiguredController(ResourceController controller, - ControllerConfiguration configuration, - KubernetesClient kubernetesClient) { + ControllerConfiguration configuration, + KubernetesClient kubernetesClient) { this.controller = controller; this.configuration = configuration; this.kubernetesClient = kubernetesClient; @@ -40,15 +40,15 @@ public ConfiguredController(ResourceController controller, @Override public DeleteControl deleteResource(R resource, Context context) { return configuration.getConfigurationService().getMetrics().timeControllerExecution( - new ControllerExecution<>() { - @Override - public String name() { - return "delete"; - } - - @Override - public String controllerName() { - return configuration.getName(); + new ControllerExecution<>() { + @Override + public String name() { + return "delete"; + } + + @Override + public String controllerName() { + return configuration.getName(); } @Override @@ -66,15 +66,15 @@ public DeleteControl execute() { @Override public UpdateControl createOrUpdateResource(R resource, Context context) { return configuration.getConfigurationService().getMetrics().timeControllerExecution( - new ControllerExecution<>() { - @Override - public String name() { - return "createOrUpdate"; - } - - @Override - public String controllerName() { - return configuration.getName(); + new ControllerExecution<>() { + @Override + public String name() { + return "createOrUpdate"; + } + + @Override + public String controllerName() { + return configuration.getName(); } @Override diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/DefaultEventHandler.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/DefaultEventHandler.java index 6a9fec7b71..212cd378d7 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/DefaultEventHandler.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/DefaultEventHandler.java @@ -1,5 +1,17 @@ package io.javaoperatorsdk.operator.processing; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.locks.ReentrantLock; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.OperatorException; import io.javaoperatorsdk.operator.api.LifecycleAware; @@ -16,17 +28,6 @@ import io.javaoperatorsdk.operator.processing.retry.GenericRetry; import io.javaoperatorsdk.operator.processing.retry.Retry; import io.javaoperatorsdk.operator.processing.retry.RetryExecution; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.locks.ReentrantLock; import static io.javaoperatorsdk.operator.processing.KubernetesResourceUtils.getName; import static io.javaoperatorsdk.operator.processing.KubernetesResourceUtils.getVersion; @@ -36,7 +37,7 @@ * UID, while buffering events which are received during an execution. */ public class DefaultEventHandler> - implements EventHandler, LifecycleAware { + implements EventHandler, LifecycleAware { private static final Logger log = LoggerFactory.getLogger(DefaultEventHandler.class); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/EventDispatcher.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/EventDispatcher.java index 5aeb71fecb..3764667288 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/EventDispatcher.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/EventDispatcher.java @@ -1,19 +1,21 @@ package io.javaoperatorsdk.operator.processing; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import io.fabric8.kubernetes.api.model.KubernetesResourceList; import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; import io.javaoperatorsdk.operator.api.BaseControl; +import io.javaoperatorsdk.operator.api.Context; import io.javaoperatorsdk.operator.api.DefaultContext; import io.javaoperatorsdk.operator.api.DeleteControl; import io.javaoperatorsdk.operator.api.ObservedGenerationAware; import io.javaoperatorsdk.operator.api.ResourceController; import io.javaoperatorsdk.operator.api.UpdateControl; import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import static io.javaoperatorsdk.operator.processing.KubernetesResourceUtils.getName; import static io.javaoperatorsdk.operator.processing.KubernetesResourceUtils.getUID; @@ -62,14 +64,14 @@ private PostExecutionControl handleDispatch(ExecutionScope executionScope) final var markedForDeletion = resource.isMarkedForDeletion(); if (markedForDeletion && shouldNotDispatchToDelete(resource)) { log.debug( - "Skipping delete of resource {} because finalizer(s) {} don't allow processing yet", - getName(resource), - resource.getMetadata().getFinalizers()); + "Skipping delete of resource {} because finalizer(s) {} don't allow processing yet", + getName(resource), + resource.getMetadata().getFinalizers()); return PostExecutionControl.defaultDispatch(); } Context context = - new DefaultContext(executionScope.getRetryInfo()); + new DefaultContext(executionScope.getRetryInfo()); if (markedForDeletion) { return handleDelete(resource, context); } else { @@ -96,7 +98,7 @@ private boolean shouldNotDispatchToDelete(R resource) { } private PostExecutionControl handleCreateOrUpdate( - ExecutionScope executionScope, R resource, Context context) { + ExecutionScope executionScope, R resource, Context context) { if (configuration().useFinalizer() && !resource.hasFinalizer(configuration().getFinalizer())) { /* * We always add the finalizer if missing and the controller is configured to use a finalizer. @@ -167,9 +169,9 @@ private void updatePostExecutionControlWithReschedule( private PostExecutionControl handleDelete(R resource, Context context) { log.debug( - "Executing delete for resource: {} with version: {}", - getName(resource), - getVersion(resource)); + "Executing delete for resource: {} with version: {}", + getName(resource), + getVersion(resource)); DeleteControl deleteControl = controller.deleteResource(resource, context); final var useFinalizer = configuration().useFinalizer(); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/DefaultEventSourceManager.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/DefaultEventSourceManager.java index bedda50df3..dd8e7f19ce 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/DefaultEventSourceManager.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/DefaultEventSourceManager.java @@ -19,7 +19,7 @@ import io.javaoperatorsdk.operator.processing.event.internal.TimerEventSource; public class DefaultEventSourceManager> - implements EventSourceManager, LifecycleAware { + implements EventSourceManager, LifecycleAware { private static final Logger log = LoggerFactory.getLogger(DefaultEventSourceManager.class); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSource.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSource.java index 58bf357f49..7646dcc353 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSource.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/EventSource.java @@ -11,6 +11,5 @@ public interface EventSource extends LifecycleAware { * * @param customResourceUid - id of custom resource */ - default void cleanupForCustomResource(CustomResourceID customResourceUid) { - } + default void cleanupForCustomResource(CustomResourceID customResourceUid) {} } diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceEventFilter.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceEventFilter.java index ef78dd3fbd..cf9802674e 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceEventFilter.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceEventFilter.java @@ -13,15 +13,15 @@ @FunctionalInterface public interface CustomResourceEventFilter> { - /** - * 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 configuration the target controller's configuration - * @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 + /** + * 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 configuration the target controller's configuration + * @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(ControllerConfiguration configuration, T oldResource, T newResource); diff --git a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceEventFilters.java b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceEventFilters.java index c257678382..63584a2c86 100644 --- a/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceEventFilters.java +++ b/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceEventFilters.java @@ -9,40 +9,40 @@ public final class CustomResourceEventFilters { private static final CustomResourceEventFilter> USE_FINALIZER = - (configuration, oldResource, newResource) -> { - if (configuration.useFinalizer()) { - final var finalizer = configuration.getFinalizer(); - boolean oldFinalizer = oldResource == null || oldResource.hasFinalizer(finalizer); - boolean newFinalizer = newResource.hasFinalizer(finalizer); - - return !newFinalizer || !oldFinalizer; - } else { - return false; - } + (configuration, oldResource, newResource) -> { + if (configuration.useFinalizer()) { + final var finalizer = configuration.getFinalizer(); + boolean oldFinalizer = oldResource == null || oldResource.hasFinalizer(finalizer); + boolean newFinalizer = newResource.hasFinalizer(finalizer); + + return !newFinalizer || !oldFinalizer; + } else { + return false; + } }; private static final CustomResourceEventFilter> GENERATION_AWARE = - (configuration, oldResource, newResource) -> { - final var status = newResource.getStatus(); - final var generationAware = configuration.isGenerationAware(); - if (generationAware && status instanceof ObservedGenerationAware) { - var actualGeneration = newResource.getMetadata().getGeneration(); - var observedGeneration = ((ObservedGenerationAware) status) - .getObservedGeneration(); - return observedGeneration.map(aLong -> actualGeneration > aLong).orElse(true); - } - return oldResource == null || !generationAware || + (configuration, oldResource, newResource) -> { + final var status = newResource.getStatus(); + final var generationAware = configuration.isGenerationAware(); + if (generationAware && status instanceof ObservedGenerationAware) { + var actualGeneration = newResource.getMetadata().getGeneration(); + var observedGeneration = ((ObservedGenerationAware) status) + .getObservedGeneration(); + return observedGeneration.map(aLong -> actualGeneration > aLong).orElse(true); + } + return oldResource == null || !generationAware || oldResource.getMetadata().getGeneration() < newResource.getMetadata().getGeneration(); }; private static final CustomResourceEventFilter> PASSTHROUGH = - (configuration, oldResource, newResource) -> true; + (configuration, oldResource, newResource) -> true; private static final CustomResourceEventFilter> NONE = - (configuration, oldResource, newResource) -> false; + (configuration, oldResource, newResource) -> false; private static final CustomResourceEventFilter> MARKED_FOR_DELETION = - (configuration, oldResource, newResource) -> newResource.isMarkedForDeletion(); + (configuration, oldResource, newResource) -> newResource.isMarkedForDeletion(); private CustomResourceEventFilters() {} @@ -86,7 +86,7 @@ private CustomResourceEventFilters() {} * * @param the type of custom resource the filter should handle * @return a filter accepting changes based on whether the finalizer is needed and has been - * applied + * applied */ @SuppressWarnings("unchecked") public static > CustomResourceEventFilter finalizerNeededAndApplied() { diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/EventDispatcherTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/EventDispatcherTest.java index b6a81fbf63..1c651afa60 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/EventDispatcherTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/EventDispatcherTest.java @@ -1,5 +1,12 @@ package io.javaoperatorsdk.operator.processing; +import java.util.ArrayList; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.ArgumentMatchers; + import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.TestUtils; @@ -11,16 +18,14 @@ import io.javaoperatorsdk.operator.api.config.ConfigurationService; import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.monitoring.Metrics; +import io.javaoperatorsdk.operator.processing.EventDispatcher.CustomResourceFacade; import io.javaoperatorsdk.operator.sample.observedgeneration.ObservedGenCustomResource; import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.ArgumentMatchers; - -import java.util.ArrayList; 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.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.eq; @@ -34,54 +39,57 @@ class EventDispatcherTest { private static final String DEFAULT_FINALIZER = "javaoperatorsdk.io/finalizer"; private TestCustomResource testCustomResource; - private EventDispatcher eventDispatcher; + private EventDispatcher eventDispatcher; private final ResourceController controller = mock(ResourceController.class); private final ControllerConfiguration configuration = - mock(ControllerConfiguration.class); + mock(ControllerConfiguration.class); private final ConfigurationService configService = mock(ConfigurationService.class); - private final ConfiguredController> configuredController = - new ConfiguredController(controller, configuration, null); - private final EventDispatcher.CustomResourceFacade customResourceFacade = - mock(EventDispatcher.CustomResourceFacade.class); + private final CustomResourceFacade customResourceFacade = + mock(EventDispatcher.CustomResourceFacade.class); @BeforeEach void setup() { - eventDispatcher = new EventDispatcher(configuredController, customResourceFacade); - testCustomResource = TestUtils.testCustomResource(); + eventDispatcher = init(testCustomResource, controller, configuration, customResourceFacade); + } + private > EventDispatcher init(R customResource, + ResourceController controller, ControllerConfiguration configuration, + CustomResourceFacade customResourceFacade) { when(configuration.getFinalizer()).thenReturn(DEFAULT_FINALIZER); when(configuration.useFinalizer()).thenCallRealMethod(); when(configuration.getName()).thenReturn("EventDispatcherTestController"); when(configService.getMetrics()).thenReturn(Metrics.NOOP); when(configuration.getConfigurationService()).thenReturn(configService); - when(controller.createOrUpdateResource(eq(testCustomResource), any())) - .thenReturn(UpdateControl.updateCustomResource(testCustomResource)); - when(controller.deleteResource(eq(testCustomResource), any())) + when(controller.createOrUpdateResource(eq(customResource), any())) + .thenReturn(UpdateControl.updateCustomResource(customResource)); + when(controller.deleteResource(eq(customResource), any())) .thenReturn(DeleteControl.defaultDelete()); when(customResourceFacade.replaceWithLock(any())).thenReturn(null); + ConfiguredController configuredController = + new ConfiguredController<>(controller, configuration, null); + + return new EventDispatcher<>(configuredController, customResourceFacade); } @Test void addFinalizerOnNewResource() { assertFalse(testCustomResource.hasFinalizer(DEFAULT_FINALIZER)); - eventDispatcher.handleExecution( - executionScopeWithCREvent(testCustomResource)); + eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); verify(controller, never()) - .createOrUpdateResource(ArgumentMatchers.eq(testCustomResource), any()); + .createOrUpdateResource(ArgumentMatchers.eq(testCustomResource), any()); verify(customResourceFacade, times(1)) .replaceWithLock( argThat(testCustomResource -> testCustomResource.hasFinalizer(DEFAULT_FINALIZER))); - assertTrue(testCustomResource.hasFinalizer(DEFAULT_FINALIZER)); + assertThat(testCustomResource.hasFinalizer(DEFAULT_FINALIZER)); } @Test void callCreateOrUpdateOnNewResourceIfFinalizerSet() { testCustomResource.addFinalizer(DEFAULT_FINALIZER); - eventDispatcher.handleExecution( - executionScopeWithCREvent(testCustomResource)); + eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); verify(controller, times(1)) - .createOrUpdateResource(ArgumentMatchers.eq(testCustomResource), any()); + .createOrUpdateResource(ArgumentMatchers.eq(testCustomResource), any()); } @Test @@ -91,8 +99,7 @@ void updatesOnlyStatusSubResourceIfFinalizerSet() { when(controller.createOrUpdateResource(eq(testCustomResource), any())) .thenReturn(UpdateControl.updateStatusSubResource(testCustomResource)); - eventDispatcher.handleExecution( - executionScopeWithCREvent(testCustomResource)); + eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); verify(customResourceFacade, times(1)).updateStatus(testCustomResource); verify(customResourceFacade, never()).replaceWithLock(any()); @@ -106,8 +113,7 @@ void updatesBothResourceAndStatusIfFinalizerSet() { .thenReturn(UpdateControl.updateCustomResourceAndStatus(testCustomResource)); when(customResourceFacade.replaceWithLock(testCustomResource)).thenReturn(testCustomResource); - eventDispatcher.handleExecution( - executionScopeWithCREvent(testCustomResource)); + eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); verify(customResourceFacade, times(1)).replaceWithLock(testCustomResource); verify(customResourceFacade, times(1)).updateStatus(testCustomResource); @@ -117,10 +123,9 @@ void updatesBothResourceAndStatusIfFinalizerSet() { void callCreateOrUpdateOnModifiedResourceIfFinalizerSet() { testCustomResource.addFinalizer(DEFAULT_FINALIZER); - eventDispatcher.handleExecution( - executionScopeWithCREvent(testCustomResource)); + eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); verify(controller, times(1)) - .createOrUpdateResource(ArgumentMatchers.eq(testCustomResource), any()); + .createOrUpdateResource(ArgumentMatchers.eq(testCustomResource), any()); } @Test @@ -129,20 +134,20 @@ void callsDeleteIfObjectHasFinalizerAndMarkedForDelete() { assertTrue(testCustomResource.addFinalizer(DEFAULT_FINALIZER)); markForDeletion(testCustomResource); - eventDispatcher.handleExecution( - executionScopeWithCREvent(testCustomResource)); + eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); verify(controller, times(1)).deleteResource(eq(testCustomResource), any()); } - /** Note that there could be more finalizers. Out of our control. */ + /** + * Note that there could be more finalizers. Out of our control. + */ @Test void callDeleteOnControllerIfMarkedForDeletionWhenNoFinalizerIsConfigured() { configureToNotUseFinalizer(); markForDeletion(testCustomResource); - eventDispatcher.handleExecution( - executionScopeWithCREvent(testCustomResource)); + eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); verify(controller).deleteResource(eq(testCustomResource), any()); } @@ -151,29 +156,27 @@ void callDeleteOnControllerIfMarkedForDeletionWhenNoFinalizerIsConfigured() { void doNotCallDeleteIfMarkedForDeletionWhenFinalizerHasAlreadyBeenRemoved() { markForDeletion(testCustomResource); - eventDispatcher.handleExecution( - executionScopeWithCREvent(testCustomResource)); + eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); verify(controller, never()).deleteResource(eq(testCustomResource), any()); } private void configureToNotUseFinalizer() { ControllerConfiguration> configuration = - mock(ControllerConfiguration.class); + mock(ControllerConfiguration.class); when(configuration.getName()).thenReturn("EventDispatcherTestController"); when(configService.getMetrics()).thenReturn(Metrics.NOOP); when(configuration.getConfigurationService()).thenReturn(configService); when(configuration.useFinalizer()).thenReturn(false); eventDispatcher = new EventDispatcher(new ConfiguredController(controller, configuration, null), - customResourceFacade); + customResourceFacade); } @Test void doesNotAddFinalizerIfConfiguredNotTo() { configureToNotUseFinalizer(); - eventDispatcher.handleExecution( - executionScopeWithCREvent(testCustomResource)); + eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); assertEquals(0, testCustomResource.getMetadata().getFinalizers().size()); } @@ -183,8 +186,7 @@ void removesDefaultFinalizerOnDeleteIfSet() { testCustomResource.addFinalizer(DEFAULT_FINALIZER); markForDeletion(testCustomResource); - eventDispatcher.handleExecution( - executionScopeWithCREvent(testCustomResource)); + eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); assertEquals(0, testCustomResource.getMetadata().getFinalizers().size()); verify(customResourceFacade, times(1)).replaceWithLock(any()); @@ -198,8 +200,7 @@ void doesNotRemovesTheSetFinalizerIfTheDeleteNotMethodInstructsIt() { .thenReturn(DeleteControl.noFinalizerRemoval()); markForDeletion(testCustomResource); - eventDispatcher.handleExecution( - executionScopeWithCREvent(testCustomResource)); + eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); assertEquals(1, testCustomResource.getMetadata().getFinalizers().size()); verify(customResourceFacade, never()).replaceWithLock(any()); @@ -212,8 +213,7 @@ void doesNotUpdateTheResourceIfNoUpdateUpdateControlIfFinalizerSet() { when(controller.createOrUpdateResource(eq(testCustomResource), any())) .thenReturn(UpdateControl.noUpdate()); - eventDispatcher.handleExecution( - executionScopeWithCREvent(testCustomResource)); + eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); verify(customResourceFacade, never()).replaceWithLock(any()); verify(customResourceFacade, never()).updateStatus(testCustomResource); } @@ -224,8 +224,7 @@ void addsFinalizerIfNotMarkedForDeletionAndEmptyCustomResourceReturned() { when(controller.createOrUpdateResource(eq(testCustomResource), any())) .thenReturn(UpdateControl.noUpdate()); - eventDispatcher.handleExecution( - executionScopeWithCREvent(testCustomResource)); + eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); assertEquals(1, testCustomResource.getMetadata().getFinalizers().size()); verify(customResourceFacade, times(1)).replaceWithLock(any()); @@ -236,8 +235,7 @@ void doesNotCallDeleteIfMarkedForDeletionButNotOurFinalizer() { removeFinalizers(testCustomResource); markForDeletion(testCustomResource); - eventDispatcher.handleExecution( - executionScopeWithCREvent(testCustomResource)); + eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); verify(customResourceFacade, never()).replaceWithLock(any()); verify(controller, never()).deleteResource(eq(testCustomResource), any()); @@ -246,10 +244,8 @@ void doesNotCallDeleteIfMarkedForDeletionButNotOurFinalizer() { @Test void executeControllerRegardlessGenerationInNonGenerationAwareModeIfFinalizerSet() { testCustomResource.addFinalizer(DEFAULT_FINALIZER); - eventDispatcher.handleExecution( - executionScopeWithCREvent(testCustomResource)); - eventDispatcher.handleExecution( - executionScopeWithCREvent(testCustomResource)); + eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); + eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); verify(controller, times(2)).createOrUpdateResource(eq(testCustomResource), any()); } @@ -274,7 +270,7 @@ public boolean isLastAttempt() { })); ArgumentCaptor contextArgumentCaptor = - ArgumentCaptor.forClass(Context.class); + ArgumentCaptor.forClass(Context.class); verify(controller, times(1)) .createOrUpdateResource(eq(testCustomResource), contextArgumentCaptor.capture()); Context context = contextArgumentCaptor.getValue(); @@ -291,8 +287,8 @@ void setReScheduleToPostExecutionControlFromUpdateControl() { .thenReturn( UpdateControl.updateStatusSubResource(testCustomResource).rescheduleAfter(1000L)); - PostExecutionControl control = eventDispatcher.handleExecution( - executionScopeWithCREvent(testCustomResource)); + PostExecutionControl control = + eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); assertThat(control.getReScheduleDelay().get()).isEqualTo(1000L); } @@ -303,11 +299,10 @@ void reScheduleOnDeleteWithoutFinalizerRemoval() { markForDeletion(testCustomResource); when(controller.deleteResource(eq(testCustomResource), any())) - .thenReturn( - DeleteControl.noFinalizerRemoval().rescheduleAfter(1000L)); + .thenReturn(DeleteControl.noFinalizerRemoval().rescheduleAfter(1000L)); PostExecutionControl control = - eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); + eventDispatcher.handleExecution(executionScopeWithCREvent(testCustomResource)); assertThat(control.getReScheduleDelay().get()).isEqualTo(1000L); } @@ -316,15 +311,19 @@ void reScheduleOnDeleteWithoutFinalizerRemoval() { void setObservedGenerationForStatusIfNeeded() { var observedGenResource = createObservedGenCustomResource(); - when(configuration.isGenerationAware()).thenReturn(true); - when(controller.createOrUpdateResource(eq(observedGenResource), any())) - .thenReturn( - UpdateControl.updateStatusSubResource(observedGenResource)); + ResourceController lController = mock(ResourceController.class); + ControllerConfiguration lConfiguration = + mock(ControllerConfiguration.class); + CustomResourceFacade lFacade = mock(CustomResourceFacade.class); + var lDispatcher = init(observedGenResource, lController, lConfiguration, lFacade); - when(customResourceFacade.updateStatus(observedGenResource)).thenReturn(observedGenResource); + when(lConfiguration.isGenerationAware()).thenReturn(true); + when(lController.createOrUpdateResource(eq(observedGenResource), any())) + .thenReturn(UpdateControl.updateStatusSubResource(observedGenResource)); + when(lFacade.updateStatus(observedGenResource)).thenReturn(observedGenResource); - PostExecutionControl control = eventDispatcher.handleExecution( - executionScopeWithCREvent(ADDED, observedGenResource)); + PostExecutionControl control = lDispatcher.handleExecution( + executionScopeWithCREvent(observedGenResource)); assertThat(control.getUpdatedCustomResource().get().getStatus().getObservedGeneration().get()) .isEqualTo(1L); } diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceSelectorTest.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceSelectorTest.java index 0600a2ddcb..7fcda72bb4 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceSelectorTest.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/processing/event/internal/CustomResourceSelectorTest.java @@ -1,5 +1,21 @@ package io.javaoperatorsdk.operator.processing.event.internal; +import java.text.ParseException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; + +import org.awaitility.core.ConditionTimeoutException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.internal.util.collections.Sets; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.VersionInfo; @@ -14,21 +30,6 @@ import io.javaoperatorsdk.operator.api.config.ControllerConfiguration; import io.javaoperatorsdk.operator.api.config.Version; import io.javaoperatorsdk.operator.sample.simple.TestCustomResource; -import org.awaitility.core.ConditionTimeoutException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.internal.util.collections.Sets; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.text.ParseException; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Date; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Consumer; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; @@ -186,7 +187,7 @@ public MyController(Consumer consumer) { @Override public UpdateControl createOrUpdateResource( - TestCustomResource resource, Context context) { + TestCustomResource resource, Context context) { LOGGER.info("Received event on: {}", resource); diff --git a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceController.java b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceController.java index 80e0a04d87..eba0859a9c 100644 --- a/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceController.java +++ b/operator-framework-core/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceController.java @@ -1,5 +1,11 @@ package io.javaoperatorsdk.operator.sample.simple; +import java.util.HashMap; +import java.util.Map; + +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.ObjectMetaBuilder; @@ -10,11 +16,6 @@ import io.javaoperatorsdk.operator.api.DeleteControl; import io.javaoperatorsdk.operator.api.ResourceController; import io.javaoperatorsdk.operator.api.UpdateControl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashMap; -import java.util.Map; @Controller(generationAwareEventProcessing = false) public class TestCustomResourceController implements ResourceController { @@ -38,17 +39,17 @@ public TestCustomResourceController(KubernetesClient kubernetesClient, boolean u @Override public DeleteControl deleteResource( - TestCustomResource resource, Context context) { + TestCustomResource resource, Context context) { Boolean delete = - kubernetesClient - .configMaps() - .inNamespace(resource.getMetadata().getNamespace()) - .withName(resource.getSpec().getConfigMapName()) - .delete(); + kubernetesClient + .configMaps() + .inNamespace(resource.getMetadata().getNamespace()) + .withName(resource.getSpec().getConfigMapName()) + .delete(); if (delete) { log.info( - "Deleted ConfigMap {} for resource: {}", - resource.getSpec().getConfigMapName(), + "Deleted ConfigMap {} for resource: {}", + resource.getSpec().getConfigMapName(), resource.getMetadata().getName()); } else { log.error( @@ -61,17 +62,17 @@ public DeleteControl deleteResource( @Override public UpdateControl createOrUpdateResource( - TestCustomResource resource, Context context) { + TestCustomResource resource, Context context) { if (!resource.getMetadata().getFinalizers().contains(FINALIZER_NAME)) { throw new IllegalStateException("Finalizer is not present."); } ConfigMap existingConfigMap = - kubernetesClient - .configMaps() - .inNamespace(resource.getMetadata().getNamespace()) - .withName(resource.getSpec().getConfigMapName()) - .get(); + kubernetesClient + .configMaps() + .inNamespace(resource.getMetadata().getNamespace()) + .withName(resource.getSpec().getConfigMapName()) + .get(); if (existingConfigMap != null) { existingConfigMap.setData(configMapData(resource)); diff --git a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/AnnotationConfiguration.java b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/AnnotationConfiguration.java index c6de06dc2a..34ca56378f 100644 --- a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/AnnotationConfiguration.java +++ b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/AnnotationConfiguration.java @@ -1,5 +1,8 @@ package io.javaoperatorsdk.operator.config.runtime; +import java.util.Set; +import java.util.function.Function; + import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.ControllerUtils; import io.javaoperatorsdk.operator.api.Controller; @@ -9,11 +12,8 @@ import io.javaoperatorsdk.operator.processing.event.internal.CustomResourceEventFilter; import io.javaoperatorsdk.operator.processing.event.internal.CustomResourceEventFilters; -import java.util.Set; -import java.util.function.Function; - public class AnnotationConfiguration> - implements ControllerConfiguration { + implements ControllerConfiguration { private final ResourceController controller; private final Controller annotation; diff --git a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/ClassMappingProvider.java b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/ClassMappingProvider.java index 788bf28f09..a0fadbb8cb 100644 --- a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/ClassMappingProvider.java +++ b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/ClassMappingProvider.java @@ -1,9 +1,5 @@ package io.javaoperatorsdk.operator.config.runtime; -import org.apache.commons.lang3.ClassUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -15,6 +11,10 @@ import java.util.Map; import java.util.stream.Collectors; +import org.apache.commons.lang3.ClassUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + class ClassMappingProvider { private static final Logger log = LoggerFactory.getLogger(ClassMappingProvider.class); @@ -30,22 +30,22 @@ static Map provide(final String resourcePath, T key, V value) { List classNamePairs = retrieveClassNamePairs(url); classNamePairs.forEach( - clazzPair -> { - try { - final String[] classNames = clazzPair.split(","); - if (classNames.length != 2) { - throw new IllegalStateException( - String.format( - "%s is not valid Mapping metadata, defined in %s", - clazzPair, url)); - } - - result.put( - (T) ClassUtils.getClass(classNames[0]), (V) ClassUtils.getClass(classNames[1])); - } catch (ClassNotFoundException e) { - throw new RuntimeException(e); - } - }); + clazzPair -> { + try { + final String[] classNames = clazzPair.split(","); + if (classNames.length != 2) { + throw new IllegalStateException( + String.format( + "%s is not valid Mapping metadata, defined in %s", + clazzPair, url)); + } + + result.put( + (T) ClassUtils.getClass(classNames[0]), (V) ClassUtils.getClass(classNames[1])); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + }); } log.debug("Loaded Controller to CustomResource mappings {}", result); return result; 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 982ac9bb9b..60e65a06f4 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 @@ -20,21 +20,21 @@ public static DefaultConfigurationService instance() { @Override public > ControllerConfiguration getConfigurationFor( - ResourceController controller) { - return getConfigurationFor(controller, true); + ResourceController controller) { + return getConfigurationFor(controller, true); } - > ControllerConfiguration getConfigurationFor( - ResourceController controller, boolean createIfNeeded) { - var config = super.getConfigurationFor(controller); - if (config == null) { - if (createIfNeeded) { - // create the configuration on demand and register it - config = new AnnotationConfiguration<>(controller); - register(config); - getLogger().info( - "Created configuration for controller {} with name {}", - controller.getClass().getName(), + > ControllerConfiguration getConfigurationFor( + ResourceController controller, boolean createIfNeeded) { + var config = super.getConfigurationFor(controller); + if (config == null) { + if (createIfNeeded) { + // create the configuration on demand and register it + config = new AnnotationConfiguration<>(controller); + register(config); + getLogger().info( + "Created configuration for controller {} with name {}", + controller.getClass().getName(), config.getName()); } } else { diff --git a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/RuntimeControllerMetadata.java b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/RuntimeControllerMetadata.java index 446ea85260..1536d681f3 100644 --- a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/RuntimeControllerMetadata.java +++ b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/RuntimeControllerMetadata.java @@ -1,10 +1,10 @@ package io.javaoperatorsdk.operator.config.runtime; +import java.util.Map; + import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.api.ResourceController; -import java.util.Map; - @SuppressWarnings("rawtypes") public class RuntimeControllerMetadata { @@ -13,19 +13,19 @@ public class RuntimeControllerMetadata { static { controllerToCustomResourceMappings = - ClassMappingProvider.provide( - CONTROLLERS_RESOURCE_PATH, ResourceController.class, CustomResource.class); + ClassMappingProvider.provide( + CONTROLLERS_RESOURCE_PATH, ResourceController.class, CustomResource.class); } static > Class getCustomResourceClass( - ResourceController controller) { + ResourceController controller) { final Class customResourceClass = - controllerToCustomResourceMappings.get(controller.getClass()); + controllerToCustomResourceMappings.get(controller.getClass()); if (customResourceClass == null) { throw new IllegalArgumentException( - String.format( - "No custom resource has been found for controller %s", - controller.getClass().getCanonicalName())); + String.format( + "No custom resource has been found for controller %s", + controller.getClass().getCanonicalName())); } return (Class) customResourceClass; } diff --git a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/TypeParameterResolver.java b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/TypeParameterResolver.java index bc9b3a0679..82f46dcdf6 100644 --- a/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/TypeParameterResolver.java +++ b/operator-framework/src/main/java/io/javaoperatorsdk/operator/config/runtime/TypeParameterResolver.java @@ -1,5 +1,10 @@ package io.javaoperatorsdk.operator.config.runtime; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.type.DeclaredType; @@ -7,10 +12,6 @@ import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; import javax.lang.model.util.Types; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.IntStream; import static javax.lang.model.type.TypeKind.DECLARED; import static javax.lang.model.type.TypeKind.TYPEVAR; @@ -74,9 +75,9 @@ public TypeMirror resolve(Types typeUtils, DeclaredType declaredType) { private int getTypeIndexWithName( String typeName, List typeParameters) { return IntStream.range(0, typeParameters.size()) - .filter(i -> typeParameters.get(i).getSimpleName().toString().equals(typeName)) - .findFirst() - .orElseThrow(); + .filter(i -> typeParameters.get(i).getSimpleName().toString().equals(typeName)) + .findFirst() + .orElseThrow(); } private List findChain(Types typeUtils, DeclaredType declaredType) { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/runtime/DefaultConfigurationServiceTest.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/runtime/DefaultConfigurationServiceTest.java index 52fa097920..64623470ae 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/runtime/DefaultConfigurationServiceTest.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/config/runtime/DefaultConfigurationServiceTest.java @@ -1,5 +1,13 @@ package io.javaoperatorsdk.operator.config.runtime; +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.config.AppenderRef; +import org.apache.logging.log4j.core.config.LoggerConfig; +import org.apache.logging.log4j.core.layout.PatternLayout; +import org.apache.logging.log4j.test.appender.ListAppender; +import org.junit.jupiter.api.Test; + import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.model.annotation.Group; import io.fabric8.kubernetes.model.annotation.Version; @@ -8,13 +16,6 @@ import io.javaoperatorsdk.operator.api.Controller; import io.javaoperatorsdk.operator.api.ResourceController; import io.javaoperatorsdk.operator.api.UpdateControl; -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.config.AppenderRef; -import org.apache.logging.log4j.core.config.LoggerConfig; -import org.apache.logging.log4j.core.layout.PatternLayout; -import org.apache.logging.log4j.test.appender.ListAppender; -import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @@ -109,7 +110,7 @@ static class TestCustomFinalizerController @Override public UpdateControl createOrUpdateResource( - InnerCustomResource resource, Context context) { + InnerCustomResource resource, Context context) { return null; } @@ -126,7 +127,7 @@ static class NotAutomaticallyCreated implements ResourceController createOrUpdateResource( - TestCustomResource resource, Context context) { + TestCustomResource resource, Context context) { return null; } } @@ -136,7 +137,7 @@ static class TestCustomResourceController implements ResourceController createOrUpdateResource( - TestCustomResource resource, Context context) { + TestCustomResource resource, Context context) { return null; } } diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomResourceController.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomResourceController.java index 84f21f6742..df9f3dcf10 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomResourceController.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/doubleupdate/DoubleUpdateTestCustomResourceController.java @@ -1,14 +1,16 @@ package io.javaoperatorsdk.operator.sample.doubleupdate; +import java.util.HashMap; +import java.util.concurrent.atomic.AtomicInteger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.javaoperatorsdk.operator.api.Context; import io.javaoperatorsdk.operator.api.Controller; import io.javaoperatorsdk.operator.api.ResourceController; import io.javaoperatorsdk.operator.api.UpdateControl; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashMap; -import java.util.concurrent.atomic.AtomicInteger; @Controller public class DoubleUpdateTestCustomResourceController @@ -22,7 +24,7 @@ public class DoubleUpdateTestCustomResourceController @Override public UpdateControl createOrUpdateResource( - DoubleUpdateTestCustomResource resource, Context context) { + DoubleUpdateTestCustomResource resource, Context context) { numberOfExecutions.addAndGet(1); log.info("Value: " + resource.getSpec().getValue()); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomResourceController.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomResourceController.java index cfb55ef751..cecf713f3c 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomResourceController.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/event/EventSourceTestCustomResourceController.java @@ -1,7 +1,13 @@ package io.javaoperatorsdk.operator.sample.event; +import java.util.concurrent.atomic.AtomicInteger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.ControllerUtils; +import io.javaoperatorsdk.operator.api.Context; import io.javaoperatorsdk.operator.api.Controller; import io.javaoperatorsdk.operator.api.EventSourceInitializer; import io.javaoperatorsdk.operator.api.ResourceController; @@ -9,10 +15,6 @@ import io.javaoperatorsdk.operator.processing.event.EventSourceManager; import io.javaoperatorsdk.operator.processing.event.internal.TimerEventSource; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.concurrent.atomic.AtomicInteger; @Controller public class EventSourceTestCustomResourceController @@ -37,7 +39,7 @@ public void prepareEventSources(EventSourceManager eventSourceManager) { @Override public UpdateControl createOrUpdateResource( - EventSourceTestCustomResource resource, Context context) { + EventSourceTestCustomResource resource, Context context) { timerEventSource.schedule(resource, TIMER_DELAY, TIMER_PERIOD); diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informereventsource/InformerEventSourceTestCustomResourceController.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informereventsource/InformerEventSourceTestCustomResourceController.java index 0f5a820081..ad2a2dc863 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informereventsource/InformerEventSourceTestCustomResourceController.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/informereventsource/InformerEventSourceTestCustomResourceController.java @@ -1,7 +1,11 @@ package io.javaoperatorsdk.operator.sample.informereventsource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import io.fabric8.kubernetes.api.model.ConfigMap; import io.fabric8.kubernetes.client.KubernetesClient; +import io.javaoperatorsdk.operator.api.Context; import io.javaoperatorsdk.operator.api.Controller; import io.javaoperatorsdk.operator.api.EventSourceInitializer; import io.javaoperatorsdk.operator.api.ResourceController; @@ -10,8 +14,6 @@ import io.javaoperatorsdk.operator.processing.event.EventSourceManager; import io.javaoperatorsdk.operator.processing.event.internal.InformerEventSource; import io.javaoperatorsdk.operator.processing.event.internal.Mappers; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import static io.javaoperatorsdk.operator.api.Controller.NO_FINALIZER; @@ -42,8 +44,8 @@ public void prepareEventSources(EventSourceManager eventSourceManager) { @Override public UpdateControl createOrUpdateResource( - InformerEventSourceTestCustomResource resource, - Context context) { + InformerEventSourceTestCustomResource resource, + Context context) { // Reading the config map from the informer not from the API // name of the config map same as custom resource for sake of simplicity diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomResourceController.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomResourceController.java index e31100597b..cf24ee9484 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomResourceController.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/retry/RetryTestCustomResourceController.java @@ -1,5 +1,10 @@ package io.javaoperatorsdk.operator.sample.retry; +import java.util.concurrent.atomic.AtomicInteger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.ControllerUtils; import io.javaoperatorsdk.operator.api.Context; @@ -7,10 +12,6 @@ import io.javaoperatorsdk.operator.api.ResourceController; import io.javaoperatorsdk.operator.api.UpdateControl; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.concurrent.atomic.AtomicInteger; @Controller public class RetryTestCustomResourceController @@ -27,7 +28,7 @@ public class RetryTestCustomResourceController @Override public UpdateControl createOrUpdateResource( - RetryTestCustomResource resource, Context context) { + RetryTestCustomResource resource, Context context) { numberOfExecutions.addAndGet(1); if (!resource.getMetadata().getFinalizers().contains(FINALIZER_NAME)) { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceController.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceController.java index cd9670f6ec..6aefaa3922 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceController.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/simple/TestCustomResourceController.java @@ -1,5 +1,12 @@ package io.javaoperatorsdk.operator.sample.simple; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +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.ObjectMetaBuilder; @@ -13,12 +20,6 @@ import io.javaoperatorsdk.operator.api.UpdateControl; import io.javaoperatorsdk.operator.junit.KubernetesClientAware; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; @Controller(generationAwareEventProcessing = false) public class TestCustomResourceController @@ -62,17 +63,17 @@ public void setKubernetesClient(KubernetesClient kubernetesClient) { @Override public DeleteControl deleteResource( - TestCustomResource resource, Context context) { + TestCustomResource resource, Context context) { Boolean delete = - kubernetesClient - .configMaps() - .inNamespace(resource.getMetadata().getNamespace()) - .withName(resource.getSpec().getConfigMapName()) - .delete(); + kubernetesClient + .configMaps() + .inNamespace(resource.getMetadata().getNamespace()) + .withName(resource.getSpec().getConfigMapName()) + .delete(); if (delete) { log.info( - "Deleted ConfigMap {} for resource: {}", - resource.getSpec().getConfigMapName(), + "Deleted ConfigMap {} for resource: {}", + resource.getSpec().getConfigMapName(), resource.getMetadata().getName()); } else { log.error( @@ -85,17 +86,17 @@ public DeleteControl deleteResource( @Override public UpdateControl createOrUpdateResource( - TestCustomResource resource, Context context) { + TestCustomResource resource, Context context) { numberOfExecutions.addAndGet(1); if (!resource.getMetadata().getFinalizers().contains(FINALIZER_NAME)) { throw new IllegalStateException("Finalizer is not present."); } ConfigMap existingConfigMap = - kubernetesClient - .configMaps() - .inNamespace(resource.getMetadata().getNamespace()) - .withName(resource.getSpec().getConfigMapName()) + kubernetesClient + .configMaps() + .inNamespace(resource.getMetadata().getNamespace()) + .withName(resource.getSpec().getConfigMapName()) .get(); if (existingConfigMap != null) { diff --git a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomResourceController.java b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomResourceController.java index 845bd6ef21..f04958cbcd 100644 --- a/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomResourceController.java +++ b/operator-framework/src/test/java/io/javaoperatorsdk/operator/sample/subresource/SubResourceTestCustomResourceController.java @@ -1,5 +1,10 @@ package io.javaoperatorsdk.operator.sample.subresource; +import java.util.concurrent.atomic.AtomicInteger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import io.fabric8.kubernetes.client.CustomResource; import io.javaoperatorsdk.operator.ControllerUtils; import io.javaoperatorsdk.operator.api.Context; @@ -7,10 +12,6 @@ import io.javaoperatorsdk.operator.api.ResourceController; import io.javaoperatorsdk.operator.api.UpdateControl; import io.javaoperatorsdk.operator.support.TestExecutionInfoProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.concurrent.atomic.AtomicInteger; @Controller(generationAwareEventProcessing = false) public class SubResourceTestCustomResourceController @@ -25,7 +26,7 @@ public class SubResourceTestCustomResourceController @Override public UpdateControl createOrUpdateResource( - SubResourceTestCustomResource resource, Context context) { + SubResourceTestCustomResource resource, Context context) { numberOfExecutions.addAndGet(1); if (!resource.getMetadata().getFinalizers().contains(FINALIZER_NAME)) { throw new IllegalStateException("Finalizer is not present."); diff --git a/samples/common/src/main/java/io/javaoperatorsdk/operator/sample/CustomServiceController.java b/samples/common/src/main/java/io/javaoperatorsdk/operator/sample/CustomServiceController.java index 8ed1eb854a..932fd1bc1b 100644 --- a/samples/common/src/main/java/io/javaoperatorsdk/operator/sample/CustomServiceController.java +++ b/samples/common/src/main/java/io/javaoperatorsdk/operator/sample/CustomServiceController.java @@ -1,5 +1,10 @@ package io.javaoperatorsdk.operator.sample; +import java.util.Collections; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import io.fabric8.kubernetes.api.model.ServiceBuilder; import io.fabric8.kubernetes.api.model.ServicePort; import io.fabric8.kubernetes.api.model.ServiceSpec; @@ -10,10 +15,6 @@ import io.javaoperatorsdk.operator.api.DeleteControl; import io.javaoperatorsdk.operator.api.ResourceController; import io.javaoperatorsdk.operator.api.UpdateControl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Collections; /** A very simple sample controller that creates a service with a label. */ @Controller @@ -32,25 +33,25 @@ public CustomServiceController(KubernetesClient kubernetesClient) { this.kubernetesClient = kubernetesClient; } - @Override - public DeleteControl deleteResource(CustomService resource, Context context) { - log.info("Execution deleteResource for: {}", resource.getMetadata().getName()); - return DeleteControl.defaultDelete(); - } + @Override + public DeleteControl deleteResource(CustomService resource, Context context) { + log.info("Execution deleteResource for: {}", resource.getMetadata().getName()); + return DeleteControl.defaultDelete(); + } - @Override - public UpdateControl createOrUpdateResource( - CustomService resource, Context context) { - log.info("Execution createOrUpdateResource for: {}", resource.getMetadata().getName()); + @Override + public UpdateControl createOrUpdateResource( + CustomService resource, Context context) { + log.info("Execution createOrUpdateResource for: {}", resource.getMetadata().getName()); - ServicePort servicePort = new ServicePort(); - servicePort.setPort(8080); - ServiceSpec serviceSpec = new ServiceSpec(); - serviceSpec.setPorts(Collections.singletonList(servicePort)); + ServicePort servicePort = new ServicePort(); + servicePort.setPort(8080); + ServiceSpec serviceSpec = new ServiceSpec(); + serviceSpec.setPorts(Collections.singletonList(servicePort)); - kubernetesClient - .services() - .inNamespace(resource.getMetadata().getNamespace()) + kubernetesClient + .services() + .inNamespace(resource.getMetadata().getNamespace()) .createOrReplace( new ServiceBuilder() .withNewMetadata()