|
| 1 | +/* |
| 2 | + * Copyright Java Operator SDK Authors |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package io.javaoperatorsdk.operator.processing.event.source.informer.pool; |
| 17 | + |
| 18 | +import java.util.HashMap; |
| 19 | +import java.util.Map; |
| 20 | +import java.util.concurrent.ExecutionException; |
| 21 | +import java.util.concurrent.TimeUnit; |
| 22 | +import java.util.concurrent.TimeoutException; |
| 23 | +import java.util.concurrent.atomic.AtomicInteger; |
| 24 | + |
| 25 | +import org.slf4j.Logger; |
| 26 | +import org.slf4j.LoggerFactory; |
| 27 | + |
| 28 | +import io.fabric8.kubernetes.api.model.HasMetadata; |
| 29 | +import io.fabric8.kubernetes.client.KubernetesClient; |
| 30 | +import io.fabric8.kubernetes.client.dsl.FilterWatchListDeletable; |
| 31 | +import io.fabric8.kubernetes.client.informers.ExceptionHandler; |
| 32 | +import io.fabric8.kubernetes.client.informers.SharedIndexInformer; |
| 33 | +import io.javaoperatorsdk.operator.OperatorException; |
| 34 | +import io.javaoperatorsdk.operator.ReconcilerUtilsInternal; |
| 35 | +import io.javaoperatorsdk.operator.api.config.ConfigurationService; |
| 36 | + |
| 37 | +import static io.javaoperatorsdk.operator.api.reconciler.Constants.WATCH_ALL_NAMESPACES; |
| 38 | + |
| 39 | +public class DefaultInformerPool implements InformerPool { |
| 40 | + |
| 41 | + private static final Logger log = LoggerFactory.getLogger(DefaultInformerPool.class); |
| 42 | + |
| 43 | + private final KubernetesClient client; |
| 44 | + private final ConfigurationService configurationService; |
| 45 | + |
| 46 | + private final Map<InformerClassifier, SharedIndexInformer<?>> informers = new HashMap<>(); |
| 47 | + private final Map<SharedIndexInformer<?>, AtomicInteger> counters = new HashMap<>(); |
| 48 | + |
| 49 | + public DefaultInformerPool(KubernetesClient client, ConfigurationService configurationService) { |
| 50 | + this.client = client; |
| 51 | + this.configurationService = configurationService; |
| 52 | + } |
| 53 | + |
| 54 | + public synchronized SharedIndexInformer<?> getResource(InformerClassifier classifier) { |
| 55 | + var informer = informers.get(classifier); |
| 56 | + if (informer == null) { |
| 57 | + informer = createInformer(client, classifier); |
| 58 | + initInformer(informer, classifier.namespaceIdentifier()); |
| 59 | + informers.put(classifier, informer); |
| 60 | + counters.put(informer, new AtomicInteger(1)); |
| 61 | + } else { |
| 62 | + counters.get(informer).incrementAndGet(); |
| 63 | + } |
| 64 | + return informer; |
| 65 | + } |
| 66 | + |
| 67 | + public synchronized void releaseResource(SharedIndexInformer<?> informer) { |
| 68 | + var counter = counters.get(informer); |
| 69 | + if (counter != null && counter.decrementAndGet() <= 0) { |
| 70 | + informer.stop(); |
| 71 | + counters.remove(informer); |
| 72 | + informers.values().remove(informer); |
| 73 | + } else { |
| 74 | + log.warn("No informer found in the pool."); |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + private void initInformer(SharedIndexInformer<?> informer, String namespaceIdentifier) { |
| 79 | + try { |
| 80 | + configurationService |
| 81 | + .getInformerStoppedHandler() |
| 82 | + .ifPresent( |
| 83 | + ish -> { |
| 84 | + final var stopped = informer.stopped(); |
| 85 | + if (stopped != null) { |
| 86 | + stopped.handle( |
| 87 | + (res, ex) -> { |
| 88 | + ish.onStop(informer, ex); |
| 89 | + return null; |
| 90 | + }); |
| 91 | + } else { |
| 92 | + final var apiTypeClass = informer.getApiTypeClass(); |
| 93 | + final var fullResourceName = HasMetadata.getFullResourceName(apiTypeClass); |
| 94 | + final var version = HasMetadata.getVersion(apiTypeClass); |
| 95 | + throw new IllegalStateException( |
| 96 | + "Cannot retrieve 'stopped' callback to listen to informer stopping for" |
| 97 | + + " informer for " |
| 98 | + + fullResourceName |
| 99 | + + "/" |
| 100 | + + version); |
| 101 | + } |
| 102 | + }); |
| 103 | + if (!configurationService.stopOnInformerErrorDuringStartup()) { |
| 104 | + informer.exceptionHandler((b, t) -> !ExceptionHandler.isDeserializationException(t)); |
| 105 | + } |
| 106 | + // change thread name for easier debugging |
| 107 | + final var thread = Thread.currentThread(); |
| 108 | + final var name = thread.getName(); |
| 109 | + try { |
| 110 | + thread.setName( |
| 111 | + "InformerPool [" + versionedFullResourceName(informer) + "] " + thread.getId()); |
| 112 | + final var resourceName = informer.getApiTypeClass().getSimpleName(); |
| 113 | + log.debug( |
| 114 | + "Starting informer for namespace: {} resource: {}", namespaceIdentifier, resourceName); |
| 115 | + var start = informer.start(); |
| 116 | + // note that in case we don't put here timeout and stopOnInformerErrorDuringStartup is |
| 117 | + // false, and there is a rbac issue the get never returns; therefore operator never really |
| 118 | + // starts |
| 119 | + log.trace( |
| 120 | + "Waiting informer to start namespace: {} resource: {}", |
| 121 | + namespaceIdentifier, |
| 122 | + resourceName); |
| 123 | + start |
| 124 | + .toCompletableFuture() |
| 125 | + .get(configurationService.cacheSyncTimeout().toMillis(), TimeUnit.MILLISECONDS); |
| 126 | + log.debug( |
| 127 | + "Started informer for namespace: {} resource: {}", namespaceIdentifier, resourceName); |
| 128 | + } catch (TimeoutException | ExecutionException e) { |
| 129 | + if (configurationService.stopOnInformerErrorDuringStartup()) { |
| 130 | + log.error("Informer startup error. Operator will be stopped. Informer: {}", informer, e); |
| 131 | + throw new OperatorException(e); |
| 132 | + } else { |
| 133 | + log.warn("Informer startup error. Will periodically retry. Informer: {}", informer, e); |
| 134 | + } |
| 135 | + } catch (InterruptedException e) { |
| 136 | + thread.interrupt(); |
| 137 | + throw new IllegalStateException(e); |
| 138 | + } finally { |
| 139 | + // restore original name |
| 140 | + thread.setName(name); |
| 141 | + } |
| 142 | + } catch (Exception e) { |
| 143 | + ReconcilerUtilsInternal.handleKubernetesClientException( |
| 144 | + e, HasMetadata.getFullResourceName(informer.getApiTypeClass())); |
| 145 | + throw new OperatorException( |
| 146 | + "Couldn't start informer for " + versionedFullResourceName(informer) + " resources", e); |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + @SuppressWarnings("unchecked") |
| 151 | + private static String versionedFullResourceName(SharedIndexInformer<?> informer) { |
| 152 | + return ReconcilerUtilsInternal.getResourceTypeNameWithVersion( |
| 153 | + (Class<? extends HasMetadata>) informer.getApiTypeClass()); |
| 154 | + } |
| 155 | + |
| 156 | + @SuppressWarnings("rawtypes") |
| 157 | + static SharedIndexInformer<?> createInformer( |
| 158 | + KubernetesClient client, InformerClassifier classifier) { |
| 159 | + FilterWatchListDeletable filteredClient; |
| 160 | + if (WATCH_ALL_NAMESPACES.equals(classifier.namespaceIdentifier())) { |
| 161 | + filteredClient = |
| 162 | + client |
| 163 | + .resources(classifier.resourceClass()) |
| 164 | + .inAnyNamespace() |
| 165 | + .withLabelSelector(classifier.labelSelector()); |
| 166 | + } else { |
| 167 | + filteredClient = |
| 168 | + client |
| 169 | + .resources(classifier.resourceClass()) |
| 170 | + .inNamespace(classifier.namespaceIdentifier()) |
| 171 | + .withLabelSelector(classifier.labelSelector()); |
| 172 | + } |
| 173 | + |
| 174 | + if (classifier.fieldSelector() != null && !classifier.fieldSelector().getFields().isEmpty()) { |
| 175 | + for (var f : classifier.fieldSelector().getFields()) { |
| 176 | + if (f.negated()) { |
| 177 | + filteredClient = |
| 178 | + (FilterWatchListDeletable) filteredClient.withoutField(f.path(), f.value()); |
| 179 | + } else { |
| 180 | + filteredClient = (FilterWatchListDeletable) filteredClient.withField(f.path(), f.value()); |
| 181 | + } |
| 182 | + } |
| 183 | + } |
| 184 | + return filteredClient.runnableInformer(0); |
| 185 | + } |
| 186 | +} |
0 commit comments