|
| 1 | +package io.javaoperatorsdk.operator; |
| 2 | + |
| 3 | +import java.util.Collection; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.Map; |
| 6 | +import java.util.Optional; |
| 7 | + |
| 8 | +import org.slf4j.Logger; |
| 9 | +import org.slf4j.LoggerFactory; |
| 10 | + |
| 11 | +import io.javaoperatorsdk.operator.processing.Controller; |
| 12 | +import io.javaoperatorsdk.operator.processing.LifecycleAware; |
| 13 | + |
| 14 | +/** |
| 15 | + * Not confuse with controller manager form go operators. The high level aggregate is Operator in |
| 16 | + * JOSDK. |
| 17 | + */ |
| 18 | +class ControllerManager implements LifecycleAware { |
| 19 | + |
| 20 | + private static final Logger log = LoggerFactory.getLogger(ControllerManager.class); |
| 21 | + |
| 22 | + private final Map<String, Controller> controllers = new HashMap<>(); |
| 23 | + private boolean started = false; |
| 24 | + |
| 25 | + public synchronized void shouldStart() { |
| 26 | + if (started) { |
| 27 | + return; |
| 28 | + } |
| 29 | + if (controllers.isEmpty()) { |
| 30 | + throw new OperatorException("No Controller exists. Exiting!"); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + public synchronized void start() { |
| 35 | + controllers().parallelStream().forEach(Controller::start); |
| 36 | + started = true; |
| 37 | + } |
| 38 | + |
| 39 | + public synchronized void stop() { |
| 40 | + controllers().parallelStream().forEach(closeable -> { |
| 41 | + log.debug("closing {}", closeable); |
| 42 | + closeable.stop(); |
| 43 | + }); |
| 44 | + |
| 45 | + started = false; |
| 46 | + } |
| 47 | + |
| 48 | + @SuppressWarnings("unchecked") |
| 49 | + synchronized void add(Controller controller) { |
| 50 | + final var configuration = controller.getConfiguration(); |
| 51 | + final var resourceTypeName = ReconcilerUtils |
| 52 | + .getResourceTypeNameWithVersion(configuration.getResourceClass()); |
| 53 | + final var existing = controllers.get(resourceTypeName); |
| 54 | + if (existing != null) { |
| 55 | + throw new OperatorException("Cannot register controller '" + configuration.getName() |
| 56 | + + "': another controller named '" + existing.getConfiguration().getName() |
| 57 | + + "' is already registered for resource '" + resourceTypeName + "'"); |
| 58 | + } |
| 59 | + controllers.put(resourceTypeName, controller); |
| 60 | + if (started) { |
| 61 | + controller.start(); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + synchronized Optional<Controller> get(String name) { |
| 66 | + return controllers().stream() |
| 67 | + .filter(c -> name.equals(c.getConfiguration().getName())) |
| 68 | + .findFirst(); |
| 69 | + } |
| 70 | + |
| 71 | + synchronized Collection<Controller> controllers() { |
| 72 | + return controllers.values(); |
| 73 | + } |
| 74 | + |
| 75 | + synchronized int size() { |
| 76 | + return controllers.size(); |
| 77 | + } |
| 78 | +} |
| 79 | + |
0 commit comments