-
Notifications
You must be signed in to change notification settings - Fork 2k
Feat(spring): Adding FromConfigMap annotation that dynamically maps data config-map to map #1594
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
k8s-ci-robot
merged 2 commits into
kubernetes-client:master
from
yue9944882:feat/spring-cfgmap-mapper
Mar 17, 2021
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
164 changes: 164 additions & 0 deletions
164
...java/io/kubernetes/client/spring/extended/manifests/KubernetesFromConfigMapProcessor.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,164 @@ | ||
/* | ||
Copyright 2021 The Kubernetes Authors. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
package io.kubernetes.client.spring.extended.manifests; | ||
|
||
import com.github.benmanes.caffeine.cache.CacheLoader; | ||
import com.github.benmanes.caffeine.cache.Caffeine; | ||
import com.github.benmanes.caffeine.cache.LoadingCache; | ||
import io.kubernetes.client.openapi.models.V1ConfigMap; | ||
import io.kubernetes.client.spring.extended.manifests.annotation.FromConfigMap; | ||
import io.kubernetes.client.spring.extended.manifests.config.KubernetesManifestsProperties; | ||
import io.kubernetes.client.spring.extended.manifests.configmaps.ConfigMapGetter; | ||
import java.lang.reflect.Field; | ||
import java.util.Map; | ||
import java.util.concurrent.Executors; | ||
import java.util.concurrent.ScheduledExecutorService; | ||
import java.util.concurrent.TimeUnit; | ||
import java.util.function.Supplier; | ||
import org.checkerframework.checker.nullness.qual.NonNull; | ||
import org.checkerframework.checker.nullness.qual.Nullable; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
import org.springframework.beans.BeansException; | ||
import org.springframework.beans.factory.BeanCreationException; | ||
import org.springframework.beans.factory.NoSuchBeanDefinitionException; | ||
import org.springframework.beans.factory.annotation.Autowired; | ||
import org.springframework.beans.factory.config.BeanPostProcessor; | ||
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor; | ||
import org.springframework.context.ApplicationContext; | ||
import org.springframework.context.ApplicationContextAware; | ||
import org.springframework.util.ReflectionUtils; | ||
|
||
public class KubernetesFromConfigMapProcessor | ||
implements InstantiationAwareBeanPostProcessor, BeanPostProcessor, ApplicationContextAware { | ||
|
||
private static final Logger log = LoggerFactory.getLogger(KubernetesFromConfigMapProcessor.class); | ||
|
||
private ApplicationContext applicationContext; | ||
|
||
private final ScheduledExecutorService configMapKeyRefresher = | ||
Executors.newSingleThreadScheduledExecutor(); | ||
|
||
@Autowired private KubernetesManifestsProperties manifestsProperties; | ||
|
||
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { | ||
|
||
for (Field field : bean.getClass().getDeclaredFields()) { | ||
ReflectionUtils.makeAccessible(field); | ||
try { | ||
if (field.get(bean) != null) { | ||
continue; // field already set, skip processing | ||
} | ||
} catch (IllegalAccessException e) { | ||
log.warn("Failed inject resource for @FromConfigMap annotated field {}", field, e); | ||
continue; | ||
} | ||
|
||
FromConfigMap fromConfigMapAnnotation = field.getAnnotation(FromConfigMap.class); | ||
if (fromConfigMapAnnotation == null) { | ||
continue; // skip if the field doesn't have the annotation | ||
} | ||
|
||
if (!Map.class.isAssignableFrom(field.getType())) { | ||
log.warn( | ||
"Failed inject resource for @FromConfigMap annotated field {}, the declaring type should be Map<String, String>", | ||
field); | ||
continue; | ||
} | ||
|
||
ConfigMapGetter configMapGetter = | ||
getOrCreateConfigMapGetter(fromConfigMapAnnotation, applicationContext); | ||
|
||
LoadingCache<String, String> configMapDataCache = | ||
Caffeine.newBuilder() | ||
.expireAfterWrite(manifestsProperties.getRefreshInterval()) | ||
.build( | ||
new ConfigMapGetterCacheLoader( | ||
() -> { | ||
return configMapGetter.get( | ||
fromConfigMapAnnotation.namespace(), fromConfigMapAnnotation.name()); | ||
})); | ||
fullyRefreshCache(configMapGetter, fromConfigMapAnnotation, configMapDataCache); | ||
configMapKeyRefresher.scheduleAtFixedRate( | ||
() -> { | ||
fullyRefreshCache(configMapGetter, fromConfigMapAnnotation, configMapDataCache); | ||
}, | ||
manifestsProperties.getRefreshInterval().getSeconds(), | ||
manifestsProperties.getRefreshInterval().getSeconds(), | ||
TimeUnit.SECONDS); | ||
ReflectionUtils.setField(field, bean, configMapDataCache.asMap()); | ||
} | ||
|
||
return bean; | ||
} | ||
|
||
private static void fullyRefreshCache( | ||
ConfigMapGetter configMapGetter, | ||
FromConfigMap fromConfigMapAnnotation, | ||
LoadingCache<String, String> configMapDataCache) { | ||
V1ConfigMap configMap = | ||
configMapGetter.get(fromConfigMapAnnotation.namespace(), fromConfigMapAnnotation.name()); | ||
if (configMap == null || configMap.getData() == null) { | ||
return; | ||
} | ||
// TODO: make the cache data refreshment atomic | ||
configMap.getData().keySet().stream().forEach(key -> configMapDataCache.refresh(key)); | ||
} | ||
|
||
private ConfigMapGetter getOrCreateConfigMapGetter( | ||
FromConfigMap fromConfigMapAnnotation, ApplicationContext applicationContext) { | ||
ConfigMapGetter configMapGetter; | ||
try { | ||
configMapGetter = | ||
applicationContext | ||
.getAutowireCapableBeanFactory() | ||
.getBean(fromConfigMapAnnotation.configMapGetter()); | ||
} catch (NoSuchBeanDefinitionException ne) { | ||
try { | ||
configMapGetter = fromConfigMapAnnotation.configMapGetter().newInstance(); | ||
} catch (IllegalAccessException | InstantiationException e) { | ||
throw new BeanCreationException("failed creating configmap getter instance", e); | ||
} | ||
applicationContext.getAutowireCapableBeanFactory().autowireBean(configMapGetter); | ||
applicationContext | ||
.getAutowireCapableBeanFactory() | ||
.initializeBean( | ||
configMapGetter, | ||
"configmap-getter-" + fromConfigMapAnnotation.configMapGetter().getSimpleName()); | ||
} | ||
return configMapGetter; | ||
} | ||
|
||
@Override | ||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { | ||
this.applicationContext = applicationContext; | ||
} | ||
|
||
static class ConfigMapGetterCacheLoader implements CacheLoader<String, String> { | ||
|
||
ConfigMapGetterCacheLoader(Supplier<V1ConfigMap> configMapSupplier) { | ||
this.configMapSupplier = configMapSupplier; | ||
} | ||
|
||
private final Supplier<V1ConfigMap> configMapSupplier; | ||
|
||
@Override | ||
public @Nullable String load(@NonNull String key) throws Exception { | ||
V1ConfigMap configMap = this.configMapSupplier.get(); | ||
if (configMap == null || configMap.getData() == null) { | ||
return null; | ||
} | ||
return configMap.getData().get(key); | ||
} | ||
} | ||
} |
56 changes: 56 additions & 0 deletions
56
...rc/main/java/io/kubernetes/client/spring/extended/manifests/annotation/FromConfigMap.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
/* | ||
Copyright 2021 The Kubernetes Authors. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
package io.kubernetes.client.spring.extended.manifests.annotation; | ||
|
||
import io.kubernetes.client.spring.extended.manifests.configmaps.ConfigMapGetter; | ||
import io.kubernetes.client.spring.extended.manifests.configmaps.PollingConfigMapGetter; | ||
import java.lang.annotation.ElementType; | ||
import java.lang.annotation.Retention; | ||
import java.lang.annotation.RetentionPolicy; | ||
import java.lang.annotation.Target; | ||
|
||
/** | ||
* Injecting resources by reading from ConfigMap. | ||
* | ||
* <p>The annotations has to be be applied to member field of type Map<String, String>. | ||
* | ||
* <p>The content of the map will be automatically updated at the interval specified by the property | ||
* "kubernetes.manifests.refreshInterval". | ||
* | ||
* <p>If the given configmap, is not present in the cluster, the content of the map will stay empty. | ||
*/ | ||
@Target({ElementType.FIELD}) | ||
@Retention(RetentionPolicy.RUNTIME) | ||
public @interface FromConfigMap { | ||
|
||
/** | ||
* Namespace of the configmap. | ||
* | ||
* @return the string | ||
*/ | ||
String namespace(); | ||
|
||
/** | ||
* Name of the configmap | ||
* | ||
* @return the string | ||
*/ | ||
String name(); | ||
|
||
/** | ||
* Config map getter class. | ||
* | ||
* @return the class | ||
*/ | ||
Class<? extends ConfigMapGetter> configMapGetter() default PollingConfigMapGetter.class; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
30 changes: 30 additions & 0 deletions
30
.../io/kubernetes/client/spring/extended/manifests/config/KubernetesManifestsProperties.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
/* | ||
Copyright 2021 The Kubernetes Authors. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
package io.kubernetes.client.spring.extended.manifests.config; | ||
|
||
import java.time.Duration; | ||
import org.springframework.boot.context.properties.ConfigurationProperties; | ||
|
||
@ConfigurationProperties("kubernetes.manifests") | ||
public class KubernetesManifestsProperties { | ||
private Duration refreshInterval = Duration.ofSeconds(5); | ||
|
||
public Duration getRefreshInterval() { | ||
return refreshInterval; | ||
} | ||
|
||
public KubernetesManifestsProperties setRefreshInterval(Duration refreshInterval) { | ||
this.refreshInterval = refreshInterval; | ||
return this; | ||
} | ||
} |
19 changes: 19 additions & 0 deletions
19
.../main/java/io/kubernetes/client/spring/extended/manifests/configmaps/ConfigMapGetter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
/* | ||
Copyright 2021 The Kubernetes Authors. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
package io.kubernetes.client.spring.extended.manifests.configmaps; | ||
|
||
import io.kubernetes.client.openapi.models.V1ConfigMap; | ||
|
||
public interface ConfigMapGetter { | ||
V1ConfigMap get(String namespace, String name); | ||
} |
27 changes: 27 additions & 0 deletions
27
...va/io/kubernetes/client/spring/extended/manifests/configmaps/InformerConfigMapGetter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
/* | ||
Copyright 2021 The Kubernetes Authors. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
package io.kubernetes.client.spring.extended.manifests.configmaps; | ||
|
||
import io.kubernetes.client.informer.cache.Lister; | ||
import io.kubernetes.client.openapi.models.V1ConfigMap; | ||
import org.springframework.beans.factory.annotation.Autowired; | ||
|
||
public class InformerConfigMapGetter implements ConfigMapGetter { | ||
|
||
@Autowired private Lister<V1ConfigMap> configMapLister; | ||
|
||
@Override | ||
public V1ConfigMap get(String namespace, String name) { | ||
return this.configMapLister.namespace(namespace).get(name); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do we want an update to be atomic? e.g. it is currently possible that a user could read half the values from ConfigMap v1 and half the values from ConfigMap v2.
This would probably be pretty unexpected from a programmers perspective.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
i added a todo comment on the line. am not sure if atomic cache entry update is supported in the cache library for now, we will need that otherwise it wont work