|
| 1 | +/* |
| 2 | + * Copyright Kroxylicious Authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +package io.kroxylicious.kubernetes.operator; |
| 8 | + |
| 9 | +import java.time.Clock; |
| 10 | +import java.time.ZoneId; |
| 11 | +import java.time.ZonedDateTime; |
| 12 | +import java.util.List; |
| 13 | +import java.util.Objects; |
| 14 | +import java.util.Optional; |
| 15 | +import java.util.Set; |
| 16 | +import java.util.TreeSet; |
| 17 | +import java.util.function.Function; |
| 18 | +import java.util.stream.Collectors; |
| 19 | +import java.util.stream.Stream; |
| 20 | + |
| 21 | +import org.slf4j.Logger; |
| 22 | +import org.slf4j.LoggerFactory; |
| 23 | + |
| 24 | +import io.fabric8.kubernetes.api.model.ConfigMap; |
| 25 | +import io.fabric8.kubernetes.api.model.ConfigMapVolumeSource; |
| 26 | +import io.fabric8.kubernetes.api.model.HasMetadata; |
| 27 | +import io.fabric8.kubernetes.api.model.Secret; |
| 28 | +import io.fabric8.kubernetes.api.model.SecretVolumeSource; |
| 29 | +import io.javaoperatorsdk.operator.api.config.informer.InformerEventSourceConfiguration; |
| 30 | +import io.javaoperatorsdk.operator.api.reconciler.Context; |
| 31 | +import io.javaoperatorsdk.operator.api.reconciler.ErrorStatusUpdateControl; |
| 32 | +import io.javaoperatorsdk.operator.api.reconciler.EventSourceContext; |
| 33 | +import io.javaoperatorsdk.operator.api.reconciler.Reconciler; |
| 34 | +import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; |
| 35 | +import io.javaoperatorsdk.operator.processing.event.ResourceID; |
| 36 | +import io.javaoperatorsdk.operator.processing.event.source.EventSource; |
| 37 | +import io.javaoperatorsdk.operator.processing.event.source.informer.InformerEventSource; |
| 38 | + |
| 39 | +import io.kroxylicious.kubernetes.api.common.Condition; |
| 40 | +import io.kroxylicious.kubernetes.api.common.ConditionBuilder; |
| 41 | +import io.kroxylicious.kubernetes.filter.api.v1alpha1.KafkaProtocolFilter; |
| 42 | +import io.kroxylicious.kubernetes.filter.api.v1alpha1.KafkaProtocolFilterBuilder; |
| 43 | + |
| 44 | +import edu.umd.cs.findbugs.annotations.NonNull; |
| 45 | + |
| 46 | +/** |
| 47 | + * Reconciles a {@link KafkaProtocolFilter} by checking whether the {@link Secret}s |
| 48 | + * and {@link ConfigMap}s refered to in interpolated expressions actually exist, setting a |
| 49 | + * {@link Condition.Type#ResolvedRefs} {@link Condition} accordingly. |
| 50 | + */ |
| 51 | +public class KafkaProtocolFilterReconciler implements |
| 52 | + Reconciler<KafkaProtocolFilter> { |
| 53 | + |
| 54 | + private static final Logger LOGGER = LoggerFactory.getLogger(KafkaProtocolFilterReconciler.class); |
| 55 | + private final Clock clock; |
| 56 | + private final SecureConfigInterpolator secureConfigInterpolator; |
| 57 | + |
| 58 | + KafkaProtocolFilterReconciler(Clock clock, SecureConfigInterpolator secureConfigInterpolator) { |
| 59 | + this.clock = Objects.requireNonNull(clock); |
| 60 | + this.secureConfigInterpolator = Objects.requireNonNull(secureConfigInterpolator); |
| 61 | + } |
| 62 | + |
| 63 | + @Override |
| 64 | + public List<EventSource<?, KafkaProtocolFilter>> prepareEventSources(EventSourceContext<KafkaProtocolFilter> context) { |
| 65 | + return List.of( |
| 66 | + new InformerEventSource<>(templateResourceReferenceEventSourceConfig(context, Secret.class, |
| 67 | + interpolationResult -> interpolationResult.volumes().stream() |
| 68 | + .flatMap(volume -> Optional.ofNullable(volume.getSecret()) |
| 69 | + .map(SecretVolumeSource::getSecretName) |
| 70 | + .stream())), |
| 71 | + context), |
| 72 | + new InformerEventSource<>(templateResourceReferenceEventSourceConfig(context, ConfigMap.class, |
| 73 | + interpolationResult -> interpolationResult.volumes().stream() |
| 74 | + .flatMap(volume -> Optional.ofNullable(volume.getConfigMap()) |
| 75 | + .map(ConfigMapVolumeSource::getName) |
| 76 | + .stream())), |
| 77 | + context)); |
| 78 | + } |
| 79 | + |
| 80 | + /** |
| 81 | + * Returns a new event source config for getting the resource dependencies of a given type present in a filter's {@code spec.configTemplate}. |
| 82 | + * @param context The context. |
| 83 | + * @param secondaryClass The Java type of resource reference (e.g. Secret) |
| 84 | + * @param resourceNameExtractor A function which extracts the name of the resources from an interpolation result. |
| 85 | + * @param <R> The type of referenced resource |
| 86 | + * @return The event source configuration |
| 87 | + */ |
| 88 | + private <R extends HasMetadata> InformerEventSourceConfiguration<R> templateResourceReferenceEventSourceConfig( |
| 89 | + EventSourceContext<KafkaProtocolFilter> context, |
| 90 | + Class<R> secondaryClass, |
| 91 | + Function<SecureConfigInterpolator.InterpolationResult, Stream<String>> resourceNameExtractor) { |
| 92 | + return InformerEventSourceConfiguration.from( |
| 93 | + secondaryClass, |
| 94 | + KafkaProtocolFilter.class) |
| 95 | + .withPrimaryToSecondaryMapper((KafkaProtocolFilter filter) -> { |
| 96 | + Object configTemplate = filter.getSpec().getConfigTemplate(); |
| 97 | + var interpolationResult = secureConfigInterpolator.interpolate(configTemplate); |
| 98 | + Set<ResourceID> resourceIds = resourceNameExtractor.apply(interpolationResult) |
| 99 | + .map(name -> new ResourceID(name, ResourcesUtil.namespace(filter))) |
| 100 | + .collect(Collectors.toSet()); |
| 101 | + LOGGER.debug("Filter {} references {}(s) {}", ResourcesUtil.name(filter), secondaryClass.getName(), resourceIds); |
| 102 | + return resourceIds; |
| 103 | + }) |
| 104 | + .withSecondaryToPrimaryMapper(secret -> { |
| 105 | + Set<ResourceID> resourceIds = ResourcesUtil.filteredResourceIdsInSameNamespace( |
| 106 | + context, |
| 107 | + secret, |
| 108 | + KafkaProtocolFilter.class, |
| 109 | + filter -> { |
| 110 | + Object configTemplate = filter.getSpec().getConfigTemplate(); |
| 111 | + var interpolationResult = secureConfigInterpolator.interpolate(configTemplate); |
| 112 | + return resourceNameExtractor.apply(interpolationResult) |
| 113 | + .anyMatch(secretNameFromVolume -> secretNameFromVolume.equals(ResourcesUtil.name(secret))); |
| 114 | + }); |
| 115 | + LOGGER.debug("{} {} referenced by Filters {}", secondaryClass.getName(), ResourcesUtil.name(secret), resourceIds); |
| 116 | + return resourceIds; |
| 117 | + }) |
| 118 | + .build(); |
| 119 | + } |
| 120 | + |
| 121 | + @Override |
| 122 | + public UpdateControl<KafkaProtocolFilter> reconcile( |
| 123 | + KafkaProtocolFilter filter, |
| 124 | + Context<KafkaProtocolFilter> context) { |
| 125 | + |
| 126 | + var now = ZonedDateTime.ofInstant(clock.instant(), ZoneId.of("Z")); |
| 127 | + |
| 128 | + ConditionBuilder conditionBuilder = newResolvedRefsCondition(filter, now); |
| 129 | + |
| 130 | + var existingSecrets = context.getSecondaryResourcesAsStream(Secret.class) |
| 131 | + .map(ResourcesUtil::name) |
| 132 | + .collect(Collectors.toSet()); |
| 133 | + LOGGER.debug("Existing secrets: {}", existingSecrets); |
| 134 | + |
| 135 | + var existingConfigMaps = context.getSecondaryResourcesAsStream(ConfigMap.class) |
| 136 | + .map(ResourcesUtil::name) |
| 137 | + .collect(Collectors.toSet()); |
| 138 | + LOGGER.debug("Existing configmaps: {}", existingConfigMaps); |
| 139 | + |
| 140 | + var interpolationResult = secureConfigInterpolator.interpolate(filter.getSpec().getConfigTemplate()); |
| 141 | + var referencedSecrets = interpolationResult.volumes().stream().flatMap(volume -> Optional.ofNullable(volume.getSecret()) |
| 142 | + .map(SecretVolumeSource::getSecretName) |
| 143 | + .stream()) |
| 144 | + .collect(Collectors.toCollection(TreeSet::new)); |
| 145 | + LOGGER.debug("Referenced secrets: {}", referencedSecrets); |
| 146 | + |
| 147 | + var referencedConfigMaps = interpolationResult.volumes().stream().flatMap(volume -> Optional.ofNullable(volume.getConfigMap()) |
| 148 | + .map(ConfigMapVolumeSource::getName) |
| 149 | + .stream()) |
| 150 | + .collect(Collectors.toCollection(TreeSet::new)); |
| 151 | + LOGGER.debug("Referenced configmaps: {}", referencedConfigMaps); |
| 152 | + |
| 153 | + if (existingSecrets.containsAll(referencedSecrets) |
| 154 | + && existingConfigMaps.containsAll(referencedConfigMaps)) { |
| 155 | + conditionBuilder.withStatus(Condition.Status.TRUE); |
| 156 | + } |
| 157 | + else { |
| 158 | + referencedSecrets.removeAll(existingSecrets); |
| 159 | + referencedConfigMaps.removeAll(existingConfigMaps); |
| 160 | + String message = "Referenced"; |
| 161 | + if (!referencedSecrets.isEmpty()) { |
| 162 | + message += " Secrets [" + String.join(", ", referencedSecrets) + "]"; |
| 163 | + } |
| 164 | + if (!referencedConfigMaps.isEmpty()) { |
| 165 | + message += " ConfigMaps [" + String.join(", ", referencedConfigMaps) + "]"; |
| 166 | + } |
| 167 | + message += " not found"; |
| 168 | + conditionBuilder.withStatus(Condition.Status.FALSE) |
| 169 | + .withReason("MissingInterpolationReferences") |
| 170 | + .withMessage(message); |
| 171 | + } |
| 172 | + |
| 173 | + KafkaProtocolFilter newFilter = newFilterWithCondition(filter, conditionBuilder.build()); |
| 174 | + LOGGER.debug("Patching with status {}", newFilter.getStatus()); |
| 175 | + return UpdateControl.patchStatus(newFilter); |
| 176 | + } |
| 177 | + |
| 178 | + @NonNull |
| 179 | + private static KafkaProtocolFilter newFilterWithCondition(KafkaProtocolFilter filter, Condition condition) { |
| 180 | + // @formatter:off |
| 181 | + return new KafkaProtocolFilterBuilder(filter) |
| 182 | + .withNewStatus() |
| 183 | + .withObservedGeneration(ResourcesUtil.generation(filter)) |
| 184 | + .withConditions(condition) // overwrite any existing conditions |
| 185 | + .endStatus() |
| 186 | + .build(); |
| 187 | + // @formatter:on |
| 188 | + } |
| 189 | + |
| 190 | + private static ConditionBuilder newResolvedRefsCondition(KafkaProtocolFilter filter, ZonedDateTime now) { |
| 191 | + return new ConditionBuilder() |
| 192 | + .withType(Condition.Type.ResolvedRefs) |
| 193 | + .withLastTransitionTime(now) |
| 194 | + .withObservedGeneration(ResourcesUtil.generation(filter)); |
| 195 | + } |
| 196 | + |
| 197 | + @Override |
| 198 | + public ErrorStatusUpdateControl<KafkaProtocolFilter> updateErrorStatus( |
| 199 | + KafkaProtocolFilter filter, |
| 200 | + Context<KafkaProtocolFilter> context, |
| 201 | + Exception e) { |
| 202 | + var now = ZonedDateTime.ofInstant(clock.instant(), ZoneId.of("Z")); |
| 203 | + // ResolvedRefs to UNKNOWN |
| 204 | + Condition condition = newResolvedRefsCondition(filter, now) |
| 205 | + .withStatus(Condition.Status.UNKNOWN) |
| 206 | + .withReason(e.getClass().getName()) |
| 207 | + .withMessage(e.getMessage()) |
| 208 | + .build(); |
| 209 | + return ErrorStatusUpdateControl.patchStatus(newFilterWithCondition(filter, condition)); |
| 210 | + } |
| 211 | +} |
0 commit comments