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 9bcd72673d..fa9f1a93bb 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 @@ -12,6 +12,7 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -137,13 +138,39 @@ public void register( controller.init(eventSourceManager); closeables.add(eventSourceManager); + if (failOnMissingCurrentNS(configuration)) { + throw new OperatorException( + "Controller '" + + controllerName + + "' is configured to watch the current namespace but it couldn't be inferred from the current configuration."); + } + + final var watchedNS = + configuration.watchAllNamespaces() + ? "[all namespaces]" + : configuration.getEffectiveNamespaces(); log.info( "Registered Controller: '{}' for CRD: '{}' for namespace(s): {}", controllerName, resClass, - configuration.watchAllNamespaces() - ? "[all namespaces]" - : configuration.getEffectiveNamespaces()); + watchedNS); + } + } + + /** + * Determines whether we should fail because the current namespace is request as target namespace + * but is missing + * + * @return {@code true} if the current namespace is requested but is missing, {@code false} + * otherwise + */ + private static boolean failOnMissingCurrentNS( + ControllerConfiguration configuration) { + if (configuration.watchCurrentNamespace()) { + final var effectiveNamespaces = configuration.getEffectiveNamespaces(); + return effectiveNamespaces.size() == 1 + && effectiveNamespaces.stream().allMatch(Objects::isNull); } + return false; } } 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 b487f2af5f..95555c511d 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 @@ -41,6 +41,13 @@ static boolean currentNamespaceWatched(Set namespaces) { && namespaces.contains(Controller.WATCH_CURRENT_NAMESPACE); } + /** + * Computes the effective namespaces based on the set specified by the user, in particular + * retrieves the current namespace from the client when the user specified that they wanted to + * watch the current namespace only. + * + * @return a Set of namespace names the associated controller will watch + */ default Set getEffectiveNamespaces() { var targetNamespaces = getNamespaces(); if (watchCurrentNamespace()) {