proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/AbstractKubernetesHealthIndicator.java
AbstractKubernetesHealthIndicator
doHealthCheck
class AbstractKubernetesHealthIndicator extends AbstractHealthIndicator { /** * Inside key. */ public static final String INSIDE = "inside"; /** * Namespace key. */ public static final String NAMESPACE = "namespace"; /** * Pod name key. */ public static final String POD_NAME = "podName"; /** * Pod IP key. */ public static final String POD_IP = "podIp"; /** * Service account key. */ public static final String SERVICE_ACCOUNT = "serviceAccount"; /** * Node name key. */ public static final String NODE_NAME = "nodeName"; /** * Host IP key. */ public static final String HOST_IP = "hostIp"; /** * Labels key. */ public static final String LABELS = "labels"; @Override protected void doHealthCheck(Health.Builder builder) {<FILL_FUNCTION_BODY>} protected abstract Map<String, Object> getDetails() throws Exception; }
try { builder.up().withDetails(getDetails()); } catch (Exception e) { builder.down(e); }
281
45
326
<methods>public final org.springframework.boot.actuate.health.Health health() <variables>private static final java.lang.String DEFAULT_MESSAGE,private static final java.lang.String NO_MESSAGE,private final Function<java.lang.Exception,java.lang.String> healthCheckFailedMessage,private final org.apache.commons.logging.Log logger
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/AbstractKubernetesInfoContributor.java
AbstractKubernetesInfoContributor
contribute
class AbstractKubernetesInfoContributor implements InfoContributor { /** * Kubernetes key. */ public static final String KUBERNETES = "kubernetes"; /** * Inside key. */ public static final String INSIDE = "inside"; /** * Namespace key. */ public static final String NAMESPACE = "namespace"; /** * Pod name key. */ public static final String POD_NAME = "podName"; /** * Pod IP key. */ public static final String POD_IP = "podIp"; /** * Service account key. */ public static final String SERVICE_ACCOUNT = "serviceAccount"; /** * Node name key. */ public static final String NODE_NAME = "nodeName"; /** * Host IP key. */ public static final String HOST_IP = "hostIp"; /** * Labels key. */ public static final String LABELS = "labels"; private static final Log LOG = LogFactory.getLog(AbstractKubernetesInfoContributor.class); @Override public void contribute(Info.Builder builder) {<FILL_FUNCTION_BODY>} public abstract Map<String, Object> getDetails(); }
try { builder.withDetail(KUBERNETES, getDetails()); } catch (Exception e) { LOG.warn("Failed to get pod details", e); }
328
55
383
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/KubernetesCommonsSanitizeAutoConfiguration.java
KubernetesCommonsSanitizeAutoConfiguration
secretsPropertySourceSanitizingFunction
class KubernetesCommonsSanitizeAutoConfiguration { @Bean @ConditionalOnMissingBean SanitizingFunction secretsPropertySourceSanitizingFunction() {<FILL_FUNCTION_BODY>} }
return data -> { PropertySource<?> propertySource = data.getPropertySource(); if (propertySource instanceof BootstrapPropertySource<?> bootstrapPropertySource) { PropertySource<?> source = bootstrapPropertySource.getDelegate(); if (source instanceof SecretsPropertySource) { return new SanitizableData(propertySource, data.getKey(), data.getValue()) .withValue(SanitizableData.SANITIZED_VALUE); } } if (propertySource instanceof SecretsPropertySource) { return new SanitizableData(propertySource, data.getKey(), data.getValue()) .withValue(SanitizableData.SANITIZED_VALUE); } // at the moment, our structure is pretty simply, CompositePropertySource // children can be SecretsPropertySource; i.e.: there is no recursion // needed to get all children. If this structure changes, there are enough // unit tests that will start failing. if (propertySource instanceof CompositePropertySource compositePropertySource) { Collection<PropertySource<?>> sources = compositePropertySource.getPropertySources(); for (PropertySource<?> one : sources) { if (one.containsProperty(data.getKey()) && one instanceof SecretsPropertySource) { return new SanitizableData(propertySource, data.getKey(), data.getValue()) .withValue(SanitizableData.SANITIZED_VALUE); } } } return data; };
54
376
430
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/KubernetesNamespaceProvider.java
KubernetesNamespaceProvider
getNamespace
class KubernetesNamespaceProvider { /** * Property name for namespace. */ public static final String NAMESPACE_PROPERTY = "spring.cloud.kubernetes.client.namespace"; /** * Property for namespace file path. */ public static final String NAMESPACE_PATH_PROPERTY = "spring.cloud.kubernetes.client.serviceAccountNamespacePath"; private static final DeferredLog LOG = new DeferredLog(); private String namespacePropertyValue; private BindHandler bindHandler; private String serviceAccountNamespace; private Environment environment; private Binder binder; public KubernetesNamespaceProvider(Environment env) { this.environment = env; LOG.replayTo(KubernetesNamespaceProvider.class); } public KubernetesNamespaceProvider(Binder binder, BindHandler bindHandler) { this.binder = binder; this.bindHandler = bindHandler; } public KubernetesNamespaceProvider(String namespacePropertyValue) { this.namespacePropertyValue = namespacePropertyValue; } public static String getNamespaceFromServiceAccountFile(String path) { String namespace = null; LOG.debug("Looking for service account namespace at: [" + path + "]."); Path serviceAccountNamespacePath = Paths.get(path); boolean serviceAccountNamespaceExists = Files.isRegularFile(serviceAccountNamespacePath); if (serviceAccountNamespaceExists) { LOG.debug("Found service account namespace at: [" + serviceAccountNamespacePath + "]."); try { namespace = new String(Files.readAllBytes((serviceAccountNamespacePath))); LOG.debug("Service account namespace value: " + serviceAccountNamespacePath); } catch (IOException ioe) { LOG.error("Error reading service account namespace from: [" + serviceAccountNamespacePath + "].", ioe); } } return namespace; } public String getNamespace() {<FILL_FUNCTION_BODY>} private String getServiceAccountNamespace() { String serviceAccountNamespacePathString = null; if (environment != null) { serviceAccountNamespacePathString = environment.getProperty(NAMESPACE_PATH_PROPERTY, SERVICE_ACCOUNT_NAMESPACE_PATH); } if (ObjectUtils.isEmpty(serviceAccountNamespacePathString) && binder != null) { // When using the binder we cannot use camelcase properties, it considers them // invalid serviceAccountNamespacePathString = binder .bind("spring.cloud.kubernetes.client.service-account-namespace-path", Bindable.of(String.class), bindHandler) .orElse(SERVICE_ACCOUNT_NAMESPACE_PATH); } if (serviceAccountNamespace == null) { serviceAccountNamespace = getNamespaceFromServiceAccountFile(serviceAccountNamespacePathString); } return serviceAccountNamespace; } }
// If they provided the namespace in the constructor just return that if (!ObjectUtils.isEmpty(namespacePropertyValue)) { return namespacePropertyValue; } // No namespace provided so try to get it from another source String namespace = null; if (environment != null) { namespace = environment.getProperty(NAMESPACE_PROPERTY); } if (ObjectUtils.isEmpty(namespace) && binder != null) { namespace = binder.bind(NAMESPACE_PROPERTY, String.class).orElse(null); } return namespace != null ? namespace : getServiceAccountNamespace();
734
160
894
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/LazilyInstantiate.java
LazilyInstantiate
get
class LazilyInstantiate<T> implements Supplier<T> { private volatile T t; private final Supplier<T> supplier; private LazilyInstantiate(Supplier<T> supplier) { this.supplier = supplier; } public static <T> LazilyInstantiate<T> using(Supplier<T> supplier) { return new LazilyInstantiate<>(supplier); } public T get() {<FILL_FUNCTION_BODY>} }
T localT = t; if (localT == null) { synchronized (this) { localT = t; if (localT == null) { localT = supplier.get(); t = localT; } } } return localT;
130
81
211
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/ConfigMapPropertySourceLocator.java
ConfigMapPropertySourceLocator
addPropertySourcesFromPaths
class ConfigMapPropertySourceLocator implements PropertySourceLocator { private static final Log LOG = LogFactory.getLog(ConfigMapPropertySourceLocator.class); private final ConfigMapCache cache; protected final ConfigMapConfigProperties properties; /** * This constructor is deprecated, and we do not use it anymore internally. It will be * removed in the next major release. */ @Deprecated(forRemoval = true) public ConfigMapPropertySourceLocator(ConfigMapConfigProperties properties) { this.properties = properties; this.cache = new ConfigMapCache.NOOPCache(); } public ConfigMapPropertySourceLocator(ConfigMapConfigProperties properties, ConfigMapCache cache) { this.properties = properties; this.cache = cache; } protected abstract MapPropertySource getMapPropertySource(NormalizedSource normalizedSource, ConfigurableEnvironment environment); @Override public PropertySource<?> locate(Environment environment) { if (environment instanceof ConfigurableEnvironment env) { CompositePropertySource composite = new CompositePropertySource("composite-configmap"); if (this.properties.enableApi()) { Set<NormalizedSource> sources = new LinkedHashSet<>(this.properties.determineSources(environment)); LOG.debug("Config Map normalized sources : " + sources); sources.forEach(s -> composite.addFirstPropertySource(getMapPropertySource(s, env))); } addPropertySourcesFromPaths(environment, composite); cache.discardAll(); return composite; } return null; } @Override public Collection<PropertySource<?>> locateCollection(Environment environment) { return PropertySourceLocator.super.locateCollection(environment); } private void addPropertySourcesFromPaths(Environment environment, CompositePropertySource composite) {<FILL_FUNCTION_BODY>} private void addPropertySourceIfNeeded(Function<String, Map<String, Object>> contentToMapFunction, String content, String name, CompositePropertySource composite) { Map<String, Object> map = new HashMap<>(contentToMapFunction.apply(content)); if (map.isEmpty()) { LOG.warn("Property source: " + name + "will be ignored because no properties could be found"); } else { LOG.debug("will add file-based property source : " + name); composite.addFirstPropertySource(new MountConfigMapPropertySource(name, map)); } } }
Set<String> uniquePaths = new LinkedHashSet<>(properties.paths()); if (!uniquePaths.isEmpty()) { LOG.warn( "path support is deprecated and will be removed in a future release. Please use spring.config.import"); } LOG.debug("paths property sources : " + uniquePaths); uniquePaths.stream().map(Paths::get).filter(p -> { boolean exists = Files.exists(p); if (!exists) { LOG.warn("Configured input path: " + p + " will be ignored because it does not exist on the file system"); } return exists; }).filter(p -> { boolean regular = Files.isRegularFile(p); if (!regular) { LOG.warn("Configured input path: " + p + " will be ignored because it is not a regular file"); } return regular; }).toList().forEach(p -> { try { String content = new String(Files.readAllBytes(p)).trim(); String filename = p.toAbsolutePath().toString().toLowerCase(); if (filename.endsWith(".properties")) { addPropertySourceIfNeeded(c -> PROPERTIES_TO_MAP.apply(KEY_VALUE_TO_PROPERTIES.apply(c)), content, filename, composite); } else if (filename.endsWith(".yml") || filename.endsWith(".yaml")) { addPropertySourceIfNeeded(c -> PROPERTIES_TO_MAP.apply(yamlParserGenerator(environment).apply(c)), content, filename, composite); } } catch (IOException e) { LOG.warn("Error reading input file", e); } });
620
456
1,076
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigDataLoader.java
KubernetesConfigDataLoader
load
class KubernetesConfigDataLoader implements ConfigDataLoader<KubernetesConfigDataResource>, Ordered { @Override public ConfigData load(ConfigDataLoaderContext context, KubernetesConfigDataResource resource) throws IOException, ConfigDataResourceNotFoundException {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return -1; } }
List<PropertySource<?>> propertySources = new ArrayList<>(2); ConfigurableBootstrapContext bootstrapContext = context.getBootstrapContext(); Environment env = resource.getEnvironment(); if (bootstrapContext.isRegistered(SecretsPropertySourceLocator.class)) { propertySources.add(bootstrapContext.get(SecretsPropertySourceLocator.class).locate(env)); } if (bootstrapContext.isRegistered(ConfigMapPropertySourceLocator.class)) { propertySources.add(bootstrapContext.get(ConfigMapPropertySourceLocator.class).locate(env)); } // boot 2.4.5+ return new ConfigData(propertySources, propertySource -> { String propertySourceName = propertySource.getName(); List<Option> options = new ArrayList<>(); options.add(Option.IGNORE_IMPORTS); options.add(Option.IGNORE_PROFILES); // TODO: the profile is now available on the backend // in a future minor, add the profile associated with a // PropertySource see // https://github.com/spring-cloud/spring-cloud-config/issues/1874 for (String profile : resource.getAcceptedProfiles()) { // TODO: switch to match // , is used as a profile-separator for property sources // from vault // - is the default profile-separator for property sources if (propertySourceName.matches(".*[-,]" + profile + ".*")) { // // TODO: switch to Options.with() when implemented options.add(Option.PROFILE_SPECIFIC); } } return ConfigData.Options.of(options.toArray(new Option[0])); });
94
448
542
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigDataLocationResolver.java
KubernetesConfigDataLocationResolver
of
class KubernetesConfigDataLocationResolver implements ConfigDataLocationResolver<KubernetesConfigDataResource>, Ordered { private static final boolean RETRY_IS_PRESENT = isPresent("org.springframework.retry.annotation.Retryable", null); private final Log log; public KubernetesConfigDataLocationResolver(DeferredLogFactory factory) { this.log = factory.getLog(KubernetesConfigDataLocationResolver.class); } protected final String getPrefix() { return "kubernetes:"; } @Override public final int getOrder() { return -1; } @Override public final boolean isResolvable(ConfigDataLocationResolverContext context, ConfigDataLocation location) { return location.hasPrefix(getPrefix()) && (KUBERNETES.isEnforced(context.getBinder()) || KUBERNETES.isDetected(new StandardEnvironment())); } @Override public final List<KubernetesConfigDataResource> resolve(ConfigDataLocationResolverContext context, ConfigDataLocation location) throws ConfigDataLocationNotFoundException, ConfigDataResourceNotFoundException { return Collections.emptyList(); } @Override public final List<KubernetesConfigDataResource> resolveProfileSpecific( ConfigDataLocationResolverContext resolverContext, ConfigDataLocation location, Profiles profiles) throws ConfigDataLocationNotFoundException { PropertyHolder propertyHolder = PropertyHolder.of(resolverContext); KubernetesClientProperties clientProperties = propertyHolder.kubernetesClientProperties(); ConfigMapConfigProperties configMapProperties = propertyHolder.configMapConfigProperties(); SecretsConfigProperties secretsProperties = propertyHolder.secretsProperties(); registerProperties(resolverContext, clientProperties, configMapProperties, secretsProperties); HashMap<String, Object> kubernetesConfigData = new HashMap<>(); kubernetesConfigData.put("spring.cloud.kubernetes.client.namespace", clientProperties.namespace()); if (propertyHolder.applicationName() != null) { // If its null it means sprig.application.name was not set so don't add it to // the property source kubernetesConfigData.put("spring.application.name", propertyHolder.applicationName()); } PropertySource<Map<String, Object>> propertySource = new MapPropertySource("kubernetesConfigData", kubernetesConfigData); ConfigurableEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addLast(propertySource); environment.setActiveProfiles(profiles.getAccepted().toArray(new String[0])); KubernetesNamespaceProvider namespaceProvider = kubernetesNamespaceProvider(environment); registerBeans(resolverContext, location, profiles, propertyHolder, namespaceProvider); KubernetesConfigDataResource resource = new KubernetesConfigDataResource(clientProperties, configMapProperties, secretsProperties, location.isOptional(), profiles, environment); resource.setLog(log); return List.of(resource); } protected abstract void registerBeans(ConfigDataLocationResolverContext resolverContext, ConfigDataLocation location, Profiles profiles, PropertyHolder propertyHolder, KubernetesNamespaceProvider namespaceProvider); protected final boolean isRetryEnabledForConfigMap(ConfigMapConfigProperties configMapProperties) { return RETRY_IS_PRESENT && configMapProperties != null && configMapProperties.retry().enabled() && configMapProperties.failFast(); } protected final boolean isRetryEnabledForSecrets(SecretsConfigProperties secretsProperties) { return RETRY_IS_PRESENT && secretsProperties != null && secretsProperties.retry().enabled() && secretsProperties.failFast(); } protected KubernetesNamespaceProvider kubernetesNamespaceProvider(Environment environment) { return new KubernetesNamespaceProvider(environment); } private void registerProperties(ConfigDataLocationResolverContext resolverContext, KubernetesClientProperties clientProperties, ConfigMapConfigProperties configMapProperties, SecretsConfigProperties secretsProperties) { ConfigurableBootstrapContext bootstrapContext = resolverContext.getBootstrapContext(); registerSingle(bootstrapContext, KubernetesClientProperties.class, clientProperties, "configDataKubernetesClientProperties"); if (configMapProperties != null) { registerSingle(bootstrapContext, ConfigMapConfigProperties.class, configMapProperties, "configDataConfigMapConfigProperties"); } if (secretsProperties != null) { registerSingle(bootstrapContext, SecretsConfigProperties.class, secretsProperties, "configDataSecretsConfigProperties"); } } protected record PropertyHolder(KubernetesClientProperties kubernetesClientProperties, ConfigMapConfigProperties configMapConfigProperties, SecretsConfigProperties secretsProperties, String applicationName) { private static PropertyHolder of(ConfigDataLocationResolverContext context) {<FILL_FUNCTION_BODY>} private static KubernetesClientProperties clientProperties(ConfigDataLocationResolverContext context, String namespace) { KubernetesClientProperties kubernetesClientProperties; if (context.getBootstrapContext().isRegistered(KubernetesClientProperties.class)) { kubernetesClientProperties = context.getBootstrapContext().get(KubernetesClientProperties.class) .withNamespace(namespace); } else { kubernetesClientProperties = context.getBinder() .bindOrCreate(KubernetesClientProperties.PREFIX, Bindable.of(KubernetesClientProperties.class)) .withNamespace(namespace); } return kubernetesClientProperties; } } /** * holds ConfigMapConfigProperties and SecretsConfigProperties, both can be null if * using such sources is disabled. */ private record ConfigMapAndSecrets(ConfigMapConfigProperties configMapProperties, SecretsConfigProperties secretsConfigProperties) { private static ConfigMapAndSecrets of(Binder binder) { boolean configEnabled = binder.bind("spring.cloud.kubernetes.config.enabled", boolean.class).orElse(true); boolean secretsEnabled = binder.bind("spring.cloud.kubernetes.secrets.enabled", boolean.class).orElse(true); ConfigMapConfigProperties configMapConfigProperties = null; if (configEnabled) { configMapConfigProperties = binder.bindOrCreate(ConfigMapConfigProperties.PREFIX, ConfigMapConfigProperties.class); } SecretsConfigProperties secretsProperties = null; if (secretsEnabled) { secretsProperties = binder.bindOrCreate(SecretsConfigProperties.PREFIX, SecretsConfigProperties.class); } return new ConfigMapAndSecrets(configMapConfigProperties, secretsProperties); } } }
Binder binder = context.getBinder(); String applicationName = binder.bind("spring.application.name", String.class).orElse(null); String namespace = binder.bind("spring.cloud.kubernetes.client.namespace", String.class) .orElse(binder.bind("kubernetes.namespace", String.class).orElse("")); KubernetesClientProperties kubernetesClientProperties = clientProperties(context, namespace); ConfigMapAndSecrets both = ConfigMapAndSecrets.of(binder); return new PropertyHolder(kubernetesClientProperties, both.configMapProperties(), both.secretsConfigProperties(), applicationName);
1,698
175
1,873
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigDataResource.java
KubernetesConfigDataResource
equals
class KubernetesConfigDataResource extends ConfigDataResource { private final KubernetesClientProperties properties; private final ConfigMapConfigProperties configMapProperties; private final SecretsConfigProperties secretsConfigProperties; private final boolean optional; private final Profiles profiles; private Log log; private Environment environment; public KubernetesConfigDataResource(KubernetesClientProperties properties, ConfigMapConfigProperties configMapProperties, SecretsConfigProperties secretsConfigProperties, boolean optional, Profiles profiles, Environment environment) { this.properties = properties; this.configMapProperties = configMapProperties; this.secretsConfigProperties = secretsConfigProperties; this.optional = optional; this.profiles = profiles; this.environment = environment; } public KubernetesClientProperties getProperties() { return this.properties; } /** * ConfigMapConfigProperties that might be null. */ public ConfigMapConfigProperties getConfigMapProperties() { return configMapProperties; } /** * SecretsConfigProperties that might be null. */ public SecretsConfigProperties getSecretsConfigProperties() { return secretsConfigProperties; } public boolean isOptional() { return this.optional; } public String getProfiles() { return StringUtils.collectionToCommaDelimitedString(getAcceptedProfiles()); } List<String> getAcceptedProfiles() { return this.profiles.getAccepted(); } public void setLog(Log log) { this.log = log; } public Log getLog() { return this.log; } public Environment getEnvironment() { return environment; } public void setEnvironment(Environment environment) { this.environment = environment; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(this.properties, this.optional, this.profiles, configMapProperties, secretsConfigProperties); } @Override public String toString() { return new ToStringCreator(this).append("optional", optional).append("profiles", profiles.getAccepted()) .toString(); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } KubernetesConfigDataResource that = (KubernetesConfigDataResource) o; return Objects.equals(this.properties, that.properties) && Objects.equals(this.optional, that.optional) && Objects.equals(this.profiles, that.profiles) && Objects.equals(this.configMapProperties, that.configMapProperties) && Objects.equals(this.secretsConfigProperties, that.secretsConfigProperties);
559
160
719
<methods>public void <init>() <variables>private final boolean optional
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/KubernetesConfigServerBootstrapper.java
KubernetesConfigServerBootstrapper
createKubernetesDiscoveryProperties
class KubernetesConfigServerBootstrapper implements BootstrapRegistryInitializer { public static boolean hasConfigServerInstanceProvider() { return !ClassUtils.isPresent("org.springframework.cloud.config.client.ConfigServerInstanceProvider", null); } public static KubernetesDiscoveryProperties createKubernetesDiscoveryProperties(Binder binder, BindHandler bindHandler) { return binder.bind(KubernetesDiscoveryProperties.PREFIX, Bindable.of(KubernetesDiscoveryProperties.class), bindHandler).orElseGet(() -> KubernetesDiscoveryProperties.DEFAULT); } public static KubernetesDiscoveryProperties createKubernetesDiscoveryProperties(BootstrapContext bootstrapContext) {<FILL_FUNCTION_BODY>} public static KubernetesClientProperties createKubernetesClientProperties(Binder binder, BindHandler bindHandler) { return binder.bindOrCreate(KubernetesClientProperties.PREFIX, Bindable.of(KubernetesClientProperties.class)) .withNamespace(new KubernetesNamespaceProvider(binder, bindHandler).getNamespace()); } public static KubernetesClientProperties createKubernetesClientProperties(BootstrapContext bootstrapContext) { PropertyResolver propertyResolver = getPropertyResolver(bootstrapContext); return getPropertyResolver(bootstrapContext) .resolveOrCreateConfigurationProperties(KubernetesClientProperties.PREFIX, KubernetesClientProperties.class) .withNamespace( propertyResolver.get(KubernetesNamespaceProvider.NAMESPACE_PROPERTY, String.class, null)); } public static Boolean getDiscoveryEnabled(Binder binder, BindHandler bindHandler) { return binder.bind(ConfigClientProperties.CONFIG_DISCOVERY_ENABLED, Bindable.of(Boolean.class), bindHandler) .orElse(false); } public static Boolean getDiscoveryEnabled(BootstrapContext bootstrapContext) { return getPropertyResolver(bootstrapContext).get(ConfigClientProperties.CONFIG_DISCOVERY_ENABLED, Boolean.class, false); } protected static PropertyResolver getPropertyResolver(BootstrapContext context) { return context.getOrElseSupply(ConfigServerConfigDataLocationResolver.PropertyResolver.class, () -> new ConfigServerConfigDataLocationResolver.PropertyResolver(context.get(Binder.class), context.getOrElse(BindHandler.class, null))); } }
PropertyResolver propertyResolver = getPropertyResolver(bootstrapContext); return propertyResolver.resolveConfigurationProperties(KubernetesDiscoveryProperties.PREFIX, KubernetesDiscoveryProperties.class, () -> KubernetesDiscoveryProperties.DEFAULT);
597
62
659
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/LabeledConfigMapNormalizedSource.java
LabeledConfigMapNormalizedSource
equals
class LabeledConfigMapNormalizedSource extends NormalizedSource { private final Map<String, String> labels; private final ConfigUtils.Prefix prefix; private final boolean includeProfileSpecificSources; public LabeledConfigMapNormalizedSource(String namespace, Map<String, String> labels, boolean failFast, ConfigUtils.Prefix prefix, boolean includeProfileSpecificSources) { super(null, namespace, failFast); this.labels = Collections.unmodifiableMap(Objects.requireNonNull(labels)); this.prefix = Objects.requireNonNull(prefix); this.includeProfileSpecificSources = includeProfileSpecificSources; } public LabeledConfigMapNormalizedSource(String namespace, Map<String, String> labels, boolean failFast, boolean includeProfileSpecificSources) { super(null, namespace, failFast); this.labels = Collections.unmodifiableMap(Objects.requireNonNull(labels)); this.prefix = ConfigUtils.Prefix.DEFAULT; this.includeProfileSpecificSources = includeProfileSpecificSources; } /** * will return an immutable Map. */ public Map<String, String> labels() { return labels; } public ConfigUtils.Prefix prefix() { return prefix; } public boolean profileSpecificSources() { return this.includeProfileSpecificSources; } @Override public NormalizedSourceType type() { return NormalizedSourceType.LABELED_CONFIG_MAP; } @Override public String target() { return "configmap"; } @Override public String toString() { return "{ config map labels : '" + labels() + "', namespace : '" + namespace() + "'"; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(labels(), namespace()); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LabeledConfigMapNormalizedSource other = (LabeledConfigMapNormalizedSource) o; return Objects.equals(labels(), other.labels()) && Objects.equals(namespace(), other.namespace());
484
96
580
<methods>public abstract boolean equals(java.lang.Object) ,public final boolean failFast() ,public abstract int hashCode() ,public final Optional<java.lang.String> name() ,public final Optional<java.lang.String> namespace() ,public abstract java.lang.String target() ,public abstract java.lang.String toString() ,public abstract org.springframework.cloud.kubernetes.commons.config.NormalizedSourceType type() <variables>permits LabeledConfigMapNormalizedSource,permits LabeledSecretNormalizedSource,permits NamedConfigMapNormalizedSource,permits NamedSecretNormalizedSource,private final non-sealed boolean failFast,private final non-sealed java.lang.String name,private final non-sealed java.lang.String namespace
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/LabeledSecretNormalizedSource.java
LabeledSecretNormalizedSource
equals
class LabeledSecretNormalizedSource extends NormalizedSource { private final Map<String, String> labels; private final ConfigUtils.Prefix prefix; private final boolean includeProfileSpecificSources; public LabeledSecretNormalizedSource(String namespace, Map<String, String> labels, boolean failFast, ConfigUtils.Prefix prefix, boolean includeProfileSpecificSources) { super(null, namespace, failFast); this.labels = Collections.unmodifiableMap(Objects.requireNonNull(labels)); this.prefix = Objects.requireNonNull(prefix); this.includeProfileSpecificSources = includeProfileSpecificSources; } public LabeledSecretNormalizedSource(String namespace, Map<String, String> labels, boolean failFast, boolean includeProfileSpecificSources) { super(null, namespace, failFast); this.labels = Collections.unmodifiableMap(Objects.requireNonNull(labels)); this.prefix = ConfigUtils.Prefix.DEFAULT; this.includeProfileSpecificSources = includeProfileSpecificSources; } /** * will return an immutable Map. */ public Map<String, String> labels() { return labels; } public ConfigUtils.Prefix prefix() { return prefix; } public boolean profileSpecificSources() { return this.includeProfileSpecificSources; } @Override public NormalizedSourceType type() { return NormalizedSourceType.LABELED_SECRET; } @Override public String target() { return "secret"; } @Override public String toString() { return "{ secret labels : '" + labels() + "', namespace : '" + namespace() + "'"; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(labels(), namespace()); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LabeledSecretNormalizedSource other = (LabeledSecretNormalizedSource) o; return Objects.equals(labels(), other.labels()) && Objects.equals(namespace(), other.namespace());
479
94
573
<methods>public abstract boolean equals(java.lang.Object) ,public final boolean failFast() ,public abstract int hashCode() ,public final Optional<java.lang.String> name() ,public final Optional<java.lang.String> namespace() ,public abstract java.lang.String target() ,public abstract java.lang.String toString() ,public abstract org.springframework.cloud.kubernetes.commons.config.NormalizedSourceType type() <variables>permits LabeledConfigMapNormalizedSource,permits LabeledSecretNormalizedSource,permits NamedConfigMapNormalizedSource,permits NamedSecretNormalizedSource,private final non-sealed boolean failFast,private final non-sealed java.lang.String name,private final non-sealed java.lang.String namespace
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/LabeledSourceData.java
LabeledSourceData
compute
class LabeledSourceData { public final SourceData compute(Map<String, String> labels, ConfigUtils.Prefix prefix, String target, boolean profileSources, boolean failFast, String namespace, String[] activeProfiles) {<FILL_FUNCTION_BODY>} /** * Implementation specific (fabric8 or k8s-native) way to get the data from then given * source names. * @param labels the ones that have been configured * @param profiles profiles to taken into account when gathering source data. Can be * empty. * @return a container that holds the names of the source that were found and their * data */ public abstract MultipleSourcesContainer dataSupplier(Map<String, String> labels, Set<String> profiles); }
MultipleSourcesContainer data = MultipleSourcesContainer.empty(); try { Set<String> profiles = Set.of(); if (profileSources) { profiles = Arrays.stream(activeProfiles).collect(Collectors.toSet()); } data = dataSupplier(labels, profiles); // need this check because when there is no data, the name of the property // source // is using provided labels, // unlike when the data is present: when we use secret names if (data.names().isEmpty()) { String names = labels.keySet().stream().sorted() .collect(Collectors.joining(PROPERTY_SOURCE_NAME_SEPARATOR)); return SourceData.emptyRecord(ConfigUtils.sourceName(target, names, namespace)); } if (prefix != ConfigUtils.Prefix.DEFAULT) { String prefixToUse; if (prefix == ConfigUtils.Prefix.KNOWN) { prefixToUse = prefix.prefixProvider().get(); } else { prefixToUse = data.names().stream().sorted() .collect(Collectors.joining(PROPERTY_SOURCE_NAME_SEPARATOR)); } PrefixContext prefixContext = new PrefixContext(data.data(), prefixToUse, namespace, data.names()); return ConfigUtils.withPrefix(target, prefixContext); } } catch (Exception e) { onException(failFast, e); } String names = data.names().stream().sorted().collect(Collectors.joining(PROPERTY_SOURCE_NAME_SEPARATOR)); return new SourceData(ConfigUtils.sourceName(target, names, namespace), data.data());
190
444
634
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/NamedConfigMapNormalizedSource.java
NamedConfigMapNormalizedSource
toString
class NamedConfigMapNormalizedSource extends NormalizedSource { private final ConfigUtils.Prefix prefix; private final boolean includeProfileSpecificSources; private final boolean appendProfileToName; public NamedConfigMapNormalizedSource(String name, String namespace, boolean failFast, ConfigUtils.Prefix prefix, boolean includeProfileSpecificSources) { this(name, namespace, failFast, prefix, includeProfileSpecificSources, false); } public NamedConfigMapNormalizedSource(String name, String namespace, boolean failFast, boolean includeProfileSpecificSources) { this(name, namespace, failFast, ConfigUtils.Prefix.DEFAULT, includeProfileSpecificSources); } public NamedConfigMapNormalizedSource(String name, String namespace, boolean failFast, ConfigUtils.Prefix prefix, boolean includeProfileSpecificSources, boolean appendProfileToName) { super(name, namespace, failFast); this.prefix = Objects.requireNonNull(prefix); this.includeProfileSpecificSources = includeProfileSpecificSources; this.appendProfileToName = appendProfileToName; } public ConfigUtils.Prefix prefix() { return prefix; } public boolean profileSpecificSources() { return includeProfileSpecificSources; } /** * append or not the active profiles to the name of the generated source. At the * moment this is true only for config server generated sources. */ public boolean appendProfileToName() { return appendProfileToName; } @Override public NormalizedSourceType type() { return NormalizedSourceType.NAMED_CONFIG_MAP; } @Override public String target() { return "configmap"; } @Override public String toString() {<FILL_FUNCTION_BODY>} @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NamedConfigMapNormalizedSource other = (NamedConfigMapNormalizedSource) o; return Objects.equals(this.name(), other.name()) && Objects.equals(this.namespace(), other.namespace()); } @Override public int hashCode() { return Objects.hash(name(), namespace()); } }
return "{ config-map name : '" + name() + "', namespace : '" + namespace() + "', prefix : '" + prefix() + "' }";
585
39
624
<methods>public abstract boolean equals(java.lang.Object) ,public final boolean failFast() ,public abstract int hashCode() ,public final Optional<java.lang.String> name() ,public final Optional<java.lang.String> namespace() ,public abstract java.lang.String target() ,public abstract java.lang.String toString() ,public abstract org.springframework.cloud.kubernetes.commons.config.NormalizedSourceType type() <variables>permits LabeledConfigMapNormalizedSource,permits LabeledSecretNormalizedSource,permits NamedConfigMapNormalizedSource,permits NamedSecretNormalizedSource,private final non-sealed boolean failFast,private final non-sealed java.lang.String name,private final non-sealed java.lang.String namespace
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/NamedSecretNormalizedSource.java
NamedSecretNormalizedSource
toString
class NamedSecretNormalizedSource extends NormalizedSource { private final ConfigUtils.Prefix prefix; private final boolean includeProfileSpecificSources; private final boolean appendProfileToName; public NamedSecretNormalizedSource(String name, String namespace, boolean failFast, ConfigUtils.Prefix prefix, boolean includeProfileSpecificSources, boolean appendProfileToName) { super(name, namespace, failFast); this.prefix = Objects.requireNonNull(prefix); this.includeProfileSpecificSources = includeProfileSpecificSources; this.appendProfileToName = appendProfileToName; } public NamedSecretNormalizedSource(String name, String namespace, boolean failFast, boolean includeProfileSpecificSources) { this(name, namespace, failFast, ConfigUtils.Prefix.DEFAULT, includeProfileSpecificSources, false); } public NamedSecretNormalizedSource(String name, String namespace, boolean failFast, ConfigUtils.Prefix prefix, boolean includeProfileSpecificSources) { this(name, namespace, failFast, prefix, includeProfileSpecificSources, false); } public boolean profileSpecificSources() { return includeProfileSpecificSources; } /** * append or not the active profiles to the name of the generated source. At the * moment this is true only for config server generated sources. */ public boolean appendProfileToName() { return appendProfileToName; } public ConfigUtils.Prefix prefix() { return prefix; } @Override public NormalizedSourceType type() { return NormalizedSourceType.NAMED_SECRET; } @Override public String target() { return "secret"; } @Override public String toString() {<FILL_FUNCTION_BODY>} @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NamedSecretNormalizedSource other = (NamedSecretNormalizedSource) o; return Objects.equals(name(), other.name()) && Objects.equals(namespace(), other.namespace()); } @Override public int hashCode() { return Objects.hash(name(), namespace()); } }
return "{ secret name : '" + name() + "', namespace : '" + namespace() + "'";
575
27
602
<methods>public abstract boolean equals(java.lang.Object) ,public final boolean failFast() ,public abstract int hashCode() ,public final Optional<java.lang.String> name() ,public final Optional<java.lang.String> namespace() ,public abstract java.lang.String target() ,public abstract java.lang.String toString() ,public abstract org.springframework.cloud.kubernetes.commons.config.NormalizedSourceType type() <variables>permits LabeledConfigMapNormalizedSource,permits LabeledSecretNormalizedSource,permits NamedConfigMapNormalizedSource,permits NamedSecretNormalizedSource,private final non-sealed boolean failFast,private final non-sealed java.lang.String name,private final non-sealed java.lang.String namespace
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/NamedSourceData.java
NamedSourceData
compute
class NamedSourceData { public final SourceData compute(String sourceName, ConfigUtils.Prefix prefix, String target, boolean profileSources, boolean failFast, String namespace, String[] activeProfiles) {<FILL_FUNCTION_BODY>} protected String generateSourceName(String target, String sourceName, String namespace, String[] activeProfiles) { return ConfigUtils.sourceName(target, sourceName, namespace); } /** * Implementation specific (fabric8 or k8s-native) way to get the data from then given * source names. * @param sourceNames the ones that have been configured, LinkedHashSet in order ot * preserve the order: non-profile source first and then the rest * @return an Entry that holds the names of the source that were found and their data */ public abstract MultipleSourcesContainer dataSupplier(LinkedHashSet<String> sourceNames); }
LinkedHashSet<String> sourceNames = new LinkedHashSet<>(); // first comes non-profile based source sourceNames.add(sourceName); MultipleSourcesContainer data = MultipleSourcesContainer.empty(); try { if (profileSources) { for (String activeProfile : activeProfiles) { // add all profile based sources _after_ non-profile based one sourceNames.add(sourceName + "-" + activeProfile); } } data = dataSupplier(sourceNames); if (data.names().isEmpty()) { return new SourceData(ConfigUtils.sourceName(target, sourceName, namespace), Map.of()); } if (prefix != ConfigUtils.Prefix.DEFAULT) { // since we are in a named source, calling get on the supplier is safe String prefixToUse = prefix.prefixProvider().get(); PrefixContext prefixContext = new PrefixContext(data.data(), prefixToUse, namespace, data.names()); return ConfigUtils.withPrefix(target, prefixContext); } } catch (Exception e) { onException(failFast, e); } String names = data.names().stream().sorted().collect(Collectors.joining(PROPERTY_SOURCE_NAME_SEPARATOR)); return new SourceData(generateSourceName(target, names, namespace, activeProfiles), data.data());
224
362
586
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/PropertySourceUtils.java
PropertySourceUtils
yamlParserGenerator
class PropertySourceUtils { private PropertySourceUtils() { throw new IllegalStateException("Can't instantiate a utility class"); } /** * Function to convert a String to Properties. */ public static final Function<String, Properties> KEY_VALUE_TO_PROPERTIES = s -> { Properties properties = new Properties(); try { properties.load(new ByteArrayInputStream(s.getBytes())); return properties; } catch (IOException e) { throw new UncheckedIOException(e); } }; /** * Function to convert Properties to a Map. */ public static final Function<Properties, Map<String, Object>> PROPERTIES_TO_MAP = p -> p.entrySet().stream() .collect(Collectors.toMap(e -> e.getKey().toString(), Map.Entry::getValue)); /** * Function to convert String into Properties with an environment. * @param environment Environment. * @return properties. */ public static Function<String, Properties> yamlParserGenerator(Environment environment) {<FILL_FUNCTION_BODY>} /** * returns a {@link BinaryOperator} that unconditionally throws an * {@link IllegalStateException}. * @param <T> type of the argument * @return a {@link BinaryOperator} */ public static <T> BinaryOperator<T> throwingMerger() { return (left, right) -> { throw new IllegalStateException("Duplicate key " + left); }; } }
return s -> { YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean(); yamlFactory.setDocumentMatchers(properties -> { if (environment != null) { String profiles = null; String activeOnProfile = properties.getProperty(SPRING_CONFIG_ACTIVATE_ON_PROFILE); String springProfiles = properties.getProperty(SPRING_PROFILES); if (activeOnProfile != null) { profiles = activeOnProfile; } else if (springProfiles != null) { profiles = springProfiles; } if (StringUtils.hasText(profiles)) { return environment.acceptsProfiles(Profiles.of(profiles)) ? FOUND : NOT_FOUND; } } return ABSTAIN; }); yamlFactory.setResources(new ByteArrayResource(s.getBytes(StandardCharsets.UTF_8))); return yamlFactory.getObject(); };
390
261
651
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/SecretsPropertySource.java
SecretsPropertySource
toString
class SecretsPropertySource extends MapPropertySource { public SecretsPropertySource(SourceData sourceData) { super(sourceData.sourceName(), sourceData.sourceData()); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return getClass().getSimpleName() + " {name='" + this.name + "'}";
70
27
97
<methods>public void <init>(java.lang.String, Map<java.lang.String,java.lang.Object>) ,public boolean containsProperty(java.lang.String) ,public java.lang.Object getProperty(java.lang.String) ,public java.lang.String[] getPropertyNames() <variables>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/SecretsPropertySourceLocator.java
SecretsPropertySourceLocator
putPathConfig
class SecretsPropertySourceLocator implements PropertySourceLocator { private static final Log LOG = LogFactory.getLog(SecretsPropertySourceLocator.class); private final SecretsCache cache; protected final SecretsConfigProperties properties; /** * This constructor is deprecated, and we do not use it anymore internally. It will be * removed in the next major release. */ @Deprecated(forRemoval = true) public SecretsPropertySourceLocator(SecretsConfigProperties properties) { this.properties = properties; this.cache = new SecretsCache.NOOPCache(); } public SecretsPropertySourceLocator(SecretsConfigProperties properties, SecretsCache cache) { this.properties = properties; this.cache = cache; } @Override public PropertySource<?> locate(Environment environment) { if (environment instanceof ConfigurableEnvironment env) { List<NormalizedSource> sources = this.properties.determineSources(environment); Set<NormalizedSource> uniqueSources = new HashSet<>(sources); LOG.debug("Secrets normalized sources : " + sources); CompositePropertySource composite = new CompositePropertySource("composite-secrets"); // read for secrets mount putPathConfig(composite); if (this.properties.enableApi()) { uniqueSources .forEach(s -> composite.addPropertySource(getSecretsPropertySourceForSingleSecret(env, s))); } cache.discardAll(); return composite; } return null; } @Override public Collection<PropertySource<?>> locateCollection(Environment environment) { return PropertySourceLocator.super.locateCollection(environment); } private SecretsPropertySource getSecretsPropertySourceForSingleSecret(ConfigurableEnvironment environment, NormalizedSource normalizedSource) { return getPropertySource(environment, normalizedSource); } protected abstract SecretsPropertySource getPropertySource(ConfigurableEnvironment environment, NormalizedSource normalizedSource); protected void putPathConfig(CompositePropertySource composite) {<FILL_FUNCTION_BODY>} /** * @author wind57 */ private static class SecretsPropertySourceCollector implements Collector<Path, List<SecretsPropertySource>, List<SecretsPropertySource>> { @Override public Supplier<List<SecretsPropertySource>> supplier() { return ArrayList::new; } @Override public BiConsumer<List<SecretsPropertySource>, Path> accumulator() { return (list, filePath) -> { SecretsPropertySource source = property(filePath); if (source != null) { list.add(source); } }; } @Override public BinaryOperator<List<SecretsPropertySource>> combiner() { return (left, right) -> { left.addAll(right); return left; }; } @Override public Function<List<SecretsPropertySource>, List<SecretsPropertySource>> finisher() { return Function.identity(); } @Override public Set<Characteristics> characteristics() { return EnumSet.of(Characteristics.UNORDERED, Characteristics.IDENTITY_FINISH); } private SecretsPropertySource property(Path filePath) { String fileName = filePath.getFileName().toString(); try { String content = new String(Files.readAllBytes(filePath)).trim(); String sourceName = fileName.toLowerCase(); SourceData sourceData = new SourceData(sourceName, Collections.singletonMap(fileName, content)); return new SecretsPropertySource(sourceData); } catch (IOException e) { LOG.warn("Error reading properties file", e); return null; } } } }
if (!properties.paths().isEmpty()) { LOG.warn( "path support is deprecated and will be removed in a future release. Please use spring.config.import"); } this.properties.paths().stream().map(Paths::get).filter(Files::exists).flatMap(x -> { try { return Files.walk(x); } catch (IOException e) { LOG.warn("Error walking properties files", e); return null; } }).filter(Objects::nonNull).filter(Files::isRegularFile).collect(new SecretsPropertySourceCollector()) .forEach(composite::addPropertySource);
977
171
1,148
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/SourceDataEntriesProcessor.java
SourceDataEntriesProcessor
extractProperties
class SourceDataEntriesProcessor extends MapPropertySource { private static final Log LOG = LogFactory.getLog(SourceDataEntriesProcessor.class); private static Predicate<String> ENDS_IN_EXTENSION = x -> x.endsWith(".yml") || x.endsWith(".yaml") || x.endsWith(".properties"); public SourceDataEntriesProcessor(SourceData sourceData) { super(sourceData.sourceName(), sourceData.sourceData()); } public static Map<String, Object> processAllEntries(Map<String, String> input, Environment environment) { return processAllEntries(input, environment, true); } public static Map<String, Object> processAllEntries(Map<String, String> input, Environment environment, boolean includeDefaultProfileData) { Set<Map.Entry<String, String>> entrySet = input.entrySet(); if (entrySet.size() == 1) { // we handle the case where the configmap contains a single "file" // in this case we don't care what the name of the file is Map.Entry<String, String> singleEntry = entrySet.iterator().next(); String propertyName = singleEntry.getKey(); String propertyValue = singleEntry.getValue(); if (propertyName.endsWith(".yml") || propertyName.endsWith(".yaml")) { LOG.debug("The single property with name: [" + propertyName + "] will be treated as a yaml file"); return yamlParserGenerator(environment).andThen(PROPERTIES_TO_MAP).apply(propertyValue); } else if (propertyName.endsWith(".properties")) { LOG.debug("The single property with name: [" + propertyName + "] will be treated as a properties file"); return KEY_VALUE_TO_PROPERTIES.andThen(PROPERTIES_TO_MAP).apply(propertyValue); } } return defaultProcessAllEntries(input, environment, includeDefaultProfileData); } static List<Map.Entry<String, String>> sorted(Map<String, String> input, Environment environment) { return sorted(input, environment, true); } /** * <pre> * we want to sort entries coming from the k8s source in a specific way: * * 1. "application.yaml/yml/properties" have to come first * (or the value from spring.application.name) * 2. then profile specific entries, like "application-dev.yaml" * 3. then plain properties * </pre> */ static List<Map.Entry<String, String>> sorted(Map<String, String> rawData, Environment environment, boolean includeDefaultProfileData) { record WeightedEntry(Map.Entry<String, String> entry, int weight) { } // we pass empty Strings on purpose, the logic here is either the value of // "spring.application.name" or literal "application". String applicationName = ConfigUtils.getApplicationName(environment, "", ""); String[] activeProfiles = environment.getActiveProfiles(); // In some cases we want to include the properties from the default profile along // with any properties from any active profiles // In this case includeDefaultProfileData will be true or the active profile will // be default // In the case where includeDefaultProfileData is false we only want to include // the properties from the active profiles boolean includeDataEntry = includeDefaultProfileData || Arrays.asList(environment.getActiveProfiles()).contains("default"); // the order here is important, first has to come "application.yaml" and then // "application-dev.yaml" List<String> orderedFileNames = new ArrayList<>(); if (includeDataEntry) { orderedFileNames.add(applicationName); } orderedFileNames.addAll(Arrays.stream(activeProfiles).map(profile -> applicationName + "-" + profile).toList()); int current = orderedFileNames.size() - 1; List<WeightedEntry> weightedEntries = new ArrayList<>(); boolean plainEntriesOnly = rawData.keySet().stream().noneMatch(ENDS_IN_EXTENSION); if (plainEntriesOnly) { for (Map.Entry<String, String> entry : rawData.entrySet()) { weightedEntries.add(new WeightedEntry(entry, ++current)); } } else { for (Map.Entry<String, String> entry : rawData.entrySet()) { String key = entry.getKey(); if (ENDS_IN_EXTENSION.test(key)) { String withoutExtension = key.split("\\.", 2)[0]; int index = orderedFileNames.indexOf(withoutExtension); if (index >= 0) { weightedEntries.add(new WeightedEntry(entry, index)); } else { LOG.warn("entry : " + key + " will be skipped"); } } else { if (includeDataEntry) { weightedEntries.add(new WeightedEntry(entry, ++current)); } } } } return weightedEntries.stream().sorted(Comparator.comparing(WeightedEntry::weight)).map(WeightedEntry::entry) .toList(); } private static Map<String, Object> defaultProcessAllEntries(Map<String, String> input, Environment environment, boolean includeDefaultProfile) { List<Map.Entry<String, String>> sortedEntries = sorted(input, environment, includeDefaultProfile); Map<String, Object> result = new HashMap<>(); for (Map.Entry<String, String> entry : sortedEntries) { result.putAll(extractProperties(entry.getKey(), entry.getValue(), environment)); } return result; } private static Map<String, Object> extractProperties(String resourceName, String content, Environment environment) {<FILL_FUNCTION_BODY>} }
if (resourceName.endsWith(".yml") || resourceName.endsWith(".yaml") || resourceName.endsWith(".properties")) { if (resourceName.endsWith(".properties")) { LOG.debug("entry : " + resourceName + " will be treated as a single properties file"); return KEY_VALUE_TO_PROPERTIES.andThen(PROPERTIES_TO_MAP).apply(content); } else { LOG.debug("entry : " + resourceName + " will be treated as a single yml/yaml file"); return yamlParserGenerator(environment).andThen(PROPERTIES_TO_MAP).apply(content); } } return Collections.singletonMap(resourceName, content);
1,516
186
1,702
<methods>public void <init>(java.lang.String, Map<java.lang.String,java.lang.Object>) ,public boolean containsProperty(java.lang.String) ,public java.lang.Object getProperty(java.lang.String) ,public java.lang.String[] getPropertyNames() <variables>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/ConfigReloadAutoConfiguration.java
ConfigReloadAutoConfiguration
configurationUpdateStrategy
class ConfigReloadAutoConfiguration { @Bean("springCloudKubernetesTaskScheduler") @ConditionalOnMissingBean public TaskSchedulerWrapper<TaskScheduler> taskScheduler() { ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler(); threadPoolTaskScheduler.setThreadNamePrefix("spring-cloud-kubernetes-ThreadPoolTaskScheduler-"); threadPoolTaskScheduler.setDaemon(true); return new TaskSchedulerWrapper<>(threadPoolTaskScheduler); } @Bean @ConditionalOnMissingBean public ConfigurationUpdateStrategy configurationUpdateStrategy(ConfigReloadProperties properties, ConfigurableApplicationContext ctx, Optional<RestartEndpoint> restarter, ContextRefresher refresher) {<FILL_FUNCTION_BODY>} private static void wait(ConfigReloadProperties properties) { long waitMillis = ThreadLocalRandom.current().nextLong(properties.maxWaitForRestart().toMillis()); try { Thread.sleep(waitMillis); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); } } }
String strategyName = properties.strategy().name(); return switch (properties.strategy()) { case RESTART_CONTEXT -> { restarter.orElseThrow(() -> new AssertionError("Restart endpoint is not enabled")); yield new ConfigurationUpdateStrategy(strategyName, () -> { wait(properties); restarter.get().restart(); }); } case REFRESH -> new ConfigurationUpdateStrategy(strategyName, refresher::refresh); case SHUTDOWN -> new ConfigurationUpdateStrategy(strategyName, () -> { wait(properties); ctx.close(); }); };
286
171
457
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/ConfigReloadUtil.java
ConfigReloadUtil
changed
class ConfigReloadUtil { private ConfigReloadUtil() { } private static final LogAccessor LOG = new LogAccessor(LogFactory.getLog(ConfigReloadUtil.class)); public static boolean reload(String target, String eventSourceType, PropertySourceLocator locator, ConfigurableEnvironment environment, Class<? extends MapPropertySource> existingSourcesType) { LOG.debug(() -> "onEvent " + target + ": " + eventSourceType); List<? extends MapPropertySource> sourceFromK8s = locateMapPropertySources(locator, environment); List<? extends MapPropertySource> existingSources = findPropertySources(existingSourcesType, environment); boolean changed = changed(sourceFromK8s, existingSources); if (changed) { LOG.info("Detected change in config maps/secrets"); return true; } else { LOG.debug("No change detected in config maps/secrets, reload will not happen"); } return false; } /** * @param <S> property source type * @param sourceClass class for which property sources will be found * @return finds all registered property sources of the given type */ public static <S extends PropertySource<?>> List<S> findPropertySources(Class<S> sourceClass, ConfigurableEnvironment environment) { List<S> managedSources = new ArrayList<>(); List<PropertySource<?>> sources = environment.getPropertySources().stream() .collect(Collectors.toCollection(ArrayList::new)); LOG.debug(() -> "environment from findPropertySources: " + environment); LOG.debug(() -> "environment sources from findPropertySources : " + sources); while (!sources.isEmpty()) { PropertySource<?> source = sources.remove(0); if (source instanceof CompositePropertySource comp) { sources.addAll(comp.getPropertySources()); } else if (sourceClass.isInstance(source)) { managedSources.add(sourceClass.cast(source)); } else if (source instanceof MountConfigMapPropertySource mountConfigMapPropertySource) { // we know that the type is correct here managedSources.add((S) mountConfigMapPropertySource); } else if (source instanceof BootstrapPropertySource<?> bootstrapPropertySource) { PropertySource<?> propertySource = bootstrapPropertySource.getDelegate(); LOG.debug(() -> "bootstrap delegate class : " + propertySource.getClass()); if (sourceClass.isInstance(propertySource)) { sources.add(propertySource); } else if (propertySource instanceof MountConfigMapPropertySource mountConfigMapPropertySource) { // we know that the type is correct here managedSources.add((S) mountConfigMapPropertySource); } } } LOG.debug(() -> "findPropertySources : " + managedSources.stream().map(PropertySource::getName).toList()); return managedSources; } /** * Returns a list of MapPropertySource that correspond to the current state of the * system. This only handles the PropertySource objects that are returned. * @param propertySourceLocator Spring's property source locator * @param environment Spring environment * @return a list of MapPropertySource that correspond to the current state of the * system */ static List<MapPropertySource> locateMapPropertySources(PropertySourceLocator propertySourceLocator, ConfigurableEnvironment environment) { List<MapPropertySource> result = new ArrayList<>(); PropertySource<?> propertySource = propertySourceLocator.locate(environment); if (propertySource instanceof MapPropertySource mapPropertySource) { result.add(mapPropertySource); } else if (propertySource instanceof CompositePropertySource source) { source.getPropertySources().forEach(x -> { if (x instanceof MapPropertySource mapPropertySource) { result.add(mapPropertySource); } }); } else { LOG.debug(() -> "Found property source that cannot be handled: " + propertySource.getClass()); } LOG.debug(() -> "environment from locateMapPropertySources : " + environment); LOG.debug(() -> "sources from locateMapPropertySources : " + result); return result; } static boolean changed(List<? extends MapPropertySource> left, List<? extends MapPropertySource> right) {<FILL_FUNCTION_BODY>} /** * Determines if two property sources are different. * @param left left map property sources * @param right right map property sources * @return {@code true} if source has changed */ static boolean changed(MapPropertySource left, MapPropertySource right) { if (left == right) { return false; } if (left == null || right == null) { return true; } Map<String, Object> leftMap = left.getSource(); Map<String, Object> rightMap = right.getSource(); return !Objects.equals(leftMap, rightMap); } }
if (left.size() != right.size()) { if (LOG.isDebugEnabled()) { LOG.debug("left size: " + left.size()); left.forEach(item -> LOG.debug(item.toString())); LOG.debug("right size: " + right.size()); right.forEach(item -> LOG.debug(item.toString())); } LOG.warn(() -> "The current number of ConfigMap PropertySources does not match " + "the ones loaded from Kubernetes - No reload will take place"); return false; } for (int i = 0; i < left.size(); i++) { MapPropertySource leftPropertySource = left.get(i); MapPropertySource rightPropertySource = right.get(i); if (changed(leftPropertySource, rightPropertySource)) { LOG.debug(() -> "found change in : " + leftPropertySource); return true; } } LOG.debug(() -> "no changes found, reload will not happen"); return false;
1,310
274
1,584
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/ConfigurationChangeDetector.java
ConfigurationChangeDetector
reloadProperties
class ConfigurationChangeDetector { private static final LogAccessor LOG = new LogAccessor(LogFactory.getLog(ConfigurationChangeDetector.class)); protected ConfigurableEnvironment environment; protected ConfigReloadProperties properties; protected ConfigurationUpdateStrategy strategy; public ConfigurationChangeDetector(ConfigurableEnvironment environment, ConfigReloadProperties properties, ConfigurationUpdateStrategy strategy) { this.environment = Objects.requireNonNull(environment); this.properties = Objects.requireNonNull(properties); this.strategy = Objects.requireNonNull(strategy); } public void reloadProperties() {<FILL_FUNCTION_BODY>} }
LOG.info(() -> "Reloading using strategy: " + this.strategy.name()); strategy.reloadProcedure().run();
164
41
205
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/PollingConfigMapChangeDetector.java
PollingConfigMapChangeDetector
executeCycle
class PollingConfigMapChangeDetector extends ConfigurationChangeDetector { protected Log log = LogFactory.getLog(getClass()); private final PropertySourceLocator propertySourceLocator; private final Class<? extends MapPropertySource> propertySourceClass; private final TaskScheduler taskExecutor; private final long period; private final boolean monitorConfigMaps; public PollingConfigMapChangeDetector(AbstractEnvironment environment, ConfigReloadProperties properties, ConfigurationUpdateStrategy strategy, Class<? extends MapPropertySource> propertySourceClass, PropertySourceLocator propertySourceLocator, TaskScheduler taskExecutor) { super(environment, properties, strategy); this.propertySourceLocator = propertySourceLocator; this.propertySourceClass = propertySourceClass; this.taskExecutor = taskExecutor; this.period = properties.period().toMillis(); this.monitorConfigMaps = properties.monitoringConfigMaps(); } @PostConstruct private void init() { log.info("Kubernetes polling configMap change detector activated"); PeriodicTrigger trigger = new PeriodicTrigger(Duration.ofMillis(period)); trigger.setInitialDelay(Duration.ofMillis(period)); taskExecutor.schedule(this::executeCycle, trigger); } private void executeCycle() {<FILL_FUNCTION_BODY>} }
boolean changedConfigMap = false; if (monitorConfigMaps) { log.debug("Polling for changes in config maps"); List<? extends MapPropertySource> currentConfigMapSources = findPropertySources(propertySourceClass, environment); if (!currentConfigMapSources.isEmpty()) { changedConfigMap = changed(locateMapPropertySources(this.propertySourceLocator, this.environment), currentConfigMapSources); } } if (changedConfigMap) { log.info("Detected change in config maps"); reloadProperties(); }
339
160
499
<methods>public void <init>(org.springframework.core.env.ConfigurableEnvironment, ConfigReloadProperties, ConfigurationUpdateStrategy) ,public void reloadProperties() <variables>private static final org.springframework.core.log.LogAccessor LOG,protected org.springframework.core.env.ConfigurableEnvironment environment,protected ConfigReloadProperties properties,protected ConfigurationUpdateStrategy strategy
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/PollingSecretsChangeDetector.java
PollingSecretsChangeDetector
executeCycle
class PollingSecretsChangeDetector extends ConfigurationChangeDetector { protected Log log = LogFactory.getLog(getClass()); private final PropertySourceLocator propertySourceLocator; private final Class<? extends MapPropertySource> propertySourceClass; private final TaskScheduler taskExecutor; private final long period; private final boolean monitorSecrets; public PollingSecretsChangeDetector(AbstractEnvironment environment, ConfigReloadProperties properties, ConfigurationUpdateStrategy strategy, Class<? extends MapPropertySource> propertySourceClass, PropertySourceLocator propertySourceLocator, TaskScheduler taskExecutor) { super(environment, properties, strategy); this.propertySourceLocator = propertySourceLocator; this.propertySourceClass = propertySourceClass; this.taskExecutor = taskExecutor; this.period = properties.period().toMillis(); this.monitorSecrets = properties.monitoringSecrets(); } @PostConstruct private void init() { log.info("Kubernetes polling secrets change detector activated"); PeriodicTrigger trigger = new PeriodicTrigger(Duration.ofMillis(period)); trigger.setInitialDelay(Duration.ofMillis(period)); taskExecutor.schedule(this::executeCycle, trigger); } private void executeCycle() {<FILL_FUNCTION_BODY>} }
boolean changedSecrets = false; if (monitorSecrets) { log.debug("Polling for changes in secrets"); List<MapPropertySource> currentSecretSources = locateMapPropertySources(this.propertySourceLocator, this.environment); if (!currentSecretSources.isEmpty()) { List<? extends MapPropertySource> propertySources = findPropertySources(propertySourceClass, environment); changedSecrets = changed(currentSecretSources, propertySources); } } if (changedSecrets) { log.info("Detected change in secrets"); reloadProperties(); }
335
168
503
<methods>public void <init>(org.springframework.core.env.ConfigurableEnvironment, ConfigReloadProperties, ConfigurationUpdateStrategy) ,public void reloadProperties() <variables>private static final org.springframework.core.log.LogAccessor LOG,protected org.springframework.core.env.ConfigurableEnvironment environment,protected ConfigReloadProperties properties,protected ConfigurationUpdateStrategy strategy
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/condition/EventReloadDetectionMode.java
EventReloadDetectionMode
matches
class EventReloadDetectionMode implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {<FILL_FUNCTION_BODY>} }
Environment environment = context.getEnvironment(); if (!environment.containsProperty(Constants.RELOAD_MODE)) { return true; } return ConfigReloadProperties.ReloadDetectionMode.EVENT.name() .equalsIgnoreCase(environment.getProperty(Constants.RELOAD_MODE));
47
76
123
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/config/reload/condition/PollingReloadDetectionMode.java
PollingReloadDetectionMode
matches
class PollingReloadDetectionMode implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {<FILL_FUNCTION_BODY>} }
Environment environment = context.getEnvironment(); if (!environment.containsProperty(Constants.RELOAD_MODE)) { return false; } return ConfigReloadProperties.ReloadDetectionMode.POLLING.name() .equalsIgnoreCase(environment.getProperty(Constants.RELOAD_MODE));
48
78
126
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/discovery/KubernetesDiscoveryClientHealthIndicatorInitializer.java
KubernetesDiscoveryClientHealthIndicatorInitializer
postConstruct
class KubernetesDiscoveryClientHealthIndicatorInitializer { private static final LogAccessor LOG = new LogAccessor( LogFactory.getLog(KubernetesDiscoveryClientHealthIndicatorInitializer.class)); private final PodUtils<?> podUtils; private final ApplicationEventPublisher applicationEventPublisher; public KubernetesDiscoveryClientHealthIndicatorInitializer(PodUtils<?> podUtils, ApplicationEventPublisher applicationEventPublisher) { this.podUtils = podUtils; this.applicationEventPublisher = applicationEventPublisher; } @PostConstruct private void postConstruct() {<FILL_FUNCTION_BODY>} /** * @param cloudPlatform "kubernetes" always * @param inside inside kubernetes or not * @param pod an actual pod or null, if we are outside kubernetes */ public record RegisteredEventSource(String cloudPlatform, boolean inside, Object pod) { } }
LOG.debug(() -> "publishing InstanceRegisteredEvent"); InstanceRegisteredEvent<RegisteredEventSource> instanceRegisteredEvent = new InstanceRegisteredEvent<>( new RegisteredEventSource("kubernetes", podUtils.isInsideKubernetes(), podUtils.currentPod().get()), null); applicationEventPublisher.publishEvent(instanceRegisteredEvent);
241
100
341
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/discovery/ServicePortSecureResolver.java
ServicePortSecureResolver
resolve
class ServicePortSecureResolver { private static final LogAccessor LOG = new LogAccessor(LogFactory.getLog(ServicePortSecureResolver.class)); private static final Set<String> TRUTHY_STRINGS = Set.of("true", "on", "yes", "1"); private final KubernetesDiscoveryProperties properties; public ServicePortSecureResolver(KubernetesDiscoveryProperties properties) { this.properties = properties; } /** * <p> * Returns true if any of the following conditions apply. * <p> * <ul> * <li>service contains a label named 'secured' that is truthy</li> * <li>service contains an annotation named 'secured' that is truthy</li> * <li>the port is one of the known ports used for secure communication</li> * </ul> * */ public boolean resolve(Input input) {<FILL_FUNCTION_BODY>} private static void logEntry(String serviceName, Integer port, String reason) { LOG.debug(() -> "Considering service with name: " + serviceName + " and port " + port + " to be secure since " + reason); } /** * @author wind57 */ public record Input(ServicePortNameAndNumber portData, String serviceName, Map<String, String> serviceLabels, Map<String, String> serviceAnnotations) { public Input(ServicePortNameAndNumber portData, String serviceName, Map<String, String> serviceLabels, Map<String, String> serviceAnnotations) { this.portData = portData; this.serviceName = serviceName; this.serviceLabels = serviceLabels == null ? Map.of() : serviceLabels; this.serviceAnnotations = serviceAnnotations == null ? Map.of() : serviceAnnotations; } } }
String serviceName = input.serviceName(); ServicePortNameAndNumber portData = input.portData(); Integer portNumber = portData.portNumber(); Optional<String> securedLabelValue = Optional.ofNullable(input.serviceLabels().get(SECURED)); if (securedLabelValue.isPresent() && TRUTHY_STRINGS.contains(securedLabelValue.get())) { logEntry(serviceName, portData.portNumber(), "the service contains a true value for the 'secured' label"); return true; } Optional<String> securedAnnotationValue = Optional.ofNullable(input.serviceAnnotations().get(SECURED)); if (securedAnnotationValue.isPresent() && TRUTHY_STRINGS.contains(securedAnnotationValue.get())) { logEntry(serviceName, portData.portNumber(), "the service contains a true value for the 'secured' annotation"); return true; } if (portNumber != null && properties.knownSecurePorts().contains(portData.portNumber())) { logEntry(serviceName, portData.portNumber(), "port is known to be a https port"); return true; } if ("https".equalsIgnoreCase(input.portData().portName())) { logEntry(serviceName, portData.portNumber(), "port-name is 'https'"); return true; } return false;
476
362
838
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/leader/Leader.java
Leader
isCandidate
class Leader { private final String role; private final String id; public Leader(String role, String id) { this.role = role; this.id = id; } public String getRole() { return this.role; } public String getId() { return this.id; } public boolean isCandidate(Candidate candidate) {<FILL_FUNCTION_BODY>} @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Leader leader = (Leader) o; return Objects.equals(this.role, leader.role) && Objects.equals(this.id, leader.id); } @Override public int hashCode() { return Objects.hash(this.role, this.id); } @Override public String toString() { return String.format("Leader{role='%s', id='%s'}", this.role, this.id); } }
if (candidate == null) { return false; } return Objects.equals(role, candidate.getRole()) && Objects.equals(id, candidate.getId());
290
49
339
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/leader/LeaderInfoContributor.java
LeaderInfoContributor
contribute
class LeaderInfoContributor implements InfoContributor { private final LeadershipController leadershipController; private final Candidate candidate; public LeaderInfoContributor(LeadershipController leadershipController, Candidate candidate) { this.leadershipController = leadershipController; this.candidate = candidate; } @Override public void contribute(Builder builder) {<FILL_FUNCTION_BODY>} }
Map<String, Object> details = new HashMap<>(); leadershipController.getLocalLeader().ifPresentOrElse(leader -> { details.put("leaderId", leader.getId()); details.put("role", leader.getRole()); details.put("isLeader", leader.isCandidate(candidate)); }, () -> details.put("leaderId", "Unknown")); builder.withDetail("leaderElection", details);
103
124
227
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/leader/LeaderInitiator.java
LeaderInitiator
stop
class LeaderInitiator implements SmartLifecycle { private static final Logger LOGGER = LoggerFactory.getLogger(LeaderInitiator.class); private final LeaderProperties leaderProperties; private final LeadershipController leadershipController; private final LeaderRecordWatcher leaderRecordWatcher; private final PodReadinessWatcher hostPodWatcher; private ScheduledExecutorService scheduledExecutorService; private boolean isRunning; public LeaderInitiator(LeaderProperties leaderProperties, LeadershipController leadershipController, LeaderRecordWatcher leaderRecordWatcher, PodReadinessWatcher hostPodWatcher) { this.leaderProperties = leaderProperties; this.leadershipController = leadershipController; this.leaderRecordWatcher = leaderRecordWatcher; this.hostPodWatcher = hostPodWatcher; } @Override public boolean isAutoStartup() { return this.leaderProperties.isAutoStartup(); } @Override public void start() { if (!isRunning()) { LOGGER.debug("Leader initiator starting"); this.leaderRecordWatcher.start(); this.hostPodWatcher.start(); this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); this.scheduledExecutorService.scheduleAtFixedRate(this.leadershipController::update, this.leaderProperties.getUpdatePeriod().toMillis(), this.leaderProperties.getUpdatePeriod().toMillis(), TimeUnit.MILLISECONDS); this.isRunning = true; } } @Override public void stop() {<FILL_FUNCTION_BODY>} @Override public void stop(Runnable callback) { stop(); callback.run(); } @Override public boolean isRunning() { return this.isRunning; } @Override public int getPhase() { return 0; } }
if (isRunning()) { LOGGER.debug("Leader initiator stopping"); this.scheduledExecutorService.shutdown(); this.scheduledExecutorService = null; this.hostPodWatcher.stop(); this.leaderRecordWatcher.stop(); this.leadershipController.revoke(); this.isRunning = false; }
494
96
590
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/leader/LeaderProperties.java
LeaderProperties
getNamespace
class LeaderProperties { /** * Should leader election be enabled. Default: true */ private boolean enabled = true; /** * Should leader election be started automatically on startup. Default: true */ private boolean autoStartup = true; /** * Role for which leadership this candidate will compete. */ private String role; /** * Kubernetes namespace where the leaders ConfigMap and candidates are located. */ private String namespace; /** * Kubernetes ConfigMap where leaders information will be stored. Default: leaders */ private String configMapName = "leaders"; /** * Leader id property prefix for the ConfigMap. Default: leader.id. */ private String leaderIdPrefix = "leader.id."; /** * Leadership status check period. Default: 60s */ private Duration updatePeriod = Duration.ofMillis(60000); /** * Enable/disable publishing events in case leadership acquisition fails. Default: * false */ private boolean publishFailedEvents = false; /** * Enable/disable creating ConfigMap if it does not exist. Default: true */ private boolean createConfigMap = true; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isAutoStartup() { return autoStartup; } public void setAutoStartup(boolean autoStartup) { this.autoStartup = autoStartup; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public String getNamespace(String defaultValue) {<FILL_FUNCTION_BODY>} public String getConfigMapName() { return configMapName; } public void setConfigMapName(String configMapName) { this.configMapName = configMapName; } public String getLeaderIdPrefix() { return leaderIdPrefix; } public void setLeaderIdPrefix(String leaderIdPrefix) { this.leaderIdPrefix = leaderIdPrefix; } public Duration getUpdatePeriod() { return updatePeriod; } public void setUpdatePeriod(Duration updatePeriod) { this.updatePeriod = updatePeriod; } public boolean isPublishFailedEvents() { return publishFailedEvents; } public void setPublishFailedEvents(boolean publishFailedEvents) { this.publishFailedEvents = publishFailedEvents; } public boolean isCreateConfigMap() { return createConfigMap; } public void setCreateConfigMap(boolean createConfigMap) { this.createConfigMap = createConfigMap; } }
if (namespace == null || namespace.isEmpty()) { return defaultValue; } return namespace;
720
31
751
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/leader/LeaderUtils.java
LeaderUtils
hostName
class LeaderUtils { // k8s environment variable responsible for host name private static final String HOSTNAME = "HOSTNAME"; private LeaderUtils() { } public static String hostName() throws UnknownHostException {<FILL_FUNCTION_BODY>} }
String hostName = EnvReader.getEnv(HOSTNAME); if (StringUtils.hasText(hostName)) { return hostName; } else { return InetAddress.getLocalHost().getHostName(); }
71
65
136
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/leader/LeadershipController.java
LeadershipController
handleLeaderChange
class LeadershipController { private static final Logger LOGGER = LoggerFactory.getLogger(LeadershipController.class); protected static final String PROVIDER_KEY = "provider"; protected static final String PROVIDER = "spring-cloud-kubernetes"; protected static final String KIND_KEY = "kind"; protected static final String KIND = "leaders"; protected Candidate candidate; protected Leader localLeader; protected LeaderProperties leaderProperties; protected LeaderEventPublisher leaderEventPublisher; protected PodReadinessWatcher leaderReadinessWatcher; public LeadershipController(Candidate candidate, LeaderProperties leaderProperties, LeaderEventPublisher leaderEventPublisher) { this.candidate = candidate; this.leaderProperties = leaderProperties; this.leaderEventPublisher = leaderEventPublisher; } public Optional<Leader> getLocalLeader() { return Optional.ofNullable(this.localLeader); } public abstract void update(); public abstract void revoke(); protected String getLeaderKey() { return this.leaderProperties.getLeaderIdPrefix() + this.candidate.getRole(); } protected Map<String, String> getLeaderData(Candidate candidate) { String leaderKey = getLeaderKey(); return Collections.singletonMap(leaderKey, candidate.getId()); } protected Leader extractLeader(Map<String, String> data) { if (data == null) { return null; } String leaderKey = getLeaderKey(); String leaderId = data.get(leaderKey); if (!StringUtils.hasText(leaderId)) { return null; } return new Leader(this.candidate.getRole(), leaderId); } protected void handleLeaderChange(Leader newLeader) {<FILL_FUNCTION_BODY>} protected void notifyOnGranted() { LOGGER.debug("Leadership has been granted for '{}'", this.candidate); Context context = new LeaderContext(this.candidate, this); this.leaderEventPublisher.publishOnGranted(this, context, this.candidate.getRole()); try { this.candidate.onGranted(context); } catch (InterruptedException e) { LOGGER.warn(e.getMessage()); Thread.currentThread().interrupt(); } } protected void notifyOnRevoked() { LOGGER.debug("Leadership has been revoked for '{}'", this.candidate); Context context = new LeaderContext(this.candidate, this); this.leaderEventPublisher.publishOnRevoked(this, context, this.candidate.getRole()); this.candidate.onRevoked(context); } protected void notifyOnFailedToAcquire() { if (this.leaderProperties.isPublishFailedEvents()) { Context context = new LeaderContext(this.candidate, this); this.leaderEventPublisher.publishOnFailedToAcquire(this, context, this.candidate.getRole()); } } protected void restartLeaderReadinessWatcher() { if (this.leaderReadinessWatcher != null) { this.leaderReadinessWatcher.stop(); this.leaderReadinessWatcher = null; } if (this.localLeader != null && !this.localLeader.isCandidate(this.candidate)) { this.leaderReadinessWatcher = createPodReadinessWatcher(this.localLeader.getId()); this.leaderReadinessWatcher.start(); } } protected abstract PodReadinessWatcher createPodReadinessWatcher(String localLeaderId); }
if (Objects.equals(this.localLeader, newLeader)) { LOGGER.debug("Leader is still '{}'", this.localLeader); return; } Leader oldLeader = this.localLeader; this.localLeader = newLeader; if (oldLeader != null && oldLeader.isCandidate(this.candidate)) { notifyOnRevoked(); } else if (newLeader != null && newLeader.isCandidate(this.candidate)) { notifyOnGranted(); } restartLeaderReadinessWatcher(); LOGGER.debug("New leader is '{}'", this.localLeader);
980
189
1,169
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-commons/src/main/java/org/springframework/cloud/kubernetes/commons/profile/AbstractKubernetesProfileEnvironmentPostProcessor.java
AbstractKubernetesProfileEnvironmentPostProcessor
addNamespaceFromServiceAccountFile
class AbstractKubernetesProfileEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { private static final DeferredLog LOG = new DeferredLog(); private static final String NAMESPACE_PATH_PROPERTY = "spring.cloud.kubernetes.client.serviceAccountNamespacePath"; protected static final String NAMESPACE_PROPERTY = "spring.cloud.kubernetes.client.namespace"; private static final String PROPERTY_SOURCE_NAME = "KUBERNETES_NAMESPACE_PROPERTY_SOURCE"; // Before ConfigFileApplicationListener so values there can use these ones private static final int ORDER = ConfigDataEnvironmentPostProcessor.ORDER - 1; /** * Profile name. */ public static final String KUBERNETES_PROFILE = "kubernetes"; @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { application.addInitializers(ctx -> LOG.replayTo(AbstractKubernetesProfileEnvironmentPostProcessor.class)); if (CloudPlatform.KUBERNETES.isActive(environment)) { addNamespaceFromServiceAccountFile(environment); addKubernetesProfileIfMissing(environment); } } protected abstract boolean isInsideKubernetes(Environment environment); private boolean hasKubernetesProfile(Environment environment) { return Arrays.stream(environment.getActiveProfiles()).anyMatch(KUBERNETES_PROFILE::equalsIgnoreCase); } @Override public int getOrder() { return ORDER; } private void addKubernetesProfileIfMissing(ConfigurableEnvironment environment) { if (isInsideKubernetes(environment)) { if (hasKubernetesProfile(environment)) { LOG.debug("'kubernetes' already in list of active profiles"); } else { LOG.debug("Adding 'kubernetes' to list of active profiles"); environment.addActiveProfile(KUBERNETES_PROFILE); } } else { LOG.warn("Not running inside kubernetes. Skipping 'kubernetes' profile activation."); } } private void addNamespaceFromServiceAccountFile(ConfigurableEnvironment environment) {<FILL_FUNCTION_BODY>} }
String serviceAccountNamespacePathString = environment.getProperty(NAMESPACE_PATH_PROPERTY, SERVICE_ACCOUNT_NAMESPACE_PATH); String namespace = KubernetesNamespaceProvider .getNamespaceFromServiceAccountFile(serviceAccountNamespacePathString); if (StringUtils.hasText(namespace)) { environment.getPropertySources().addLast(new MapPropertySource(PROPERTY_SOURCE_NAME, Collections.singletonMap(NAMESPACE_PROPERTY, namespace))); }
556
134
690
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/main/java/org/springframework/cloud/kubernetes/configserver/KubernetesConfigServerAutoConfiguration.java
KubernetesConfigServerAutoConfiguration
configMapPropertySourceSupplier
class KubernetesConfigServerAutoConfiguration { @Bean @Profile("kubernetes") public EnvironmentRepository kubernetesEnvironmentRepository(CoreV1Api coreV1Api, List<KubernetesPropertySourceSupplier> kubernetesPropertySourceSuppliers, KubernetesNamespaceProvider kubernetesNamespaceProvider) { return new KubernetesEnvironmentRepository(coreV1Api, kubernetesPropertySourceSuppliers, kubernetesNamespaceProvider.getNamespace()); } @Bean @ConditionalOnKubernetesConfigEnabled @ConditionalOnProperty(value = "spring.cloud.kubernetes.config.enableApi", matchIfMissing = true) public KubernetesPropertySourceSupplier configMapPropertySourceSupplier( KubernetesConfigServerProperties properties) {<FILL_FUNCTION_BODY>} @Bean @ConditionalOnKubernetesSecretsEnabled @ConditionalOnProperty("spring.cloud.kubernetes.secrets.enableApi") public KubernetesPropertySourceSupplier secretsPropertySourceSupplier(KubernetesConfigServerProperties properties) { return (coreApi, applicationName, namespace, springEnv) -> { List<String> namespaces = namespaceSplitter(properties.getSecretsNamespaces(), namespace); List<MapPropertySource> propertySources = new ArrayList<>(); namespaces.forEach(space -> { NormalizedSource source = new NamedSecretNormalizedSource(applicationName, space, false, ConfigUtils.Prefix.DEFAULT, true, true); KubernetesClientConfigContext context = new KubernetesClientConfigContext(coreApi, source, space, springEnv, false); propertySources.add(new KubernetesClientSecretsPropertySource(context)); }); return propertySources; }; } }
return (coreApi, applicationName, namespace, springEnv) -> { List<String> namespaces = namespaceSplitter(properties.getConfigMapNamespaces(), namespace); List<MapPropertySource> propertySources = new ArrayList<>(); namespaces.forEach(space -> { NamedConfigMapNormalizedSource source = new NamedConfigMapNormalizedSource(applicationName, space, false, ConfigUtils.Prefix.DEFAULT, true, true); KubernetesClientConfigContext context = new KubernetesClientConfigContext(coreApi, source, space, springEnv, false); propertySources.add(new KubernetesClientConfigMapPropertySource(context)); }); return propertySources; };
443
186
629
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configserver/src/main/java/org/springframework/cloud/kubernetes/configserver/KubernetesEnvironmentRepository.java
KubernetesEnvironmentRepository
addApplicationConfiguration
class KubernetesEnvironmentRepository implements EnvironmentRepository { private static final Log LOG = LogFactory.getLog(KubernetesEnvironmentRepository.class); private final CoreV1Api coreApi; private final List<KubernetesPropertySourceSupplier> kubernetesPropertySourceSuppliers; private final String namespace; public KubernetesEnvironmentRepository(CoreV1Api coreApi, List<KubernetesPropertySourceSupplier> kubernetesPropertySourceSuppliers, String namespace) { this.coreApi = coreApi; this.kubernetesPropertySourceSuppliers = kubernetesPropertySourceSuppliers; this.namespace = namespace; } @Override public Environment findOne(String application, String profile, String label) { return findOne(application, profile, label, true); } @Override public Environment findOne(String application, String profile, String label, boolean includeOrigin) { if (!StringUtils.hasText(profile)) { profile = "default"; } List<String> profiles = new ArrayList<>(List.of(StringUtils.commaDelimitedListToStringArray(profile))); Collections.reverse(profiles); if (!profiles.contains("default")) { profiles.add("default"); } Environment environment = new Environment(application, profiles.toArray(profiles.toArray(new String[0])), label, null, null); LOG.info("Profiles: " + profile); LOG.info("Application: " + application); LOG.info("Label: " + label); for (String activeProfile : profiles) { try { // This is needed so that when we get the application name in // SourceDataProcessor.sorted that it actually // exists in the Environment StandardEnvironment springEnv = new KubernetesConfigServerEnvironment( createPropertySources(application)); springEnv.setActiveProfiles(activeProfile); if (!"application".equalsIgnoreCase(application)) { addApplicationConfiguration(environment, springEnv, application); } } catch (Exception e) { LOG.warn(e); } } StandardEnvironment springEnv = new KubernetesConfigServerEnvironment(createPropertySources("application")); addApplicationConfiguration(environment, springEnv, "application"); return environment; } private MutablePropertySources createPropertySources(String application) { Map<String, Object> applicationProperties = Map.of("spring.application.name", application); MapPropertySource propertySource = new MapPropertySource("kubernetes-config-server", applicationProperties); MutablePropertySources mutablePropertySources = new MutablePropertySources(); mutablePropertySources.addFirst(propertySource); return mutablePropertySources; } private void addApplicationConfiguration(Environment environment, StandardEnvironment springEnv, String applicationName) {<FILL_FUNCTION_BODY>} }
kubernetesPropertySourceSuppliers.forEach(supplier -> { List<MapPropertySource> propertySources = supplier.get(coreApi, applicationName, namespace, springEnv); propertySources.forEach(propertySource -> { if (propertySource.getPropertyNames().length > 0) { LOG.debug("Adding PropertySource " + propertySource.getName()); LOG.debug("PropertySource Names: " + StringUtils.arrayToCommaDelimitedString(propertySource.getPropertyNames())); environment.add(new PropertySource(propertySource.getName(), propertySource.getSource())); } }); });
730
163
893
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/main/java/org/springframework/cloud/kubernetes/configuration/watcher/ConfigMapWatcherChangeDetector.java
ConfigMapWatcherChangeDetector
onEvent
class ConfigMapWatcherChangeDetector extends KubernetesClientEventBasedConfigMapChangeDetector implements RefreshTrigger permits BusEventBasedConfigMapWatcherChangeDetector, HttpBasedConfigMapWatchChangeDetector { private final ScheduledExecutorService executorService; private final long refreshDelay; ConfigMapWatcherChangeDetector(CoreV1Api coreV1Api, ConfigurableEnvironment environment, ConfigReloadProperties properties, ConfigurationUpdateStrategy strategy, KubernetesClientConfigMapPropertySourceLocator propertySourceLocator, KubernetesNamespaceProvider kubernetesNamespaceProvider, ConfigurationWatcherConfigurationProperties k8SConfigurationProperties, ThreadPoolTaskExecutor threadPoolTaskExecutor) { super(coreV1Api, environment, properties, strategy, propertySourceLocator, kubernetesNamespaceProvider); this.executorService = Executors.newScheduledThreadPool(k8SConfigurationProperties.getThreadPoolSize(), threadPoolTaskExecutor); this.refreshDelay = k8SConfigurationProperties.getRefreshDelay().toMillis(); } @Override protected final void onEvent(KubernetesObject configMap) {<FILL_FUNCTION_BODY>} }
// this::refreshTrigger is coming from BusEventBasedConfigMapWatcherChangeDetector WatcherUtil.onEvent(configMap, CONFIG_MAP_LABEL, CONFIG_MAP_APPS_ANNOTATION, refreshDelay, executorService, "config-map", this::triggerRefresh);
300
81
381
<methods>public void <init>(io.kubernetes.client.openapi.apis.CoreV1Api, org.springframework.core.env.ConfigurableEnvironment, ConfigReloadProperties, ConfigurationUpdateStrategy, org.springframework.cloud.kubernetes.client.config.KubernetesClientConfigMapPropertySourceLocator, org.springframework.cloud.kubernetes.commons.KubernetesNamespaceProvider) <variables>private static final org.springframework.core.log.LogAccessor LOG,private final non-sealed io.kubernetes.client.openapi.ApiClient apiClient,private final non-sealed io.kubernetes.client.openapi.apis.CoreV1Api coreV1Api,private final non-sealed boolean enableReloadFiltering,private final List<io.kubernetes.client.informer.SharedInformerFactory> factories,private final ResourceEventHandler<io.kubernetes.client.openapi.models.V1ConfigMap> handler,private final List<SharedIndexInformer<io.kubernetes.client.openapi.models.V1ConfigMap>> informers,private final non-sealed Set<java.lang.String> namespaces,private final non-sealed org.springframework.cloud.kubernetes.client.config.KubernetesClientConfigMapPropertySourceLocator propertySourceLocator
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/main/java/org/springframework/cloud/kubernetes/configuration/watcher/ConfigUpdateStrategyAutoConfiguration.java
ConfigUpdateStrategyAutoConfiguration
noopConfigurationUpdateStrategy
class ConfigUpdateStrategyAutoConfiguration { private static final LogAccessor LOG = new LogAccessor( LogFactory.getLog(ConfigUpdateStrategyAutoConfiguration.class)); @Bean @ConditionalOnMissingBean ConfigurationUpdateStrategy noopConfigurationUpdateStrategy() {<FILL_FUNCTION_BODY>} }
LOG.debug(() -> "creating NOOP strategy because reload is disabled"); return ConfigurationUpdateStrategy.NOOP;
78
34
112
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/main/java/org/springframework/cloud/kubernetes/configuration/watcher/ConfigurationWatcherAutoConfiguration.java
ConfigurationWatcherAutoConfiguration
httpBasedConfigMapWatchChangeDetector
class ConfigurationWatcherAutoConfiguration { private static final String AMQP = "bus-amqp"; private static final String KAFKA = "bus-kafka"; @Bean @ConditionalOnMissingBean public WebClient webClient(WebClient.Builder webClientBuilder) { return webClientBuilder.build(); } @Bean @ConditionalOnMissingBean(ConfigMapWatcherChangeDetector.class) @ConditionalOnBean(KubernetesClientConfigMapPropertySourceLocator.class) public ConfigMapWatcherChangeDetector httpBasedConfigMapWatchChangeDetector(AbstractEnvironment environment, CoreV1Api coreV1Api, KubernetesClientConfigMapPropertySourceLocator configMapPropertySourceLocator, ConfigReloadProperties properties, ConfigurationUpdateStrategy strategy, ConfigurationWatcherConfigurationProperties k8SConfigurationProperties, KubernetesNamespaceProvider namespaceProvider, ThreadPoolTaskExecutor threadFactory, HttpRefreshTrigger httpRefreshTrigger) {<FILL_FUNCTION_BODY>} @Bean @ConditionalOnMissingBean @ConditionalOnBean(KubernetesClientSecretsPropertySourceLocator.class) public SecretsWatcherChangeDetector httpBasedSecretsWatchChangeDetector(AbstractEnvironment environment, CoreV1Api coreV1Api, KubernetesClientSecretsPropertySourceLocator secretsPropertySourceLocator, KubernetesNamespaceProvider namespaceProvider, ConfigReloadProperties properties, ConfigurationUpdateStrategy strategy, ConfigurationWatcherConfigurationProperties k8SConfigurationProperties, ThreadPoolTaskExecutor threadFactory, HttpRefreshTrigger httpRefreshTrigger) { return new HttpBasedSecretsWatchChangeDetector(coreV1Api, environment, properties, strategy, secretsPropertySourceLocator, namespaceProvider, k8SConfigurationProperties, threadFactory, httpRefreshTrigger); } @Configuration @Profile(AMQP) @Import({ ContextFunctionCatalogAutoConfiguration.class, RabbitHealthContributorAutoConfiguration.class, RefreshTriggerConfiguration.class }) static class BusRabbitConfiguration { @Bean @ConditionalOnMissingBean(ConfigMapWatcherChangeDetector.class) @ConditionalOnBean(KubernetesClientConfigMapPropertySourceLocator.class) public ConfigMapWatcherChangeDetector busConfigMapChangeWatcher(AbstractEnvironment environment, CoreV1Api coreV1Api, KubernetesClientConfigMapPropertySourceLocator configMapPropertySourceLocator, KubernetesNamespaceProvider kubernetesNamespaceProvider, ConfigReloadProperties properties, ConfigurationUpdateStrategy strategy, ConfigurationWatcherConfigurationProperties k8SConfigurationProperties, ThreadPoolTaskExecutor threadFactory, BusRefreshTrigger busRefreshTrigger) { return new BusEventBasedConfigMapWatcherChangeDetector(coreV1Api, environment, properties, strategy, configMapPropertySourceLocator, kubernetesNamespaceProvider, k8SConfigurationProperties, threadFactory, busRefreshTrigger); } @Bean @ConditionalOnMissingBean(SecretsWatcherChangeDetector.class) @ConditionalOnBean(KubernetesClientSecretsPropertySourceLocator.class) public SecretsWatcherChangeDetector busSecretsChangeWatcher(AbstractEnvironment environment, CoreV1Api coreV1Api, KubernetesClientSecretsPropertySourceLocator secretsPropertySourceLocator, ConfigReloadProperties properties, KubernetesNamespaceProvider kubernetesNamespaceProvider, ConfigurationUpdateStrategy strategy, ConfigurationWatcherConfigurationProperties k8SConfigurationProperties, ThreadPoolTaskExecutor threadFactory, BusRefreshTrigger busRefreshTrigger) { return new BusEventBasedSecretsWatcherChangeDetector(coreV1Api, environment, properties, strategy, secretsPropertySourceLocator, kubernetesNamespaceProvider, k8SConfigurationProperties, threadFactory, busRefreshTrigger); } } @Configuration @Profile(KAFKA) @Import({ ContextFunctionCatalogAutoConfiguration.class, RefreshTriggerConfiguration.class }) static class BusKafkaConfiguration { @Bean @ConditionalOnMissingBean(ConfigMapWatcherChangeDetector.class) @ConditionalOnBean(KubernetesClientConfigMapPropertySourceLocator.class) public ConfigMapWatcherChangeDetector busConfigMapChangeWatcher(AbstractEnvironment environment, CoreV1Api coreV1Api, KubernetesClientConfigMapPropertySourceLocator configMapPropertySourceLocator, ConfigReloadProperties properties, KubernetesNamespaceProvider namespaceProvider, ConfigurationUpdateStrategy strategy, ConfigurationWatcherConfigurationProperties k8SConfigurationProperties, ThreadPoolTaskExecutor threadFactory, BusRefreshTrigger busRefreshTrigger) { return new BusEventBasedConfigMapWatcherChangeDetector(coreV1Api, environment, properties, strategy, configMapPropertySourceLocator, namespaceProvider, k8SConfigurationProperties, threadFactory, busRefreshTrigger); } @Bean @ConditionalOnMissingBean(SecretsWatcherChangeDetector.class) @ConditionalOnBean(KubernetesClientSecretsPropertySourceLocator.class) public SecretsWatcherChangeDetector busSecretsChangeWatcher(AbstractEnvironment environment, CoreV1Api coreV1Api, KubernetesClientSecretsPropertySourceLocator secretsPropertySourceLocator, ConfigReloadProperties properties, ConfigurationUpdateStrategy strategy, ConfigurationWatcherConfigurationProperties k8SConfigurationProperties, ThreadPoolTaskExecutor threadFactory, KubernetesNamespaceProvider namespaceProvider, BusRefreshTrigger busRefreshTrigger) { return new BusEventBasedSecretsWatcherChangeDetector(coreV1Api, environment, properties, strategy, secretsPropertySourceLocator, namespaceProvider, k8SConfigurationProperties, threadFactory, busRefreshTrigger); } } @AutoConfiguration static class RefreshTriggerConfiguration { @Bean @ConditionalOnMissingBean @Profile({ AMQP, KAFKA }) public BusRefreshTrigger busRefreshTrigger(ApplicationEventPublisher applicationEventPublisher, BusProperties busProperties) { return new BusRefreshTrigger(applicationEventPublisher, busProperties.getId()); } @Bean @ConditionalOnMissingBean public HttpRefreshTrigger httpRefreshTrigger(KubernetesInformerReactiveDiscoveryClient client, ConfigurationWatcherConfigurationProperties properties, WebClient webClient) { return new HttpRefreshTrigger(client, properties, webClient); } } }
return new HttpBasedConfigMapWatchChangeDetector(coreV1Api, environment, properties, strategy, configMapPropertySourceLocator, namespaceProvider, k8SConfigurationProperties, threadFactory, httpRefreshTrigger);
1,635
58
1,693
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/main/java/org/springframework/cloud/kubernetes/configuration/watcher/ConfigurationWatcherConfigurationProperties.java
ConfigurationWatcherConfigurationProperties
setActuatorPath
class ConfigurationWatcherConfigurationProperties { /** * label to enable refresh/restart when using configmaps. */ public static final String CONFIG_MAP_LABEL = "spring.cloud.kubernetes.config"; /** * label to enable refresh/restart when using secrets. */ public static final String SECRET_LABEL = "spring.cloud.kubernetes.secret"; /** * annotation name to enable refresh/restart for specific apps when using configmaps. */ public static final String CONFIG_MAP_APPS_ANNOTATION = "spring.cloud.kubernetes.configmap.apps"; /** * annotation name to enable refresh/restart for specific apps when using secrets. */ public static final String SECRET_APPS_ANNOTATION = "spring.cloud.kubernetes.secret.apps"; /** * Annotation key for actuator port and path. */ public static final String ANNOTATION_KEY = "boot.spring.io/actuator"; /** * Amount of time to delay the posting of the event to allow the app volume to update * data. */ @DurationUnit(ChronoUnit.MILLIS) private Duration refreshDelay = Duration.ofMillis(120000); private int threadPoolSize = 1; private String actuatorPath = "/actuator"; private Integer actuatorPort = -1; public String getActuatorPath() { return actuatorPath; } public void setActuatorPath(String actuatorPath) {<FILL_FUNCTION_BODY>} public Integer getActuatorPort() { return actuatorPort; } public void setActuatorPort(Integer actuatorPort) { this.actuatorPort = actuatorPort; } public Duration getRefreshDelay() { return refreshDelay; } public void setRefreshDelay(Duration refreshDelay) { this.refreshDelay = refreshDelay; } public int getThreadPoolSize() { return threadPoolSize; } public void setThreadPoolSize(int threadPoolSize) { this.threadPoolSize = threadPoolSize; } }
String normalizedPath = actuatorPath; if (!normalizedPath.startsWith("/")) { normalizedPath = "/" + normalizedPath; } if (normalizedPath.endsWith("/")) { normalizedPath = normalizedPath.substring(0, normalizedPath.length() - 1); } this.actuatorPath = normalizedPath;
547
95
642
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/main/java/org/springframework/cloud/kubernetes/configuration/watcher/HttpRefreshTrigger.java
HttpRefreshTrigger
getActuatorUri
class HttpRefreshTrigger implements RefreshTrigger { private static final LogAccessor LOG = new LogAccessor( LogFactory.getLog(KubernetesClientEventBasedSecretsChangeDetector.class)); private final KubernetesInformerReactiveDiscoveryClient kubernetesReactiveDiscoveryClient; private final ConfigurationWatcherConfigurationProperties k8SConfigurationProperties; private final WebClient webClient; HttpRefreshTrigger(KubernetesInformerReactiveDiscoveryClient kubernetesReactiveDiscoveryClient, ConfigurationWatcherConfigurationProperties k8SConfigurationProperties, WebClient webClient) { this.kubernetesReactiveDiscoveryClient = kubernetesReactiveDiscoveryClient; this.k8SConfigurationProperties = k8SConfigurationProperties; this.webClient = webClient; } @Override public Mono<Void> triggerRefresh(KubernetesObject kubernetesObject, String appName) { return kubernetesReactiveDiscoveryClient.getInstances(appName).flatMap(si -> { URI actuatorUri = getActuatorUri(si, k8SConfigurationProperties.getActuatorPath(), k8SConfigurationProperties.getActuatorPort()); LOG.debug(() -> "Sending refresh request for " + appName + " to URI " + actuatorUri); return webClient.post().uri(actuatorUri).retrieve().toBodilessEntity() .doOnSuccess(onSuccess(appName, actuatorUri)).doOnError(onError(appName)); }).then(); } private Consumer<ResponseEntity<Void>> onSuccess(String name, URI actuatorUri) { return re -> LOG.debug(() -> "Refresh sent to " + name + " at URI address " + actuatorUri + " returned a " + re.getStatusCode()); } private Consumer<Throwable> onError(String name) { return t -> LOG.warn(t, () -> "Refresh sent to " + name + " failed"); } private URI getActuatorUri(ServiceInstance si, String actuatorPath, int actuatorPort) {<FILL_FUNCTION_BODY>} private void setActuatorUriFromAnnotation(UriComponentsBuilder actuatorUriBuilder, String metadataUri) { URI annotationUri = URI.create(metadataUri); actuatorUriBuilder.path(annotationUri.getPath() + "/refresh"); // The URI may not contain a host so if that is the case the port in the URI will // be -1. The authority of the URI will be :<port> for example :9090, we just need // the 9090 in this case if (annotationUri.getPort() < 0) { if (annotationUri.getAuthority() != null) { actuatorUriBuilder.port(annotationUri.getAuthority().replaceFirst(":", "")); } } else { actuatorUriBuilder.port(annotationUri.getPort()); } } }
String metadataUri = si.getMetadata().getOrDefault(ConfigurationWatcherConfigurationProperties.ANNOTATION_KEY, ""); LOG.debug(() -> "Metadata actuator uri is: " + metadataUri); UriComponentsBuilder actuatorUriBuilder = UriComponentsBuilder.newInstance().scheme(si.getScheme()) .host(si.getHost()); if (StringUtils.hasText(metadataUri)) { LOG.debug(() -> "Found actuator URI in service instance metadata"); setActuatorUriFromAnnotation(actuatorUriBuilder, metadataUri); } else { int port = actuatorPort < 0 ? si.getPort() : actuatorPort; actuatorUriBuilder = actuatorUriBuilder.path(actuatorPath + "/refresh").port(port); } return actuatorUriBuilder.build().toUri();
755
224
979
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/main/java/org/springframework/cloud/kubernetes/configuration/watcher/SecretsWatcherChangeDetector.java
SecretsWatcherChangeDetector
onEvent
class SecretsWatcherChangeDetector extends KubernetesClientEventBasedSecretsChangeDetector implements RefreshTrigger permits BusEventBasedSecretsWatcherChangeDetector, HttpBasedSecretsWatchChangeDetector { private final ScheduledExecutorService executorService; private final long refreshDelay; SecretsWatcherChangeDetector(CoreV1Api coreV1Api, ConfigurableEnvironment environment, ConfigReloadProperties properties, ConfigurationUpdateStrategy strategy, KubernetesClientSecretsPropertySourceLocator propertySourceLocator, KubernetesNamespaceProvider kubernetesNamespaceProvider, ConfigurationWatcherConfigurationProperties k8SConfigurationProperties, ThreadPoolTaskExecutor threadPoolTaskExecutor) { super(coreV1Api, environment, properties, strategy, propertySourceLocator, kubernetesNamespaceProvider); this.executorService = Executors.newScheduledThreadPool(k8SConfigurationProperties.getThreadPoolSize(), threadPoolTaskExecutor); this.refreshDelay = k8SConfigurationProperties.getRefreshDelay().toMillis(); } @Override protected final void onEvent(KubernetesObject secret) {<FILL_FUNCTION_BODY>} }
// this::refreshTrigger is coming from BusEventBasedSecretsWatcherChangeDetector WatcherUtil.onEvent(secret, SECRET_LABEL, SECRET_APPS_ANNOTATION, refreshDelay, executorService, "secret", this::triggerRefresh);
295
76
371
<methods>public void <init>(io.kubernetes.client.openapi.apis.CoreV1Api, org.springframework.core.env.ConfigurableEnvironment, ConfigReloadProperties, ConfigurationUpdateStrategy, org.springframework.cloud.kubernetes.client.config.KubernetesClientSecretsPropertySourceLocator, org.springframework.cloud.kubernetes.commons.KubernetesNamespaceProvider) <variables>private static final org.springframework.core.log.LogAccessor LOG,private final non-sealed io.kubernetes.client.openapi.ApiClient apiClient,private final non-sealed io.kubernetes.client.openapi.apis.CoreV1Api coreV1Api,private final non-sealed boolean enableReloadFiltering,private final List<io.kubernetes.client.informer.SharedInformerFactory> factories,private final ResourceEventHandler<io.kubernetes.client.openapi.models.V1Secret> handler,private final List<SharedIndexInformer<io.kubernetes.client.openapi.models.V1Secret>> informers,private final non-sealed Set<java.lang.String> namespaces,private final non-sealed org.springframework.cloud.kubernetes.client.config.KubernetesClientSecretsPropertySourceLocator propertySourceLocator
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-configuration-watcher/src/main/java/org/springframework/cloud/kubernetes/configuration/watcher/WatcherUtil.java
WatcherUtil
schedule
class WatcherUtil { private static final LogAccessor LOG = new LogAccessor(LogFactory.getLog(WatcherUtil.class)); private WatcherUtil() { } static void onEvent(KubernetesObject kubernetesObject, String label, String annotationName, long refreshDelay, ScheduledExecutorService executorService, String type, BiFunction<KubernetesObject, String, Mono<Void>> triggerRefresh) { String name = kubernetesObject.getMetadata().getName(); boolean isSpringCloudKubernetes = isSpringCloudKubernetes(kubernetesObject, label); if (isSpringCloudKubernetes) { Set<String> apps = apps(kubernetesObject, annotationName); if (apps.isEmpty()) { apps.add(name); } LOG.info(() -> "will schedule remote refresh based on apps : " + apps); apps.forEach(appName -> schedule(type, appName, refreshDelay, executorService, triggerRefresh, kubernetesObject)); } else { LOG.debug(() -> "Not publishing event." + type + ": " + name + " does not contain the label " + label); } } static boolean isSpringCloudKubernetes(KubernetesObject kubernetesObject, String label) { if (kubernetesObject.getMetadata() == null) { return false; } return Boolean.parseBoolean(labels(kubernetesObject).getOrDefault(label, "false")); } static Set<String> apps(KubernetesObject kubernetesObject, String annotationName) { // mutable on purpose Set<String> apps = new HashSet<>(1); Map<String, String> annotations = annotations(kubernetesObject); if (annotations.isEmpty()) { LOG.debug(() -> annotationName + " not present (empty data)"); return apps; } String appsValue = annotations.get(annotationName); if (appsValue == null) { LOG.debug(() -> annotationName + " not present (missing in annotations)"); return apps; } if (appsValue.isBlank()) { LOG.debug(() -> appsValue + " not present (blanks only)"); return apps; } return Arrays.stream(appsValue.split(",")).map(String::trim).collect(Collectors.toSet()); } static Map<String, String> labels(KubernetesObject kubernetesObject) { return Optional.ofNullable(kubernetesObject.getMetadata()).map(V1ObjectMeta::getLabels).orElse(Map.of()); } static Map<String, String> annotations(KubernetesObject kubernetesObject) { return Optional.ofNullable(kubernetesObject.getMetadata()).map(V1ObjectMeta::getAnnotations).orElse(Map.of()); } private static void schedule(String type, String appName, long refreshDelay, ScheduledExecutorService executorService, BiFunction<KubernetesObject, String, Mono<Void>> triggerRefresh, KubernetesObject kubernetesObject) {<FILL_FUNCTION_BODY>} }
LOG.debug(() -> "Scheduling remote refresh event to be published for " + type + ": with appName : " + appName + " to be published in " + refreshDelay + " milliseconds"); executorService.schedule(() -> { try { triggerRefresh.apply(kubernetesObject, appName).subscribe(); } catch (Throwable t) { LOG.warn(t, "Error when refreshing appName " + appName); } }, refreshDelay, TimeUnit.MILLISECONDS);
826
142
968
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/main/java/org/springframework/cloud/kubernetes/discoveryserver/DiscoveryServerController.java
DiscoveryServerController
apps
class DiscoveryServerController { private final KubernetesInformerReactiveDiscoveryClient reactiveDiscoveryClient; public DiscoveryServerController(KubernetesInformerReactiveDiscoveryClient reactiveDiscoveryClient) { this.reactiveDiscoveryClient = reactiveDiscoveryClient; } @GetMapping("/apps") public Flux<Service> apps() {<FILL_FUNCTION_BODY>} @GetMapping("/apps/{name}") public Flux<ServiceInstance> appInstances(@PathVariable String name) { return reactiveDiscoveryClient.getInstances(name); } /** * use the "appInstanceNonDeprecated" instead. */ @Deprecated(forRemoval = true) @GetMapping("/app/{name}/{instanceId}") public Mono<ServiceInstance> appInstance(@PathVariable String name, @PathVariable String instanceId) { return innerAppInstance(name, instanceId); } @GetMapping("/apps/{name}/{instanceId}") Mono<ServiceInstance> appInstanceNonDeprecated(@PathVariable String name, @PathVariable String instanceId) { return innerAppInstance(name, instanceId); } private Mono<ServiceInstance> innerAppInstance(String name, String instanceId) { return reactiveDiscoveryClient.getInstances(name) .filter(serviceInstance -> serviceInstance.getInstanceId().equals(instanceId)).singleOrEmpty(); } }
return reactiveDiscoveryClient.getServices() .flatMap(service -> reactiveDiscoveryClient.getInstances(service).collectList() .flatMap(serviceInstances -> Mono.just(new Service(service, serviceInstances.stream().map(x -> (DefaultKubernetesServiceInstance) x).toList()))));
350
88
438
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-controllers/spring-cloud-kubernetes-discoveryserver/src/main/java/org/springframework/cloud/kubernetes/discoveryserver/HeartBeatListener.java
HeartBeatListener
onApplicationEvent
class HeartBeatListener implements ApplicationListener<HeartbeatEvent> { private static final LogAccessor LOG = new LogAccessor(LogFactory.getLog(HeartBeatListener.class)); private final AtomicReference<List<EndpointNameAndNamespace>> lastState = new AtomicReference<>(List.of()); HeartBeatListener(Environment environment) { String watchDelay = environment.getProperty(CATALOG_WATCH_PROPERTY_NAME); if (watchDelay != null) { LOG.debug("using delay : " + watchDelay); } else { LOG.debug("using default watch delay : " + CATALOG_WATCHER_DEFAULT_DELAY); } } @Override @SuppressWarnings("unchecked") public void onApplicationEvent(HeartbeatEvent event) {<FILL_FUNCTION_BODY>} AtomicReference<List<EndpointNameAndNamespace>> lastState() { return lastState; } }
LOG.debug(() -> "received heartbeat event"); List<EndpointNameAndNamespace> state = (List<EndpointNameAndNamespace>) event.getValue(); LOG.debug(() -> "state received : " + state); lastState.set(state);
248
70
318
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/ConfigServerBootstrapper.java
KubernetesFunction
apply
class KubernetesFunction implements ConfigServerInstanceProvider.Function { private KubernetesFunction() { } static KubernetesFunction create(BootstrapContext context) { return new KubernetesFunction(); } @Override public List<ServiceInstance> apply(String serviceId, Binder binder, BindHandler bindHandler, Log log) {<FILL_FUNCTION_BODY>} private KubernetesConfigServerInstanceProvider getInstanceProvider(Binder binder, BindHandler bindHandler) { KubernetesDiscoveryProperties kubernetesDiscoveryProperties = binder .bind(KubernetesDiscoveryProperties.PREFIX, Bindable.of(KubernetesDiscoveryProperties.class), bindHandler) .orElseGet(() -> KubernetesDiscoveryProperties.DEFAULT); KubernetesDiscoveryClientBlockingAutoConfiguration autoConfiguration = new KubernetesDiscoveryClientBlockingAutoConfiguration(); DiscoveryClient discoveryClient = autoConfiguration .kubernetesDiscoveryClient(autoConfiguration.restTemplateBuilder(), kubernetesDiscoveryProperties); return discoveryClient::getInstances; } // This method should never be called, but is there for backward // compatibility purposes @Override public List<ServiceInstance> apply(String serviceId) { return apply(serviceId, null, null, null); } }
if (binder == null || bindHandler == null || !getDiscoveryEnabled(binder, bindHandler)) { // If we don't have the Binder or BinderHandler from the // ConfigDataLocationResolverContext // we won't be able to create the necessary configuration // properties to configure the // Kubernetes DiscoveryClient return Collections.emptyList(); } return getInstanceProvider(binder, bindHandler).getInstances(serviceId);
338
118
456
<methods>public non-sealed void <init>() ,public static KubernetesClientProperties createKubernetesClientProperties(org.springframework.boot.context.properties.bind.Binder, org.springframework.boot.context.properties.bind.BindHandler) ,public static KubernetesClientProperties createKubernetesClientProperties(org.springframework.boot.BootstrapContext) ,public static KubernetesDiscoveryProperties createKubernetesDiscoveryProperties(org.springframework.boot.context.properties.bind.Binder, org.springframework.boot.context.properties.bind.BindHandler) ,public static KubernetesDiscoveryProperties createKubernetesDiscoveryProperties(org.springframework.boot.BootstrapContext) ,public static java.lang.Boolean getDiscoveryEnabled(org.springframework.boot.context.properties.bind.Binder, org.springframework.boot.context.properties.bind.BindHandler) ,public static java.lang.Boolean getDiscoveryEnabled(org.springframework.boot.BootstrapContext) ,public static boolean hasConfigServerInstanceProvider() <variables>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesCatalogWatch.java
KubernetesCatalogWatch
catalogServicesWatch
class KubernetesCatalogWatch implements ApplicationEventPublisherAware { private static final ParameterizedTypeReference<List<EndpointNameAndNamespace>> TYPE = new ParameterizedTypeReference<>() { }; private static final LogAccessor LOG = new LogAccessor(LogFactory.getLog(KubernetesCatalogWatch.class)); private final AtomicReference<List<EndpointNameAndNamespace>> catalogState = new AtomicReference<>(List.of()); private final RestTemplate restTemplate; private ApplicationEventPublisher publisher; KubernetesCatalogWatch(RestTemplateBuilder builder, KubernetesDiscoveryProperties properties) { this.restTemplate = builder.rootUri(properties.discoveryServerUrl()).build(); } @Override public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { this.publisher = publisher; } @Scheduled(fixedDelayString = "${" + CATALOG_WATCH_PROPERTY_WITH_DEFAULT_VALUE + "}") public void catalogServicesWatch() {<FILL_FUNCTION_BODY>} }
try { List<EndpointNameAndNamespace> currentState = restTemplate.exchange("/state", HttpMethod.GET, null, TYPE) .getBody(); if (!catalogState.get().equals(currentState)) { LOG.debug(() -> "Received update from kubernetes discovery http client: " + currentState); publisher.publishEvent(new HeartbeatEvent(this, currentState)); } catalogState.set(currentState); } catch (Exception e) { LOG.error(e, () -> "Error watching Kubernetes Services"); }
261
157
418
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesCatalogWatchAutoConfiguration.java
KubernetesCatalogWatchAutoConfiguration
kubernetesCatalogWatch
class KubernetesCatalogWatchAutoConfiguration { private static final LogAccessor LOG = new LogAccessor( LogFactory.getLog(KubernetesCatalogWatchAutoConfiguration.class)); // this has to be a RestTemplateBuilder and not a WebClientBuilder, otherwise // we need the webflux dependency, and it might leak into client's dependencies // which is not always desirable. @Bean @ConditionalOnMissingBean RestTemplateBuilder restTemplateBuilder() { return new RestTemplateBuilder(); } @Bean @ConditionalOnMissingBean KubernetesCatalogWatch kubernetesCatalogWatch(RestTemplateBuilder builder, KubernetesDiscoveryProperties properties, Environment environment) {<FILL_FUNCTION_BODY>} }
String watchDelay = environment.getProperty(CATALOG_WATCH_PROPERTY_NAME); if (watchDelay != null) { LOG.debug("using delay : " + watchDelay); } else { LOG.debug("using default watch delay : " + CATALOG_WATCHER_DEFAULT_DELAY); } return new KubernetesCatalogWatch(builder, properties);
183
110
293
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryClient.java
KubernetesDiscoveryClient
getServices
class KubernetesDiscoveryClient implements DiscoveryClient { private final RestTemplate rest; private final boolean emptyNamespaces; private final Set<String> namespaces; private final String discoveryServerUrl; @Deprecated(forRemoval = true) public KubernetesDiscoveryClient(RestTemplate rest, KubernetesDiscoveryClientProperties properties) { if (!StringUtils.hasText(properties.getDiscoveryServerUrl())) { throw new DiscoveryServerUrlInvalidException(); } this.rest = rest; this.emptyNamespaces = properties.getNamespaces().isEmpty(); this.namespaces = properties.getNamespaces(); this.discoveryServerUrl = properties.getDiscoveryServerUrl(); } KubernetesDiscoveryClient(RestTemplate rest, KubernetesDiscoveryProperties kubernetesDiscoveryProperties) { if (!StringUtils.hasText(kubernetesDiscoveryProperties.discoveryServerUrl())) { throw new DiscoveryServerUrlInvalidException(); } this.rest = rest; this.emptyNamespaces = kubernetesDiscoveryProperties.namespaces().isEmpty(); this.namespaces = kubernetesDiscoveryProperties.namespaces(); this.discoveryServerUrl = kubernetesDiscoveryProperties.discoveryServerUrl(); } @Override public String description() { return "Kubernetes Discovery Client"; } @Override public List<ServiceInstance> getInstances(String serviceId) { DefaultKubernetesServiceInstance[] responseBody = rest .getForEntity(discoveryServerUrl + "/apps/" + serviceId, DefaultKubernetesServiceInstance[].class) .getBody(); if (responseBody != null && responseBody.length > 0) { return Arrays.stream(responseBody).filter(this::matchNamespaces).collect(Collectors.toList()); } return List.of(); } @Override public List<String> getServices() {<FILL_FUNCTION_BODY>} private boolean matchNamespaces(DefaultKubernetesServiceInstance kubernetesServiceInstance) { return emptyNamespaces || namespaces.contains(kubernetesServiceInstance.getNamespace()); } private boolean matchNamespaces(Service service) { return service.serviceInstances().isEmpty() || service.serviceInstances().stream().anyMatch(this::matchNamespaces); } }
Service[] services = rest.getForEntity(discoveryServerUrl + "/apps", Service[].class).getBody(); if (services != null && services.length > 0) { return Arrays.stream(services).filter(this::matchNamespaces).map(Service::name).toList(); } return List.of();
576
85
661
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryClientAutoConfiguration.java
Reactive
kubernetesReactiveDiscoveryClientHealthIndicator
class Reactive { @Bean @ConditionalOnClass(name = { "org.springframework.web.reactive.function.client.WebClient" }) @ConditionalOnMissingBean(WebClient.Builder.class) public WebClient.Builder webClientBuilder() { return WebClient.builder(); } @Bean @ConditionalOnClass(name = { "org.springframework.web.reactive.function.client.WebClient" }) public ReactiveDiscoveryClient kubernetesReactiveDiscoveryClient(WebClient.Builder webClientBuilder, KubernetesDiscoveryClientProperties properties) { return new KubernetesReactiveDiscoveryClient(webClientBuilder, properties); } @Bean @ConditionalOnClass(name = "org.springframework.boot.actuate.health.ReactiveHealthIndicator") @ConditionalOnDiscoveryHealthIndicatorEnabled public ReactiveDiscoveryClientHealthIndicator kubernetesReactiveDiscoveryClientHealthIndicator( KubernetesReactiveDiscoveryClient client, DiscoveryClientHealthIndicatorProperties properties, ApplicationContext applicationContext) {<FILL_FUNCTION_BODY>} }
ReactiveDiscoveryClientHealthIndicator healthIndicator = new ReactiveDiscoveryClientHealthIndicator(client, properties); InstanceRegisteredEvent event = new InstanceRegisteredEvent(applicationContext.getId(), null); healthIndicator.onApplicationEvent(event); return healthIndicator;
291
83
374
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesDiscoveryPodUtils.java
KubernetesDiscoveryPodUtils
currentPod
class KubernetesDiscoveryPodUtils implements PodUtils<Object> { @Override public Supplier<Object> currentPod() {<FILL_FUNCTION_BODY>} @Override public boolean isInsideKubernetes() { // this bean is used in a config that is annotated // with @ConditionalOnCloudPlatform(CloudPlatform.KUBERNETES), // so safe to return true here. return true; } }
// we don't really have a way to get the pod here return () -> null;
112
27
139
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-discovery/src/main/java/org/springframework/cloud/kubernetes/discovery/KubernetesServiceInstance.java
KubernetesServiceInstance
equals
class KubernetesServiceInstance implements ServiceInstance { private String instanceId; private String serviceId; private String host; private int port; private boolean secure; private URI uri; private Map<String, String> metadata; private String scheme; private String namespace; public KubernetesServiceInstance() { } public KubernetesServiceInstance(String instanceId, String serviceId, String host, int port, boolean secure, URI uri, Map<String, String> metadata, String scheme, String namespace) { this.instanceId = instanceId; this.serviceId = serviceId; this.host = host; this.port = port; this.secure = secure; this.uri = uri; this.metadata = metadata; this.scheme = scheme; this.namespace = namespace; } @Override public String getInstanceId() { return instanceId; } @Override public String getServiceId() { return serviceId; } @Override public String getHost() { return host; } @Override public int getPort() { return port; } @Override public boolean isSecure() { return secure; } @Override public URI getUri() { return uri; } @Override public Map<String, String> getMetadata() { return metadata; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public void setServiceId(String serviceId) { this.serviceId = serviceId; } public void setHost(String host) { this.host = host; } public void setPort(int port) { this.port = port; } public void setSecure(boolean secure) { this.secure = secure; } public void setUri(URI uri) { this.uri = uri; } public void setMetadata(Map<String, String> metadata) { this.metadata = metadata; } public void setScheme(String scheme) { this.scheme = scheme; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } @Override public String getScheme() { return scheme; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(getInstanceId(), getServiceId(), getHost(), getPort(), isSecure(), getUri(), getMetadata(), getScheme(), getNamespace()); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } KubernetesServiceInstance that = (KubernetesServiceInstance) o; return getPort() == that.getPort() && isSecure() == that.isSecure() && Objects.equals(getInstanceId(), that.getInstanceId()) && Objects.equals(getServiceId(), that.getServiceId()) && Objects.equals(getHost(), that.getHost()) && Objects.equals(getUri(), that.getUri()) && Objects.equals(getMetadata(), that.getMetadata()) && Objects.equals(getScheme(), that.getScheme()) && Objects.equals(getNamespace(), that.getNamespace());
665
200
865
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-examples/kubernetes-leader-election-example/src/main/java/org/springframework/cloud/kubernetes/examples/LeaderController.java
LeaderController
revokeLeadership
class LeaderController { private final String host; @Value("${spring.cloud.kubernetes.leader.role}") private String role; private Context context; public LeaderController() throws UnknownHostException { this.host = InetAddress.getLocalHost().getHostName(); } /** * Return a message whether this instance is a leader or not. * @return info */ @GetMapping("/") public String getInfo() { if (this.context == null) { return String.format("I am '%s' but I am not a leader of the '%s'", this.host, this.role); } return String.format("I am '%s' and I am the leader of the '%s'", this.host, this.role); } /** * PUT request to try and revoke a leadership of this instance. If the instance is not * a leader, leadership cannot be revoked. Thus "HTTP Bad Request" response. If the * instance is a leader, it must have a leadership context instance which can be used * to give up the leadership. * @return info about leadership */ @PutMapping("/") public ResponseEntity<String> revokeLeadership() {<FILL_FUNCTION_BODY>} /** * Handle a notification that this instance has become a leader. * @param event on granted event */ @EventListener public void handleEvent(OnGrantedEvent event) { System.out.println(String.format("'%s' leadership granted", event.getRole())); this.context = event.getContext(); } /** * Handle a notification that this instance's leadership has been revoked. * @param event on revoked event */ @EventListener public void handleEvent(OnRevokedEvent event) { System.out.println(String.format("'%s' leadership revoked", event.getRole())); this.context = null; } }
if (this.context == null) { String message = String.format("Cannot revoke leadership because '%s' is not a leader", this.host); return ResponseEntity.badRequest().body(message); } this.context.yield(); String message = String.format("Leadership revoked for '%s'", this.host); return ResponseEntity.ok(message);
485
99
584
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-autoconfig/src/main/java/org/springframework/cloud/kubernetes/fabric8/Fabric8AutoConfiguration.java
Fabric8AutoConfiguration
kubernetesClientConfig
class Fabric8AutoConfiguration { private static <D> D or(D left, D right) { return left != null ? left : right; } private static Integer orDurationInt(Duration left, Integer right) { return left != null ? (int) left.toMillis() : right; } private static Long orDurationLong(Duration left, Long right) { return left != null ? left.toMillis() : right; } @Bean @ConditionalOnMissingBean(Config.class) public Config kubernetesClientConfig(KubernetesClientProperties kubernetesClientProperties) {<FILL_FUNCTION_BODY>} @Bean @ConditionalOnMissingBean public KubernetesClient kubernetesClient(Config config) { return new KubernetesClientBuilder().withConfig(config).build(); } @Bean @ConditionalOnMissingBean public Fabric8PodUtils kubernetesPodUtils(KubernetesClient client) { return new Fabric8PodUtils(client); } }
Config base = Config.autoConfigure(null); ConfigBuilder builder = new ConfigBuilder(base) // Only set values that have been explicitly specified .withMasterUrl(or(kubernetesClientProperties.masterUrl(), base.getMasterUrl())) .withApiVersion(or(kubernetesClientProperties.apiVersion(), base.getApiVersion())) .withNamespace(or(kubernetesClientProperties.namespace(), base.getNamespace())) .withUsername(or(kubernetesClientProperties.username(), base.getUsername())) .withPassword(or(kubernetesClientProperties.password(), base.getPassword())) .withOauthToken(or(kubernetesClientProperties.oauthToken(), base.getOauthToken())) .withCaCertFile(or(kubernetesClientProperties.caCertFile(), base.getCaCertFile())) .withCaCertData(or(kubernetesClientProperties.caCertData(), base.getCaCertData())) .withClientKeyFile(or(kubernetesClientProperties.clientKeyFile(), base.getClientKeyFile())) .withClientKeyData(or(kubernetesClientProperties.clientKeyData(), base.getClientKeyData())) .withClientCertFile(or(kubernetesClientProperties.clientCertFile(), base.getClientCertFile())) .withClientCertData(or(kubernetesClientProperties.clientCertData(), base.getClientCertData())) // No magic is done for the properties below so we leave them as is. .withClientKeyAlgo(or(kubernetesClientProperties.clientKeyAlgo(), base.getClientKeyAlgo())) .withClientKeyPassphrase( or(kubernetesClientProperties.clientKeyPassphrase(), base.getClientKeyPassphrase())) .withConnectionTimeout( orDurationInt(kubernetesClientProperties.connectionTimeout(), base.getConnectionTimeout())) .withRequestTimeout( orDurationInt(kubernetesClientProperties.requestTimeout(), base.getRequestTimeout())) .withTrustCerts(or(kubernetesClientProperties.trustCerts(), base.isTrustCerts())) .withHttpProxy(or(kubernetesClientProperties.httpProxy(), base.getHttpProxy())) .withHttpsProxy(or(kubernetesClientProperties.httpsProxy(), base.getHttpsProxy())) .withProxyUsername(or(kubernetesClientProperties.proxyUsername(), base.getProxyUsername())) .withProxyPassword(or(kubernetesClientProperties.proxyPassword(), base.getProxyPassword())) .withNoProxy(or(kubernetesClientProperties.noProxy(), base.getNoProxy())) // Disable the built-in retry functionality since Spring Cloud Kubernetes // provides it // See https://github.com/fabric8io/kubernetes-client/issues/4863 .withRequestRetryBackoffLimit(0); String userAgent = or(base.getUserAgent(), KubernetesClientProperties.DEFAULT_USER_AGENT); if (!kubernetesClientProperties.userAgent().equals(KubernetesClientProperties.DEFAULT_USER_AGENT)) { userAgent = kubernetesClientProperties.userAgent(); } return builder.withUserAgent(userAgent).build();
254
800
1,054
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-autoconfig/src/main/java/org/springframework/cloud/kubernetes/fabric8/Fabric8HealthIndicator.java
Fabric8HealthIndicator
getDetails
class Fabric8HealthIndicator extends AbstractKubernetesHealthIndicator { private final PodUtils<Pod> utils; public Fabric8HealthIndicator(PodUtils<Pod> utils) { this.utils = utils; } @Override protected Map<String, Object> getDetails() {<FILL_FUNCTION_BODY>} }
Pod current = this.utils.currentPod().get(); if (current != null) { Map<String, Object> details = CollectionUtils.newHashMap(8); details.put(INSIDE, true); ObjectMeta metadata = current.getMetadata(); details.put(NAMESPACE, metadata.getNamespace()); details.put(POD_NAME, metadata.getName()); details.put(LABELS, metadata.getLabels()); PodStatus status = current.getStatus(); details.put(POD_IP, status.getPodIP()); details.put(HOST_IP, status.getHostIP()); PodSpec spec = current.getSpec(); details.put(SERVICE_ACCOUNT, spec.getServiceAccountName()); details.put(NODE_NAME, spec.getNodeName()); return details; } return Collections.singletonMap(INSIDE, false);
94
248
342
<methods>public non-sealed void <init>() <variables>public static final java.lang.String HOST_IP,public static final java.lang.String INSIDE,public static final java.lang.String LABELS,public static final java.lang.String NAMESPACE,public static final java.lang.String NODE_NAME,public static final java.lang.String POD_IP,public static final java.lang.String POD_NAME,public static final java.lang.String SERVICE_ACCOUNT
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-autoconfig/src/main/java/org/springframework/cloud/kubernetes/fabric8/Fabric8InfoContributor.java
Fabric8InfoContributor
getDetails
class Fabric8InfoContributor extends AbstractKubernetesInfoContributor { private final PodUtils<Pod> utils; public Fabric8InfoContributor(PodUtils<Pod> utils) { this.utils = utils; } @Override public Map<String, Object> getDetails() {<FILL_FUNCTION_BODY>} }
Pod current = this.utils.currentPod().get(); if (current != null) { Map<String, Object> details = CollectionUtils.newHashMap(7); details.put(INSIDE, true); ObjectMeta metadata = current.getMetadata(); details.put(NAMESPACE, metadata.getNamespace()); details.put(POD_NAME, metadata.getName()); PodStatus status = current.getStatus(); details.put(POD_IP, status.getPodIP()); details.put(HOST_IP, status.getHostIP()); PodSpec spec = current.getSpec(); details.put(SERVICE_ACCOUNT, spec.getServiceAccountName()); details.put(NODE_NAME, spec.getNodeName()); return details; } return Collections.singletonMap(INSIDE, false);
93
230
323
<methods>public non-sealed void <init>() ,public void contribute(org.springframework.boot.actuate.info.Info.Builder) ,public abstract Map<java.lang.String,java.lang.Object> getDetails() <variables>public static final java.lang.String HOST_IP,public static final java.lang.String INSIDE,public static final java.lang.String KUBERNETES,public static final java.lang.String LABELS,private static final org.apache.commons.logging.Log LOG,public static final java.lang.String NAMESPACE,public static final java.lang.String NODE_NAME,public static final java.lang.String POD_IP,public static final java.lang.String POD_NAME,public static final java.lang.String SERVICE_ACCOUNT
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-autoconfig/src/main/java/org/springframework/cloud/kubernetes/fabric8/Fabric8PodUtils.java
Fabric8PodUtils
isServiceAccountFound
class Fabric8PodUtils implements PodUtils<Pod> { /** * HOSTNAME environment variable name. */ public static final String HOSTNAME = "HOSTNAME"; /** * KUBERNETES_SERVICE_HOST environment variable name. */ public static final String KUBERNETES_SERVICE_HOST = "KUBERNETES_SERVICE_HOST"; private static final Log LOG = LogFactory.getLog(Fabric8PodUtils.class); private final KubernetesClient client; private final String hostName; private final String serviceHost; private final Supplier<Pod> current; public Fabric8PodUtils(KubernetesClient client) { if (client == null) { throw new IllegalArgumentException("Must provide an instance of KubernetesClient"); } this.client = client; this.hostName = EnvReader.getEnv(HOSTNAME); this.serviceHost = EnvReader.getEnv(KUBERNETES_SERVICE_HOST); this.current = LazilyInstantiate.using(this::internalGetPod); } @Override public Supplier<Pod> currentPod() { return this.current; } @Override public boolean isInsideKubernetes() { return currentPod().get() != null; } private Pod internalGetPod() { try { if (isServiceHostEnvVarPresent() && isHostNameEnvVarPresent() && isServiceAccountFound()) { return this.client.pods().withName(this.hostName).get(); } } catch (Throwable t) { LOG.warn("Failed to get pod with name:[" + this.hostName + "]. You should look into this if things aren't" + " working as you expect. Are you missing serviceaccount permissions?", t); } return null; } private boolean isServiceHostEnvVarPresent() { return StringUtils.hasLength(serviceHost); } private boolean isHostNameEnvVarPresent() { return StringUtils.hasLength(hostName); } private boolean isServiceAccountFound() {<FILL_FUNCTION_BODY>} }
boolean serviceAccountPathPresent = Paths.get(Config.KUBERNETES_SERVICE_ACCOUNT_TOKEN_PATH).toFile().exists(); if (!serviceAccountPathPresent) { // https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/ LOG.warn("serviceaccount path not present, did you disable it via 'automountServiceAccountToken : false'?" + " Major functionalities will not work without that property being set"); } return serviceAccountPathPresent && Paths.get(Config.KUBERNETES_SERVICE_ACCOUNT_CA_CRT_PATH).toFile().exists();
548
166
714
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-autoconfig/src/main/java/org/springframework/cloud/kubernetes/fabric8/Fabric8Utils.java
Fabric8Utils
getApplicationNamespace
class Fabric8Utils { private Fabric8Utils() { } public static ServiceMetadata serviceMetadata(Service service) { ObjectMeta metadata = service.getMetadata(); ServiceSpec serviceSpec = service.getSpec(); return new ServiceMetadata(metadata.getName(), metadata.getNamespace(), serviceSpec.getType(), metadata.getLabels(), metadata.getAnnotations()); } private static final LogAccessor LOG = new LogAccessor(LogFactory.getLog(Fabric8Utils.class)); /** * this method does the namespace resolution. Namespace is being searched according to * the order below. * * <pre> * 1. from incoming namespace, which can be null. * 2. from a property 'spring.cloud.kubernetes.client.namespace', if such is present. * 3. from a String residing in a file denoted by `spring.cloud.kubernetes.client.serviceAccountNamespacePath` * property, if such is present. * 4. from a String residing in `/var/run/secrets/kubernetes.io/serviceaccount/namespace` file, * if such is present (kubernetes default path) * 5. from KubernetesClient::getNamespace, which is implementation specific. * </pre> * * If any of the above fail, we throw a {@link NamespaceResolutionFailedException}. * @param namespace normalized namespace * @param configurationTarget Config Map/Secret * @param provider the provider which computes the namespace * @param client fabric8 Kubernetes client * @return application namespace * @throws NamespaceResolutionFailedException when namespace could not be resolved */ public static String getApplicationNamespace(KubernetesClient client, @Nullable String namespace, String configurationTarget, KubernetesNamespaceProvider provider) {<FILL_FUNCTION_BODY>} }
if (StringUtils.hasText(namespace)) { LOG.debug(configurationTarget + " namespace : " + namespace); return namespace; } if (provider != null) { String providerNamespace = provider.getNamespace(); if (StringUtils.hasText(providerNamespace)) { LOG.debug(() -> configurationTarget + " namespace from provider : " + providerNamespace); return providerNamespace; } } String clientNamespace = client.getNamespace(); LOG.debug(() -> configurationTarget + " namespace from client : " + clientNamespace); if (clientNamespace == null) { throw new NamespaceResolutionFailedException("unresolved namespace"); } return clientNamespace;
471
182
653
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-autoconfig/src/main/java/org/springframework/cloud/kubernetes/fabric8/profile/Fabric8ProfileEnvironmentPostProcessor.java
Fabric8ProfileEnvironmentPostProcessor
isInsideKubernetes
class Fabric8ProfileEnvironmentPostProcessor extends AbstractKubernetesProfileEnvironmentPostProcessor { @Override protected boolean isInsideKubernetes(Environment environment) {<FILL_FUNCTION_BODY>} }
try (KubernetesClient client = new KubernetesClientBuilder().build()) { Fabric8PodUtils podUtils = new Fabric8PodUtils(client); return environment.containsProperty(Fabric8PodUtils.KUBERNETES_SERVICE_HOST) || podUtils.isInsideKubernetes(); }
53
87
140
<methods>public non-sealed void <init>() ,public int getOrder() ,public void postProcessEnvironment(org.springframework.core.env.ConfigurableEnvironment, org.springframework.boot.SpringApplication) <variables>public static final java.lang.String KUBERNETES_PROFILE,private static final org.springframework.boot.logging.DeferredLog LOG,private static final java.lang.String NAMESPACE_PATH_PROPERTY,protected static final java.lang.String NAMESPACE_PROPERTY,private static final int ORDER,private static final java.lang.String PROPERTY_SOURCE_NAME
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigDataLocationResolver.java
Fabric8ConfigDataLocationResolver
registerBeans
class Fabric8ConfigDataLocationResolver extends KubernetesConfigDataLocationResolver { public Fabric8ConfigDataLocationResolver(DeferredLogFactory factory) { super(factory); } @Override protected void registerBeans(ConfigDataLocationResolverContext resolverContext, ConfigDataLocation location, Profiles profiles, KubernetesConfigDataLocationResolver.PropertyHolder propertyHolder, KubernetesNamespaceProvider namespaceProvider) {<FILL_FUNCTION_BODY>} private KubernetesClient registerConfigAndClient(ConfigurableBootstrapContext bootstrapContext, KubernetesClientProperties kubernetesClientProperties) { Config config = new Fabric8AutoConfiguration().kubernetesClientConfig(kubernetesClientProperties); registerSingle(bootstrapContext, Config.class, config, "fabric8Config"); KubernetesClient kubernetesClient = new Fabric8AutoConfiguration().kubernetesClient(config); registerSingle(bootstrapContext, KubernetesClient.class, kubernetesClient, "configKubernetesClient"); return kubernetesClient; } @Override protected KubernetesNamespaceProvider kubernetesNamespaceProvider(Environment environment) { return new KubernetesNamespaceProvider(environment); } }
KubernetesClientProperties kubernetesClientProperties = propertyHolder.kubernetesClientProperties(); ConfigMapConfigProperties configMapProperties = propertyHolder.configMapConfigProperties(); SecretsConfigProperties secretsProperties = propertyHolder.secretsProperties(); ConfigurableBootstrapContext bootstrapContext = resolverContext.getBootstrapContext(); KubernetesClient kubernetesClient = registerConfigAndClient(bootstrapContext, kubernetesClientProperties); if (configMapProperties != null && configMapProperties.enabled()) { ConfigMapPropertySourceLocator configMapPropertySourceLocator = new Fabric8ConfigMapPropertySourceLocator( kubernetesClient, configMapProperties, namespaceProvider); if (isRetryEnabledForConfigMap(configMapProperties)) { configMapPropertySourceLocator = new ConfigDataRetryableConfigMapPropertySourceLocator( configMapPropertySourceLocator, configMapProperties, new Fabric8ConfigMapsCache()); } registerSingle(bootstrapContext, ConfigMapPropertySourceLocator.class, configMapPropertySourceLocator, "configDataConfigMapPropertySourceLocator"); } if (secretsProperties != null && secretsProperties.enabled()) { SecretsPropertySourceLocator secretsPropertySourceLocator = new Fabric8SecretsPropertySourceLocator( kubernetesClient, secretsProperties, namespaceProvider); if (isRetryEnabledForSecrets(secretsProperties)) { secretsPropertySourceLocator = new ConfigDataRetryableSecretsPropertySourceLocator( secretsPropertySourceLocator, secretsProperties, new Fabric8SecretsCache()); } registerSingle(bootstrapContext, SecretsPropertySourceLocator.class, secretsPropertySourceLocator, "configDataSecretsPropertySourceLocator"); }
301
446
747
<methods>public void <init>(org.springframework.boot.logging.DeferredLogFactory) ,public final int getOrder() ,public final boolean isResolvable(org.springframework.boot.context.config.ConfigDataLocationResolverContext, org.springframework.boot.context.config.ConfigDataLocation) ,public final List<org.springframework.cloud.kubernetes.commons.config.KubernetesConfigDataResource> resolve(org.springframework.boot.context.config.ConfigDataLocationResolverContext, org.springframework.boot.context.config.ConfigDataLocation) throws org.springframework.boot.context.config.ConfigDataLocationNotFoundException, org.springframework.boot.context.config.ConfigDataResourceNotFoundException,public final List<org.springframework.cloud.kubernetes.commons.config.KubernetesConfigDataResource> resolveProfileSpecific(org.springframework.boot.context.config.ConfigDataLocationResolverContext, org.springframework.boot.context.config.ConfigDataLocation, org.springframework.boot.context.config.Profiles) throws org.springframework.boot.context.config.ConfigDataLocationNotFoundException<variables>private static final boolean RETRY_IS_PRESENT,private final non-sealed org.apache.commons.logging.Log log
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapPropertySource.java
Fabric8ConfigMapPropertySource
getSourceData
class Fabric8ConfigMapPropertySource extends SourceDataEntriesProcessor { private static final EnumMap<NormalizedSourceType, Fabric8ContextToSourceData> STRATEGIES = new EnumMap<>( NormalizedSourceType.class); static { STRATEGIES.put(NormalizedSourceType.NAMED_CONFIG_MAP, namedConfigMap()); STRATEGIES.put(NormalizedSourceType.LABELED_CONFIG_MAP, labeledConfigMap()); } Fabric8ConfigMapPropertySource(Fabric8ConfigContext context) { super(getSourceData(context)); } private static SourceData getSourceData(Fabric8ConfigContext context) {<FILL_FUNCTION_BODY>} private static Fabric8ContextToSourceData namedConfigMap() { return new NamedConfigMapContextToSourceDataProvider().get(); } private static Fabric8ContextToSourceData labeledConfigMap() { return new LabeledConfigMapContextToSourceDataProvider().get(); } }
NormalizedSourceType type = context.normalizedSource().type(); return Optional.ofNullable(STRATEGIES.get(type)).map(x -> x.apply(context)) .orElseThrow(() -> new IllegalArgumentException("no strategy found for : " + type));
254
71
325
<methods>public void <init>(SourceData) ,public static Map<java.lang.String,java.lang.Object> processAllEntries(Map<java.lang.String,java.lang.String>, org.springframework.core.env.Environment) ,public static Map<java.lang.String,java.lang.Object> processAllEntries(Map<java.lang.String,java.lang.String>, org.springframework.core.env.Environment, boolean) <variables>private static Predicate<java.lang.String> ENDS_IN_EXTENSION,private static final org.apache.commons.logging.Log LOG
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapPropertySourceLocator.java
Fabric8ConfigMapPropertySourceLocator
getMapPropertySource
class Fabric8ConfigMapPropertySourceLocator extends ConfigMapPropertySourceLocator { private final KubernetesClient client; private final KubernetesNamespaceProvider provider; Fabric8ConfigMapPropertySourceLocator(KubernetesClient client, ConfigMapConfigProperties properties, KubernetesNamespaceProvider provider) { super(properties, new Fabric8ConfigMapsCache()); this.client = client; this.provider = provider; } @Override protected MapPropertySource getMapPropertySource(NormalizedSource normalizedSource, ConfigurableEnvironment environment) {<FILL_FUNCTION_BODY>} }
// NormalizedSource has a namespace, but users can skip it. // In such cases we try to get it elsewhere String namespace = getApplicationNamespace(this.client, normalizedSource.namespace().orElse(null), normalizedSource.target(), provider); Fabric8ConfigContext context = new Fabric8ConfigContext(client, normalizedSource, namespace, environment); return new Fabric8ConfigMapPropertySource(context);
155
106
261
<methods>public void <init>(ConfigMapConfigProperties) ,public void <init>(ConfigMapConfigProperties, org.springframework.cloud.kubernetes.commons.config.ConfigMapCache) ,public PropertySource<?> locate(org.springframework.core.env.Environment) ,public Collection<PropertySource<?>> locateCollection(org.springframework.core.env.Environment) <variables>private static final org.apache.commons.logging.Log LOG,private final non-sealed org.springframework.cloud.kubernetes.commons.config.ConfigMapCache cache,protected final non-sealed ConfigMapConfigProperties properties
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigMapsCache.java
Fabric8ConfigMapsCache
byNamespace
class Fabric8ConfigMapsCache implements ConfigMapCache { private static final LogAccessor LOG = new LogAccessor(LogFactory.getLog(Fabric8ConfigMapsCache.class)); /** * at the moment our loading of config maps is using a single thread, but might change * in the future, thus a thread safe structure. */ private static final ConcurrentHashMap<String, List<StrippedSourceContainer>> CACHE = new ConcurrentHashMap<>(); @Override public void discardAll() { CACHE.clear(); } static List<StrippedSourceContainer> byNamespace(KubernetesClient client, String namespace) {<FILL_FUNCTION_BODY>} private static List<StrippedSourceContainer> strippedConfigMaps(List<ConfigMap> configMaps) { return configMaps.stream().map(configMap -> new StrippedSourceContainer(configMap.getMetadata().getLabels(), configMap.getMetadata().getName(), configMap.getData())).collect(Collectors.toList()); } }
boolean[] b = new boolean[1]; List<StrippedSourceContainer> result = CACHE.computeIfAbsent(namespace, x -> { b[0] = true; return strippedConfigMaps(client.configMaps().inNamespace(namespace).list().getItems()); }); if (b[0]) { LOG.debug(() -> "Loaded all config maps in namespace '" + namespace + "'"); } else { LOG.debug(() -> "Loaded (from cache) all config maps in namespace '" + namespace + "'"); } return result;
265
157
422
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8ConfigUtils.java
Fabric8ConfigUtils
configMapsDataByName
class Fabric8ConfigUtils { private static final Log LOG = LogFactory.getLog(Fabric8ConfigUtils.class); private Fabric8ConfigUtils() { } /** * finds namespaces to be used for the event based reloading. */ public static Set<String> namespaces(KubernetesClient client, KubernetesNamespaceProvider provider, ConfigReloadProperties properties, String target) { Set<String> namespaces = properties.namespaces(); if (namespaces.isEmpty()) { namespaces = Set.of(Fabric8Utils.getApplicationNamespace(client, null, target, provider)); } LOG.debug("informer namespaces : " + namespaces); return namespaces; } /** * <pre> * 1. read all secrets in the provided namespace * 2. from the above, filter the ones that we care about (filter by labels) * 3. with secret names from (2), find out if there are any profile based secrets (if profiles is not empty) * 4. concat (2) and (3) and these are the secrets we are interested in * 5. see if any of the secrets from (4) has a single yaml/properties file * 6. gather all the names of the secrets (from 4) + data they hold * </pre> */ static MultipleSourcesContainer secretsDataByLabels(KubernetesClient client, String namespace, Map<String, String> labels, Environment environment, Set<String> profiles) { List<StrippedSourceContainer> strippedSecrets = strippedSecrets(client, namespace); if (strippedSecrets.isEmpty()) { return MultipleSourcesContainer.empty(); } return ConfigUtils.processLabeledData(strippedSecrets, environment, labels, namespace, profiles, true); } /** * <pre> * 1. read all config maps in the provided namespace * 2. from the above, filter the ones that we care about (filter by labels) * 3. with config maps names from (2), find out if there are any profile based ones (if profiles is not empty) * 4. concat (2) and (3) and these are the config maps we are interested in * 5. see if any from (4) has a single yaml/properties file * 6. gather all the names of the config maps (from 4) + data they hold * </pre> */ static MultipleSourcesContainer configMapsDataByLabels(KubernetesClient client, String namespace, Map<String, String> labels, Environment environment, Set<String> profiles) { List<StrippedSourceContainer> strippedConfigMaps = strippedConfigMaps(client, namespace); if (strippedConfigMaps.isEmpty()) { return MultipleSourcesContainer.empty(); } return ConfigUtils.processLabeledData(strippedConfigMaps, environment, labels, namespace, profiles, false); } /** * <pre> * 1. read all secrets in the provided namespace * 2. from the above, filter the ones that we care about (by name) * 3. see if any of the secrets has a single yaml/properties file * 4. gather all the names of the secrets + decoded data they hold * </pre> */ static MultipleSourcesContainer secretsDataByName(KubernetesClient client, String namespace, LinkedHashSet<String> sourceNames, Environment environment) { List<StrippedSourceContainer> strippedSecrets = strippedSecrets(client, namespace); if (strippedSecrets.isEmpty()) { return MultipleSourcesContainer.empty(); } return ConfigUtils.processNamedData(strippedSecrets, environment, sourceNames, namespace, true); } /** * <pre> * 1. read all config maps in the provided namespace * 2. from the above, filter the ones that we care about (by name) * 3. see if any of the config maps has a single yaml/properties file * 4. gather all the names of the config maps + data they hold * </pre> */ static MultipleSourcesContainer configMapsDataByName(KubernetesClient client, String namespace, LinkedHashSet<String> sourceNames, Environment environment) {<FILL_FUNCTION_BODY>} private static List<StrippedSourceContainer> strippedConfigMaps(KubernetesClient client, String namespace) { List<StrippedSourceContainer> strippedConfigMaps = Fabric8ConfigMapsCache.byNamespace(client, namespace); if (strippedConfigMaps.isEmpty()) { LOG.debug("No configmaps in namespace '" + namespace + "'"); } return strippedConfigMaps; } private static List<StrippedSourceContainer> strippedSecrets(KubernetesClient client, String namespace) { List<StrippedSourceContainer> strippedSecrets = Fabric8SecretsCache.byNamespace(client, namespace); if (strippedSecrets.isEmpty()) { LOG.debug("No secrets in namespace '" + namespace + "'"); } return strippedSecrets; } }
List<StrippedSourceContainer> strippedConfigMaps = strippedConfigMaps(client, namespace); if (strippedConfigMaps.isEmpty()) { return MultipleSourcesContainer.empty(); } return ConfigUtils.processNamedData(strippedConfigMaps, environment, sourceNames, namespace, false);
1,303
82
1,385
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8SecretsCache.java
Fabric8SecretsCache
byNamespace
class Fabric8SecretsCache implements SecretsCache { private static final LogAccessor LOG = new LogAccessor(LogFactory.getLog(Fabric8SecretsCache.class)); /** * at the moment our loading of config maps is using a single thread, but might change * in the future, thus a thread safe structure. */ private static final ConcurrentHashMap<String, List<StrippedSourceContainer>> CACHE = new ConcurrentHashMap<>(); @Override public void discardAll() { CACHE.clear(); } static List<StrippedSourceContainer> byNamespace(KubernetesClient client, String namespace) {<FILL_FUNCTION_BODY>} private static List<StrippedSourceContainer> strippedSecrets(List<Secret> secrets) { return secrets.stream().map(secret -> new StrippedSourceContainer(secret.getMetadata().getLabels(), secret.getMetadata().getName(), secret.getData())).collect(Collectors.toList()); } }
boolean[] b = new boolean[1]; List<StrippedSourceContainer> result = CACHE.computeIfAbsent(namespace, x -> { b[0] = true; return strippedSecrets(client.secrets().inNamespace(namespace).list().getItems()); }); if (b[0]) { LOG.debug(() -> "Loaded all secrets in namespace '" + namespace + "'"); } else { LOG.debug(() -> "Loaded (from cache) all secrets in namespace '" + namespace + "'"); } return result;
253
154
407
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8SecretsPropertySource.java
Fabric8SecretsPropertySource
getSourceData
class Fabric8SecretsPropertySource extends SecretsPropertySource { private static final EnumMap<NormalizedSourceType, Fabric8ContextToSourceData> STRATEGIES = new EnumMap<>( NormalizedSourceType.class); static { STRATEGIES.put(NormalizedSourceType.NAMED_SECRET, namedSecret()); STRATEGIES.put(NormalizedSourceType.LABELED_SECRET, labeledSecret()); } Fabric8SecretsPropertySource(Fabric8ConfigContext context) { super(getSourceData(context)); } private static SourceData getSourceData(Fabric8ConfigContext context) {<FILL_FUNCTION_BODY>} private static Fabric8ContextToSourceData namedSecret() { return new NamedSecretContextToSourceDataProvider().get(); } private static Fabric8ContextToSourceData labeledSecret() { return new LabeledSecretContextToSourceDataProvider().get(); } }
NormalizedSourceType type = context.normalizedSource().type(); return Optional.ofNullable(STRATEGIES.get(type)).map(x -> x.apply(context)) .orElseThrow(() -> new IllegalArgumentException("no strategy found for : " + type));
247
71
318
<methods>public void <init>(SourceData) ,public java.lang.String toString() <variables>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/Fabric8SecretsPropertySourceLocator.java
Fabric8SecretsPropertySourceLocator
getPropertySource
class Fabric8SecretsPropertySourceLocator extends SecretsPropertySourceLocator { private final KubernetesClient client; private final KubernetesNamespaceProvider provider; Fabric8SecretsPropertySourceLocator(KubernetesClient client, SecretsConfigProperties properties, KubernetesNamespaceProvider provider) { super(properties, new Fabric8SecretsCache()); this.client = client; this.provider = provider; } @Override protected SecretsPropertySource getPropertySource(ConfigurableEnvironment environment, NormalizedSource normalizedSource) {<FILL_FUNCTION_BODY>} }
// NormalizedSource has a namespace, but users can skip it. // In such cases we try to get it elsewhere String namespace = getApplicationNamespace(client, normalizedSource.namespace().orElse(null), normalizedSource.target(), provider); Fabric8ConfigContext context = new Fabric8ConfigContext(client, normalizedSource, namespace, environment); return new Fabric8SecretsPropertySource(context);
154
104
258
<methods>public void <init>(SecretsConfigProperties) ,public void <init>(SecretsConfigProperties, org.springframework.cloud.kubernetes.commons.config.SecretsCache) ,public PropertySource<?> locate(org.springframework.core.env.Environment) ,public Collection<PropertySource<?>> locateCollection(org.springframework.core.env.Environment) <variables>private static final org.apache.commons.logging.Log LOG,private final non-sealed org.springframework.cloud.kubernetes.commons.config.SecretsCache cache,protected final non-sealed SecretsConfigProperties properties
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/LabeledConfigMapContextToSourceDataProvider.java
LabeledConfigMapContextToSourceDataProvider
get
class LabeledConfigMapContextToSourceDataProvider implements Supplier<Fabric8ContextToSourceData> { LabeledConfigMapContextToSourceDataProvider() { } /* * Computes a ContextSourceData (think content) for configmap(s) based on some labels. * There could be many sources that are read based on incoming labels, for which we * will be computing a single Map<String, Object> in the end. * * If there is no config maps found for the provided labels, we will return an "empty" * SourceData. Its name is going to be the concatenated labels mapped to an empty Map. * * If we find config maps(s) for the provided labels, its name is going to be the * concatenated names mapped to the data they hold as a Map. */ @Override public Fabric8ContextToSourceData get() {<FILL_FUNCTION_BODY>} }
return context -> { LabeledConfigMapNormalizedSource source = (LabeledConfigMapNormalizedSource) context.normalizedSource(); return new LabeledSourceData() { @Override public MultipleSourcesContainer dataSupplier(Map<String, String> labels, Set<String> profiles) { return Fabric8ConfigUtils.configMapsDataByLabels(context.client(), context.namespace(), labels, context.environment(), profiles); } }.compute(source.labels(), source.prefix(), source.target(), source.profileSpecificSources(), source.failFast(), context.namespace(), context.environment().getActiveProfiles()); };
226
172
398
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/LabeledSecretContextToSourceDataProvider.java
LabeledSecretContextToSourceDataProvider
get
class LabeledSecretContextToSourceDataProvider implements Supplier<Fabric8ContextToSourceData> { LabeledSecretContextToSourceDataProvider() { } /* * Computes a ContextSourceData (think content) for secret(s) based on some labels. * There could be many secrets that are read based on incoming labels, for which we * will be computing a single Map<String, Object> in the end. * * If there is no secret found for the provided labels, we will return an "empty" * SourceData. Its name is going to be the concatenated labels mapped to an empty Map. * * If we find secret(s) for the provided labels, its name is going to be the * concatenated secret names mapped to the data they hold as a Map. */ @Override public Fabric8ContextToSourceData get() {<FILL_FUNCTION_BODY>} }
return context -> { LabeledSecretNormalizedSource source = (LabeledSecretNormalizedSource) context.normalizedSource(); return new LabeledSourceData() { @Override public MultipleSourcesContainer dataSupplier(Map<String, String> labels, Set<String> profiles) { return Fabric8ConfigUtils.secretsDataByLabels(context.client(), context.namespace(), labels, context.environment(), profiles); } }.compute(source.labels(), source.prefix(), source.target(), source.profileSpecificSources(), source.failFast(), context.namespace(), context.environment().getActiveProfiles()); };
222
170
392
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/NamedConfigMapContextToSourceDataProvider.java
NamedConfigMapContextToSourceDataProvider
generateSourceName
class NamedConfigMapContextToSourceDataProvider implements Supplier<Fabric8ContextToSourceData> { NamedConfigMapContextToSourceDataProvider() { } /* * Computes a ContextToSourceData (think content) for config map(s) based on name. * There could be potentially many config maps read (we also read profile based * sources). In such a case the name of the property source is going to be the * concatenated config map names, while the value is all the data that those config * maps hold. */ @Override public Fabric8ContextToSourceData get() { return context -> { NamedConfigMapNormalizedSource source = (NamedConfigMapNormalizedSource) context.normalizedSource(); return new NamedSourceData() { @Override protected String generateSourceName(String target, String sourceName, String namespace, String[] activeProfiles) {<FILL_FUNCTION_BODY>} @Override public MultipleSourcesContainer dataSupplier(LinkedHashSet<String> sourceNames) { return Fabric8ConfigUtils.configMapsDataByName(context.client(), context.namespace(), sourceNames, context.environment()); } }.compute(source.name().orElseThrow(), source.prefix(), source.target(), source.profileSpecificSources(), source.failFast(), context.namespace(), context.environment().getActiveProfiles()); }; } }
if (source.appendProfileToName()) { return ConfigUtils.sourceName(target, sourceName, namespace, activeProfiles); } return super.generateSourceName(target, sourceName, namespace, activeProfiles);
362
58
420
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/NamedSecretContextToSourceDataProvider.java
NamedSecretContextToSourceDataProvider
generateSourceName
class NamedSecretContextToSourceDataProvider implements Supplier<Fabric8ContextToSourceData> { NamedSecretContextToSourceDataProvider() { } @Override public Fabric8ContextToSourceData get() { return context -> { NamedSecretNormalizedSource source = (NamedSecretNormalizedSource) context.normalizedSource(); return new NamedSourceData() { @Override protected String generateSourceName(String target, String sourceName, String namespace, String[] activeProfiles) {<FILL_FUNCTION_BODY>} @Override public MultipleSourcesContainer dataSupplier(LinkedHashSet<String> sourceNames) { return Fabric8ConfigUtils.secretsDataByName(context.client(), context.namespace(), sourceNames, context.environment()); } }.compute(source.name().orElseThrow(), source.prefix(), source.target(), source.profileSpecificSources(), source.failFast(), context.namespace(), context.environment().getActiveProfiles()); }; } }
if (source.appendProfileToName()) { return ConfigUtils.sourceName(target, sourceName, namespace, activeProfiles); } return super.generateSourceName(target, sourceName, namespace, activeProfiles);
264
58
322
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/reload/Fabric8ConfigReloadAutoConfiguration.java
Fabric8ConfigReloadAutoConfiguration
secretsPropertyChangeEventWatcher
class Fabric8ConfigReloadAutoConfiguration { /** * Polling configMap ConfigurationChangeDetector. * @param properties config reload properties * @param strategy configuration update strategy * @param fabric8ConfigMapPropertySourceLocator configMap property source locator * @return a bean that listen to configuration changes and fire a reload. */ @Bean @ConditionalOnConfigMapsReloadEnabled @ConditionalOnBean(Fabric8ConfigMapPropertySourceLocator.class) @Conditional(PollingReloadDetectionMode.class) public ConfigurationChangeDetector configMapPropertyChangePollingWatcher(ConfigReloadProperties properties, ConfigurationUpdateStrategy strategy, Fabric8ConfigMapPropertySourceLocator fabric8ConfigMapPropertySourceLocator, TaskSchedulerWrapper<TaskScheduler> taskSchedulerWrapper, AbstractEnvironment environment) { return new PollingConfigMapChangeDetector(environment, properties, strategy, Fabric8ConfigMapPropertySource.class, fabric8ConfigMapPropertySourceLocator, taskSchedulerWrapper.getTaskScheduler()); } /** * Polling secrets ConfigurationChangeDetector. * @param properties config reload properties * @param strategy configuration update strategy * @param fabric8SecretsPropertySourceLocator secrets property source locator * @return a bean that listen to configuration changes and fire a reload. */ @Bean @ConditionalOnSecretsReloadEnabled @ConditionalOnBean(Fabric8SecretsPropertySourceLocator.class) @Conditional(PollingReloadDetectionMode.class) public ConfigurationChangeDetector secretsPropertyChangePollingWatcher(ConfigReloadProperties properties, ConfigurationUpdateStrategy strategy, Fabric8SecretsPropertySourceLocator fabric8SecretsPropertySourceLocator, TaskSchedulerWrapper<TaskScheduler> taskScheduler, AbstractEnvironment environment) { return new PollingSecretsChangeDetector(environment, properties, strategy, Fabric8SecretsPropertySource.class, fabric8SecretsPropertySourceLocator, taskScheduler.getTaskScheduler()); } /** * Event Based configMap ConfigurationChangeDetector. * @param properties config reload properties * @param strategy configuration update strategy * @param fabric8ConfigMapPropertySourceLocator configMap property source locator * @return a bean that listen to configMap change events and fire a reload. */ @Bean @ConditionalOnConfigMapsReloadEnabled @ConditionalOnBean(Fabric8ConfigMapPropertySourceLocator.class) @Conditional(EventReloadDetectionMode.class) public ConfigurationChangeDetector configMapPropertyChangeEventWatcher(ConfigReloadProperties properties, ConfigurationUpdateStrategy strategy, Fabric8ConfigMapPropertySourceLocator fabric8ConfigMapPropertySourceLocator, AbstractEnvironment environment, KubernetesClient kubernetesClient) { return new Fabric8EventBasedConfigMapChangeDetector(environment, properties, kubernetesClient, strategy, fabric8ConfigMapPropertySourceLocator, new KubernetesNamespaceProvider(environment)); } /** * Event Based secrets ConfigurationChangeDetector. * @param properties config reload properties * @param strategy configuration update strategy * @param fabric8SecretsPropertySourceLocator secrets property source locator * @return a bean that listen to secrets change events and fire a reload. */ @Bean @ConditionalOnSecretsReloadEnabled @ConditionalOnBean(Fabric8SecretsPropertySourceLocator.class) @Conditional(EventReloadDetectionMode.class) public ConfigurationChangeDetector secretsPropertyChangeEventWatcher(ConfigReloadProperties properties, ConfigurationUpdateStrategy strategy, Fabric8SecretsPropertySourceLocator fabric8SecretsPropertySourceLocator, AbstractEnvironment environment, KubernetesClient kubernetesClient) {<FILL_FUNCTION_BODY>} }
return new Fabric8EventBasedSecretsChangeDetector(environment, properties, kubernetesClient, strategy, fabric8SecretsPropertySourceLocator, new KubernetesNamespaceProvider(environment));
944
51
995
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/reload/Fabric8EventBasedConfigMapChangeDetector.java
Fabric8EventBasedConfigMapChangeDetector
inform
class Fabric8EventBasedConfigMapChangeDetector extends ConfigurationChangeDetector { private static final LogAccessor LOG = new LogAccessor( LogFactory.getLog(Fabric8EventBasedConfigMapChangeDetector.class)); private final Fabric8ConfigMapPropertySourceLocator fabric8ConfigMapPropertySourceLocator; private final KubernetesClient kubernetesClient; private final List<SharedIndexInformer<ConfigMap>> informers = new ArrayList<>(); private final Set<String> namespaces; private final boolean enableReloadFiltering; public Fabric8EventBasedConfigMapChangeDetector(AbstractEnvironment environment, ConfigReloadProperties properties, KubernetesClient kubernetesClient, ConfigurationUpdateStrategy strategy, Fabric8ConfigMapPropertySourceLocator fabric8ConfigMapPropertySourceLocator, KubernetesNamespaceProvider namespaceProvider) { super(environment, properties, strategy); this.kubernetesClient = kubernetesClient; this.fabric8ConfigMapPropertySourceLocator = fabric8ConfigMapPropertySourceLocator; this.enableReloadFiltering = properties.enableReloadFiltering(); namespaces = namespaces(kubernetesClient, namespaceProvider, properties, "configmap"); } @PostConstruct private void inform() {<FILL_FUNCTION_BODY>} @PreDestroy private void shutdown() { informers.forEach(SharedIndexInformer::close); // Ensure the kubernetes client is cleaned up from spare threads when shutting // down kubernetesClient.close(); } protected void onEvent(ConfigMap configMap) { boolean reload = ConfigReloadUtil.reload("config-map", configMap.toString(), fabric8ConfigMapPropertySourceLocator, environment, Fabric8ConfigMapPropertySource.class); if (reload) { reloadProperties(); } } private final class ConfigMapInformerAwareEventHandler implements ResourceEventHandler<ConfigMap> { private final SharedIndexInformer<ConfigMap> informer; private ConfigMapInformerAwareEventHandler(SharedIndexInformer<ConfigMap> informer) { this.informer = informer; } @Override public void onAdd(ConfigMap configMap) { LOG.debug("ConfigMap " + configMap.getMetadata().getName() + " was added in namespace " + configMap.getMetadata().getNamespace()); onEvent(configMap); } @Override public void onUpdate(ConfigMap oldConfigMap, ConfigMap newConfigMap) { LOG.debug("ConfigMap " + newConfigMap.getMetadata().getName() + " was updated in namespace " + newConfigMap.getMetadata().getNamespace()); if (Objects.equals(oldConfigMap.getData(), newConfigMap.getData())) { LOG.debug(() -> "data in configmap has not changed, will not reload"); } else { onEvent(newConfigMap); } } @Override public void onDelete(ConfigMap configMap, boolean deletedFinalStateUnknown) { LOG.debug("ConfigMap " + configMap.getMetadata().getName() + " was deleted in namespace " + configMap.getMetadata().getName()); onEvent(configMap); } @Override public void onNothing() { List<ConfigMap> store = informer.getStore().list(); LOG.info("onNothing called with a store of size : " + store.size()); LOG.info("this might be an indication of a HTTP_GONE code"); } } }
LOG.info("Kubernetes event-based configMap change detector activated"); namespaces.forEach(namespace -> { SharedIndexInformer<ConfigMap> informer; if (enableReloadFiltering) { informer = kubernetesClient.configMaps().inNamespace(namespace) .withLabels(Map.of(ConfigReloadProperties.RELOAD_LABEL_FILTER, "true")).inform(); LOG.debug("added configmap informer for namespace : " + namespace + " with enabled filter"); } else { informer = kubernetesClient.configMaps().inNamespace(namespace).inform(); LOG.debug("added configmap informer for namespace : " + namespace); } informer.addEventHandler(new ConfigMapInformerAwareEventHandler(informer)); informers.add(informer); });
899
226
1,125
<methods>public void <init>(org.springframework.core.env.ConfigurableEnvironment, ConfigReloadProperties, ConfigurationUpdateStrategy) ,public void reloadProperties() <variables>private static final org.springframework.core.log.LogAccessor LOG,protected org.springframework.core.env.ConfigurableEnvironment environment,protected ConfigReloadProperties properties,protected ConfigurationUpdateStrategy strategy
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-config/src/main/java/org/springframework/cloud/kubernetes/fabric8/config/reload/Fabric8EventBasedSecretsChangeDetector.java
SecretInformerAwareEventHandler
onDelete
class SecretInformerAwareEventHandler implements ResourceEventHandler<Secret> { private final SharedIndexInformer<Secret> informer; private SecretInformerAwareEventHandler(SharedIndexInformer<Secret> informer) { this.informer = informer; } @Override public void onAdd(Secret secret) { LOG.debug("Secret " + secret.getMetadata().getName() + " was added in namespace " + secret.getMetadata().getNamespace()); onEvent(secret); } @Override public void onUpdate(Secret oldSecret, Secret newSecret) { LOG.debug("Secret " + newSecret.getMetadata().getName() + " was updated in namespace " + newSecret.getMetadata().getNamespace()); if (Objects.equals(oldSecret.getData(), newSecret.getData())) { LOG.debug(() -> "data in secret has not changed, will not reload"); } else { onEvent(newSecret); } } @Override public void onDelete(Secret secret, boolean deletedFinalStateUnknown) {<FILL_FUNCTION_BODY>} @Override public void onNothing() { List<Secret> store = informer.getStore().list(); LOG.info("onNothing called with a store of size : " + store.size()); LOG.info("this might be an indication of a HTTP_GONE code"); } }
LOG.debug("Secret " + secret.getMetadata().getName() + " was deleted in namespace " + secret.getMetadata().getNamespace()); onEvent(secret);
366
46
412
<methods>public void <init>(org.springframework.core.env.ConfigurableEnvironment, ConfigReloadProperties, ConfigurationUpdateStrategy) ,public void reloadProperties() <variables>private static final org.springframework.core.log.LogAccessor LOG,protected org.springframework.core.env.ConfigurableEnvironment environment,protected ConfigReloadProperties properties,protected ConfigurationUpdateStrategy strategy
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8ConfigServerBootstrapper.java
Fabric8ConfigServerBootstrapper
initialize
class Fabric8ConfigServerBootstrapper extends KubernetesConfigServerBootstrapper { @Override public void initialize(BootstrapRegistry registry) {<FILL_FUNCTION_BODY>} }
if (hasConfigServerInstanceProvider()) { return; } registry.registerIfAbsent(KubernetesDiscoveryProperties.class, context -> { if (!getDiscoveryEnabled(context)) { return null; } return createKubernetesDiscoveryProperties(context); }); registry.registerIfAbsent(KubernetesClientProperties.class, context -> { if (!getDiscoveryEnabled(context)) { return null; } return createKubernetesClientProperties(context); }); // create instance provider registry.registerIfAbsent(ConfigServerInstanceProvider.Function.class, context -> { if (!getDiscoveryEnabled(context)) { return (id) -> Collections.emptyList(); } if (context.isRegistered(KubernetesDiscoveryClient.class)) { KubernetesDiscoveryClient client = context.get(KubernetesDiscoveryClient.class); return client::getInstances; } else { PropertyResolver propertyResolver = getPropertyResolver(context); Fabric8AutoConfiguration fabric8AutoConfiguration = new Fabric8AutoConfiguration(); Config config = fabric8AutoConfiguration .kubernetesClientConfig(context.get(KubernetesClientProperties.class)); KubernetesClient kubernetesClient = fabric8AutoConfiguration.kubernetesClient(config); KubernetesDiscoveryProperties discoveryProperties = context.get(KubernetesDiscoveryProperties.class); KubernetesDiscoveryClient discoveryClient = new KubernetesDiscoveryClient(kubernetesClient, discoveryProperties, KubernetesClientServicesFunctionProvider.servicesFunction(discoveryProperties, new KubernetesNamespaceProvider(propertyResolver .get(KubernetesNamespaceProvider.NAMESPACE_PROPERTY, String.class, null))), null, new ServicePortSecureResolver(discoveryProperties)); return discoveryClient::getInstances; } });
50
497
547
<methods>public non-sealed void <init>() ,public static KubernetesClientProperties createKubernetesClientProperties(org.springframework.boot.context.properties.bind.Binder, org.springframework.boot.context.properties.bind.BindHandler) ,public static KubernetesClientProperties createKubernetesClientProperties(org.springframework.boot.BootstrapContext) ,public static KubernetesDiscoveryProperties createKubernetesDiscoveryProperties(org.springframework.boot.context.properties.bind.Binder, org.springframework.boot.context.properties.bind.BindHandler) ,public static KubernetesDiscoveryProperties createKubernetesDiscoveryProperties(org.springframework.boot.BootstrapContext) ,public static java.lang.Boolean getDiscoveryEnabled(org.springframework.boot.context.properties.bind.Binder, org.springframework.boot.context.properties.bind.BindHandler) ,public static java.lang.Boolean getDiscoveryEnabled(org.springframework.boot.BootstrapContext) ,public static boolean hasConfigServerInstanceProvider() <variables>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8DiscoveryServicesAdapter.java
Fabric8DiscoveryServicesAdapter
filter
class Fabric8DiscoveryServicesAdapter implements Function<KubernetesClient, List<Service>> { private static final LogAccessor LOG = new LogAccessor(LogFactory.getLog(Fabric8DiscoveryServicesAdapter.class)); private static final SpelExpressionParser PARSER = new SpelExpressionParser(); private static final SimpleEvaluationContext EVALUATION_CONTEXT = SimpleEvaluationContext.forReadOnlyDataBinding() .withInstanceMethods().build(); private final KubernetesClientServicesFunction function; private final KubernetesDiscoveryProperties properties; private final Predicate<Service> filter; Fabric8DiscoveryServicesAdapter(KubernetesClientServicesFunction function, KubernetesDiscoveryProperties properties, Predicate<Service> filter) { this.function = function; this.properties = properties; if (filter == null) { this.filter = filter(); } else { this.filter = filter; } } @Override public List<Service> apply(KubernetesClient client) { if (!properties.namespaces().isEmpty()) { LOG.debug(() -> "searching in namespaces : " + properties.namespaces() + " with filter : " + properties.filter()); List<Service> services = new ArrayList<>(); properties.namespaces().forEach(namespace -> services.addAll(client.services().inNamespace(namespace) .withLabels(properties.serviceLabels()).list().getItems().stream().filter(filter).toList())); return services; } return function.apply(client).list().getItems().stream().filter(filter).toList(); } Predicate<Service> filter() {<FILL_FUNCTION_BODY>} }
String spelExpression = properties.filter(); Predicate<Service> predicate; if (spelExpression == null || spelExpression.isEmpty()) { predicate = service -> true; } else { Expression filterExpr = PARSER.parseExpression(spelExpression); predicate = service -> { Boolean include = filterExpr.getValue(EVALUATION_CONTEXT, service, Boolean.class); return Optional.ofNullable(include).orElse(false); }; } return predicate;
427
138
565
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8EndpointSliceV1CatalogWatch.java
Fabric8EndpointSliceV1CatalogWatch
apply
class Fabric8EndpointSliceV1CatalogWatch implements Function<Fabric8CatalogWatchContext, List<EndpointNameAndNamespace>> { private static final LogAccessor LOG = new LogAccessor(LogFactory.getLog(Fabric8EndpointSliceV1CatalogWatch.class)); @Override public List<EndpointNameAndNamespace> apply(Fabric8CatalogWatchContext context) {<FILL_FUNCTION_BODY>} private List<EndpointSlice> endpointSlices(Fabric8CatalogWatchContext context, String namespace, KubernetesClient client) { return client.discovery().v1().endpointSlices().inNamespace(namespace) .withLabels(context.properties().serviceLabels()).list().getItems(); } }
// take only pods that have endpoints List<EndpointSlice> endpointSlices; KubernetesClient client = context.kubernetesClient(); if (context.properties().allNamespaces()) { LOG.debug(() -> "discovering endpoint slices in all namespaces"); endpointSlices = client.discovery().v1().endpointSlices().inAnyNamespace() .withLabels(context.properties().serviceLabels()).list().getItems(); } else if (!context.properties().namespaces().isEmpty()) { LOG.debug(() -> "discovering endpoint slices in " + context.properties().namespaces()); List<EndpointSlice> inner = new ArrayList<>(context.properties().namespaces().size()); context.properties().namespaces() .forEach(namespace -> inner.addAll(endpointSlices(context, namespace, client))); endpointSlices = inner; } else { String namespace = Fabric8Utils.getApplicationNamespace(context.kubernetesClient(), null, "catalog-watcher", context.namespaceProvider()); LOG.debug(() -> "discovering endpoint slices in namespace : " + namespace); endpointSlices = endpointSlices(context, namespace, client); } Stream<ObjectReference> references = endpointSlices.stream().map(EndpointSlice::getEndpoints) .flatMap(List::stream).map(Endpoint::getTargetRef); return Fabric8CatalogWatchContext.state(references);
191
392
583
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8EndpointsCatalogWatch.java
Fabric8EndpointsCatalogWatch
apply
class Fabric8EndpointsCatalogWatch implements Function<Fabric8CatalogWatchContext, List<EndpointNameAndNamespace>> { @Override public List<EndpointNameAndNamespace> apply(Fabric8CatalogWatchContext context) {<FILL_FUNCTION_BODY>} }
List<Endpoints> endpoints = endpoints(context.properties(), context.kubernetesClient(), context.namespaceProvider(), "catalog-watcher", null, ALWAYS_TRUE); /** * <pre> * - An "Endpoints" holds a List of EndpointSubset. * - A single EndpointSubset holds a List of EndpointAddress * * - (The union of all EndpointSubsets is the Set of all Endpoints) * - Set of Endpoints is the cartesian product of : * EndpointSubset::getAddresses and EndpointSubset::getPorts (each is a List) * </pre> */ Stream<ObjectReference> references = endpoints.stream().map(Endpoints::getSubsets).filter(Objects::nonNull) .flatMap(List::stream).map(EndpointSubset::getAddresses).filter(Objects::nonNull).flatMap(List::stream) .map(EndpointAddress::getTargetRef); return Fabric8CatalogWatchContext.state(references);
73
271
344
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8KubernetesDiscoveryClientUtils.java
Fabric8KubernetesDiscoveryClientUtils
withFilter
class Fabric8KubernetesDiscoveryClientUtils { private static final LogAccessor LOG = new LogAccessor( LogFactory.getLog(Fabric8KubernetesDiscoveryClientUtils.class)); static final Predicate<Service> ALWAYS_TRUE = x -> true; private Fabric8KubernetesDiscoveryClientUtils() { } static List<Endpoints> endpoints(KubernetesDiscoveryProperties properties, KubernetesClient client, KubernetesNamespaceProvider namespaceProvider, String target, @Nullable String serviceName, Predicate<Service> filter) { List<Endpoints> endpoints; if (!properties.namespaces().isEmpty()) { LOG.debug(() -> "discovering endpoints in namespaces : " + properties.namespaces()); List<Endpoints> inner = new ArrayList<>(properties.namespaces().size()); properties.namespaces().forEach(namespace -> inner.addAll(filteredEndpoints( client.endpoints().inNamespace(namespace).withNewFilter(), properties, serviceName))); endpoints = inner; } else if (properties.allNamespaces()) { LOG.debug(() -> "discovering endpoints in all namespaces"); endpoints = filteredEndpoints(client.endpoints().inAnyNamespace().withNewFilter(), properties, serviceName); } else { String namespace = Fabric8Utils.getApplicationNamespace(client, null, target, namespaceProvider); LOG.debug(() -> "discovering endpoints in namespace : " + namespace); endpoints = filteredEndpoints(client.endpoints().inNamespace(namespace).withNewFilter(), properties, serviceName); } return withFilter(endpoints, properties, client, filter); } // see https://github.com/spring-cloud/spring-cloud-kubernetes/issues/1182 on why this // is needed static List<Endpoints> withFilter(List<Endpoints> endpoints, KubernetesDiscoveryProperties properties, KubernetesClient client, Predicate<Service> filter) {<FILL_FUNCTION_BODY>} /** * serviceName can be null, in which case the filter for "metadata.name" will not be * applied. */ static List<Endpoints> filteredEndpoints( FilterNested<FilterWatchListDeletable<Endpoints, EndpointsList, Resource<Endpoints>>> filterNested, KubernetesDiscoveryProperties properties, @Nullable String serviceName) { FilterNested<FilterWatchListDeletable<Endpoints, EndpointsList, Resource<Endpoints>>> partial = filterNested .withLabels(properties.serviceLabels()); if (serviceName != null) { partial = partial.withField("metadata.name", serviceName); } return partial.endFilter().list().getItems(); } static List<EndpointAddress> addresses(EndpointSubset endpointSubset, KubernetesDiscoveryProperties properties) { List<EndpointAddress> addresses = Optional.ofNullable(endpointSubset.getAddresses()).map(ArrayList::new) .orElse(new ArrayList<>()); if (properties.includeNotReadyAddresses()) { List<EndpointAddress> notReadyAddresses = endpointSubset.getNotReadyAddresses(); if (CollectionUtils.isEmpty(notReadyAddresses)) { return addresses; } addresses.addAll(notReadyAddresses); } return addresses; } static List<Service> services(KubernetesDiscoveryProperties properties, KubernetesClient client, KubernetesNamespaceProvider namespaceProvider, Predicate<Service> predicate, Map<String, String> fieldFilters, String target) { List<Service> services; if (properties.allNamespaces()) { LOG.debug(() -> "discovering services in all namespaces"); services = filteredServices(client.services().inAnyNamespace().withNewFilter(), properties, predicate, fieldFilters); } else if (!properties.namespaces().isEmpty()) { LOG.debug(() -> "discovering services in namespaces : " + properties.namespaces()); List<Service> inner = new ArrayList<>(properties.namespaces().size()); properties.namespaces().forEach( namespace -> inner.addAll(filteredServices(client.services().inNamespace(namespace).withNewFilter(), properties, predicate, fieldFilters))); services = inner; } else { String namespace = Fabric8Utils.getApplicationNamespace(client, null, target, namespaceProvider); LOG.debug(() -> "discovering services in namespace : " + namespace); services = filteredServices(client.services().inNamespace(namespace).withNewFilter(), properties, predicate, fieldFilters); } return services; } /** * a service is allowed to have a single port defined without a name. */ static Map<String, Integer> endpointSubsetsPortData(List<EndpointSubset> endpointSubsets) { return endpointSubsets.stream().flatMap(endpointSubset -> endpointSubset.getPorts().stream()) .collect(Collectors.toMap( endpointPort -> hasText(endpointPort.getName()) ? endpointPort.getName() : UNSET_PORT_NAME, EndpointPort::getPort)); } /** * serviceName can be null, in which case, such a filter will not be applied. */ private static List<Service> filteredServices( FilterNested<FilterWatchListDeletable<Service, ServiceList, ServiceResource<Service>>> filterNested, KubernetesDiscoveryProperties properties, Predicate<Service> predicate, @Nullable Map<String, String> fieldFilters) { FilterNested<FilterWatchListDeletable<Service, ServiceList, ServiceResource<Service>>> partial = filterNested .withLabels(properties.serviceLabels()); if (fieldFilters != null) { partial = partial.withFields(fieldFilters); } return partial.endFilter().list().getItems().stream().filter(predicate).toList(); } }
if (properties.filter() == null || properties.filter().isBlank() || filter == ALWAYS_TRUE) { LOG.debug(() -> "filter not present"); return endpoints; } List<Endpoints> result = new ArrayList<>(); // group by namespace in order to make a single API call per namespace when // retrieving services Map<String, List<Endpoints>> endpointsByNamespace = endpoints.stream() .collect(Collectors.groupingBy(x -> x.getMetadata().getNamespace())); for (Map.Entry<String, List<Endpoints>> entry : endpointsByNamespace.entrySet()) { // get all services in the namespace that match the filter Set<String> filteredServiceNames = client.services().inNamespace(entry.getKey()).list().getItems().stream() .filter(filter).map(service -> service.getMetadata().getName()).collect(Collectors.toSet()); // in the previous step we might have taken "too many" services, so in the // next one take only those that have a matching endpoints, by name. // This way we only get the endpoints that have a matching service with an // applied filter, it's like we filtered endpoints by that filter. result.addAll(entry.getValue().stream() .filter(endpoint -> filteredServiceNames.contains(endpoint.getMetadata().getName())).toList()); } return result;
1,545
363
1,908
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/Fabric8PodLabelsAndAnnotationsSupplier.java
Fabric8PodLabelsAndAnnotationsSupplier
apply
class Fabric8PodLabelsAndAnnotationsSupplier implements Function<String, PodLabelsAndAnnotations> { private final KubernetesClient client; private final String namespace; private Fabric8PodLabelsAndAnnotationsSupplier(KubernetesClient client, String namespace) { this.client = client; this.namespace = namespace; } /** * to be used when .spec.type of the Service is != 'ExternalName'. */ static Fabric8PodLabelsAndAnnotationsSupplier nonExternalName(KubernetesClient client, String namespace) { return new Fabric8PodLabelsAndAnnotationsSupplier(client, namespace); } /** * to be used when .spec.type of the Service is == 'ExternalName'. */ static Fabric8PodLabelsAndAnnotationsSupplier externalName() { return new Fabric8PodLabelsAndAnnotationsSupplier(null, null); } @Override public PodLabelsAndAnnotations apply(String podName) {<FILL_FUNCTION_BODY>} }
ObjectMeta metadata = Optional.ofNullable(client.pods().inNamespace(namespace).withName(podName).get()) .map(Pod::getMetadata).orElse(new ObjectMeta()); return new PodLabelsAndAnnotations(metadata.getLabels(), metadata.getAnnotations());
263
74
337
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesCatalogWatch.java
KubernetesCatalogWatch
catalogServicesWatch
class KubernetesCatalogWatch implements ApplicationEventPublisherAware { private static final String DISCOVERY_GROUP_VERSION = DISCOVERY_GROUP + "/" + DISCOVERY_VERSION; private static final LogAccessor LOG = new LogAccessor(LogFactory.getLog(KubernetesCatalogWatch.class)); private final Fabric8CatalogWatchContext context; private Function<Fabric8CatalogWatchContext, List<EndpointNameAndNamespace>> stateGenerator; private volatile List<EndpointNameAndNamespace> catalogEndpointsState = null; private ApplicationEventPublisher publisher; public KubernetesCatalogWatch(KubernetesClient kubernetesClient, KubernetesDiscoveryProperties properties, KubernetesNamespaceProvider namespaceProvider) { context = new Fabric8CatalogWatchContext(kubernetesClient, properties, namespaceProvider); } @Override public void setApplicationEventPublisher(ApplicationEventPublisher publisher) { this.publisher = publisher; } @Scheduled(fixedDelayString = "${" + CATALOG_WATCH_PROPERTY_WITH_DEFAULT_VALUE + "}") public void catalogServicesWatch() {<FILL_FUNCTION_BODY>} @PostConstruct void postConstruct() { stateGenerator = stateGenerator(); } Function<Fabric8CatalogWatchContext, List<EndpointNameAndNamespace>> stateGenerator() { Function<Fabric8CatalogWatchContext, List<EndpointNameAndNamespace>> localStateGenerator; if (context.properties().useEndpointSlices()) { // can't use try with resources here as it will close the client KubernetesClient client = context.kubernetesClient(); // this emulates : 'kubectl api-resources | grep -i EndpointSlice' boolean found = client.getApiGroups().getGroups().stream().flatMap(x -> x.getVersions().stream()) .map(GroupVersionForDiscovery::getGroupVersion).filter(DISCOVERY_GROUP_VERSION::equals).findFirst() .map(client::getApiResources).map(APIResourceList::getResources) .map(x -> x.stream().map(APIResource::getKind)) .flatMap(x -> x.filter(y -> y.equals(ENDPOINT_SLICE)).findFirst()).isPresent(); if (!found) { throw new IllegalArgumentException("EndpointSlices are not supported on the cluster"); } else { localStateGenerator = new Fabric8EndpointSliceV1CatalogWatch(); } } else { localStateGenerator = new Fabric8EndpointsCatalogWatch(); } LOG.debug(() -> "stateGenerator is of type: " + localStateGenerator.getClass().getSimpleName()); return localStateGenerator; } }
try { List<EndpointNameAndNamespace> currentState = stateGenerator.apply(context); if (!currentState.equals(catalogEndpointsState)) { LOG.debug(() -> "Received endpoints update from kubernetesClient: " + currentState); publisher.publishEvent(new HeartbeatEvent(this, currentState)); } catalogEndpointsState = currentState; } catch (Exception e) { LOG.error(e, () -> "Error watching Kubernetes Services"); }
699
142
841
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesClientServicesFunctionProvider.java
KubernetesClientServicesFunctionProvider
servicesFunction
class KubernetesClientServicesFunctionProvider { private KubernetesClientServicesFunctionProvider() { } public static KubernetesClientServicesFunction servicesFunction(KubernetesDiscoveryProperties properties, Environment environment) {<FILL_FUNCTION_BODY>} @Deprecated(forRemoval = true) public static KubernetesClientServicesFunction servicesFunction(KubernetesDiscoveryProperties properties, Binder binder, BindHandler bindHandler) { return servicesFunction(properties, new KubernetesNamespaceProvider(binder, bindHandler)); } public static KubernetesClientServicesFunction servicesFunction(KubernetesDiscoveryProperties properties, KubernetesNamespaceProvider namespaceProvider) { if (properties.allNamespaces()) { return (client) -> client.services().inAnyNamespace().withLabels(properties.serviceLabels()); } return client -> { String namespace = Fabric8Utils.getApplicationNamespace(client, null, "discovery-service", namespaceProvider); return client.services().inNamespace(namespace).withLabels(properties.serviceLabels()); }; } }
if (properties.allNamespaces()) { return (client) -> client.services().inAnyNamespace().withLabels(properties.serviceLabels()); } return client -> { String namespace = Fabric8Utils.getApplicationNamespace(client, null, "discovery-service", new KubernetesNamespaceProvider(environment)); return client.services().inNamespace(namespace).withLabels(properties.serviceLabels()); };
277
114
391
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClient.java
KubernetesDiscoveryClient
getInstances
class KubernetesDiscoveryClient implements DiscoveryClient, EnvironmentAware { private static final LogAccessor LOG = new LogAccessor(LogFactory.getLog(KubernetesDiscoveryClient.class)); private final KubernetesDiscoveryProperties properties; private final KubernetesClientServicesFunction kubernetesClientServicesFunction; private final ServicePortSecureResolver servicePortSecureResolver; private final Fabric8DiscoveryServicesAdapter adapter; private KubernetesClient client; private KubernetesNamespaceProvider namespaceProvider; public KubernetesDiscoveryClient(KubernetesClient client, KubernetesDiscoveryProperties kubernetesDiscoveryProperties, KubernetesClientServicesFunction kubernetesClientServicesFunction) { this(client, kubernetesDiscoveryProperties, kubernetesClientServicesFunction, null, new ServicePortSecureResolver(kubernetesDiscoveryProperties)); } KubernetesDiscoveryClient(KubernetesClient client, KubernetesDiscoveryProperties kubernetesDiscoveryProperties, KubernetesClientServicesFunction kubernetesClientServicesFunction, Predicate<Service> filter, ServicePortSecureResolver servicePortSecureResolver) { this.client = client; this.properties = kubernetesDiscoveryProperties; this.servicePortSecureResolver = servicePortSecureResolver; this.kubernetesClientServicesFunction = kubernetesClientServicesFunction; this.adapter = new Fabric8DiscoveryServicesAdapter(kubernetesClientServicesFunction, kubernetesDiscoveryProperties, filter); } public KubernetesClient getClient() { return this.client; } public void setClient(KubernetesClient client) { this.client = client; } @Override public String description() { return "Fabric8 Kubernetes Discovery Client"; } @Override public List<ServiceInstance> getInstances(String serviceId) {<FILL_FUNCTION_BODY>} public List<Endpoints> getEndPointsList(String serviceId) { return endpoints(properties, client, namespaceProvider, "fabric8-discovery", serviceId, adapter.filter()); } private List<ServiceInstance> serviceInstances(Endpoints endpoints, String serviceId) { List<EndpointSubset> subsets = endpoints.getSubsets(); if (subsets.isEmpty()) { LOG.debug(() -> "serviceId : " + serviceId + " does not have any subsets"); return List.of(); } String namespace = endpoints.getMetadata().getNamespace(); List<ServiceInstance> instances = new ArrayList<>(); Service service = client.services().inNamespace(namespace).withName(serviceId).get(); ServiceMetadata serviceMetadata = serviceMetadata(service); Map<String, Integer> portsData = endpointSubsetsPortData(subsets); Map<String, String> serviceInstanceMetadata = serviceInstanceMetadata(portsData, serviceMetadata, properties); for (EndpointSubset endpointSubset : subsets) { Map<String, Integer> endpointsPortData = endpointSubsetsPortData(List.of(endpointSubset)); ServicePortNameAndNumber portData = endpointsPort(endpointsPortData, serviceMetadata, properties); List<EndpointAddress> addresses = addresses(endpointSubset, properties); for (EndpointAddress endpointAddress : addresses) { Fabric8InstanceIdHostPodNameSupplier supplierOne = nonExternalName(endpointAddress, service); Fabric8PodLabelsAndAnnotationsSupplier supplierTwo = nonExternalName(client, namespace); ServiceInstance serviceInstance = serviceInstance(servicePortSecureResolver, serviceMetadata, supplierOne, supplierTwo, portData, serviceInstanceMetadata, properties); instances.add(serviceInstance); } } return instances; } @Override public List<String> getServices() { List<String> services = adapter.apply(client).stream().map(s -> s.getMetadata().getName()).distinct().toList(); LOG.debug(() -> "will return services : " + services); return services; } @Deprecated(forRemoval = true) public List<String> getServices(Predicate<Service> filter) { return new Fabric8DiscoveryServicesAdapter(kubernetesClientServicesFunction, properties, filter).apply(client) .stream().map(s -> s.getMetadata().getName()).distinct().toList(); } @Override public int getOrder() { return properties.order(); } @Deprecated(forRemoval = true) @Override public final void setEnvironment(Environment environment) { namespaceProvider = new KubernetesNamespaceProvider(environment); } }
Objects.requireNonNull(serviceId); List<Endpoints> allEndpoints = getEndPointsList(serviceId).stream().toList(); List<ServiceInstance> instances = new ArrayList<>(); for (Endpoints endpoints : allEndpoints) { // endpoints are only those that matched the serviceId instances.addAll(serviceInstances(endpoints, serviceId)); } if (properties.includeExternalNameServices()) { LOG.debug(() -> "Searching for 'ExternalName' type of services with serviceId : " + serviceId); List<Service> services = services(properties, client, namespaceProvider, s -> s.getSpec().getType().equals(EXTERNAL_NAME), Map.of("metadata.name", serviceId), "fabric8-discovery"); for (Service service : services) { ServiceMetadata serviceMetadata = serviceMetadata(service); Map<String, String> serviceInstanceMetadata = serviceInstanceMetadata(Map.of(), serviceMetadata, properties); Fabric8InstanceIdHostPodNameSupplier supplierOne = externalName(service); Fabric8PodLabelsAndAnnotationsSupplier supplierTwo = externalName(); ServiceInstance externalNameServiceInstance = serviceInstance(null, serviceMetadata, supplierOne, supplierTwo, new ServicePortNameAndNumber(-1, null), serviceInstanceMetadata, properties); instances.add(externalNameServiceInstance); } } return instances;
1,164
372
1,536
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/KubernetesDiscoveryClientAutoConfiguration.java
KubernetesDiscoveryClientAutoConfiguration
indicatorInitializer
class KubernetesDiscoveryClientAutoConfiguration { private static final LogAccessor LOG = new LogAccessor( LogFactory.getLog(KubernetesDiscoveryClientAutoConfiguration.class)); @Bean @ConditionalOnMissingBean public KubernetesClientServicesFunction servicesFunction(KubernetesDiscoveryProperties properties, Environment environment) { return KubernetesClientServicesFunctionProvider.servicesFunction(properties, environment); } @Bean @ConditionalOnMissingBean public KubernetesDiscoveryClient kubernetesDiscoveryClient(KubernetesClient client, KubernetesDiscoveryProperties properties, KubernetesClientServicesFunction kubernetesClientServicesFunction) { return new KubernetesDiscoveryClient(client, properties, kubernetesClientServicesFunction, null, new ServicePortSecureResolver(properties)); } @Bean @ConditionalOnSpringCloudKubernetesBlockingDiscoveryHealthInitializer public KubernetesDiscoveryClientHealthIndicatorInitializer indicatorInitializer( ApplicationEventPublisher applicationEventPublisher, PodUtils<?> podUtils) {<FILL_FUNCTION_BODY>} }
LOG.debug(() -> "Will publish InstanceRegisteredEvent from blocking implementation"); return new KubernetesDiscoveryClientHealthIndicatorInitializer(podUtils, applicationEventPublisher);
277
49
326
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/reactive/KubernetesReactiveDiscoveryClient.java
KubernetesReactiveDiscoveryClient
getInstances
class KubernetesReactiveDiscoveryClient implements ReactiveDiscoveryClient { private final KubernetesDiscoveryClient kubernetesDiscoveryClient; public KubernetesReactiveDiscoveryClient(KubernetesClient client, KubernetesDiscoveryProperties properties, KubernetesClientServicesFunction kubernetesClientServicesFunction) { this.kubernetesDiscoveryClient = new KubernetesDiscoveryClient(client, properties, kubernetesClientServicesFunction); } @Override public String description() { return "Fabric8 Kubernetes Reactive Discovery Client"; } @Override public Flux<ServiceInstance> getInstances(String serviceId) {<FILL_FUNCTION_BODY>} @Override public Flux<String> getServices() { return Flux.defer(() -> Flux.fromIterable(kubernetesDiscoveryClient.getServices())) .subscribeOn(Schedulers.boundedElastic()); } }
Assert.notNull(serviceId, "[Assertion failed] - the object argument must not be null"); return Flux.defer(() -> Flux.fromIterable(kubernetesDiscoveryClient.getInstances(serviceId))) .subscribeOn(Schedulers.boundedElastic());
235
74
309
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-discovery/src/main/java/org/springframework/cloud/kubernetes/fabric8/discovery/reactive/KubernetesReactiveDiscoveryClientAutoConfiguration.java
KubernetesReactiveDiscoveryClientAutoConfiguration
reactiveIndicatorInitializer
class KubernetesReactiveDiscoveryClientAutoConfiguration { private static final LogAccessor LOG = new LogAccessor( LogFactory.getLog(KubernetesReactiveDiscoveryClientAutoConfiguration.class)); @Bean @ConditionalOnMissingBean public KubernetesClientServicesFunction servicesFunction(KubernetesDiscoveryProperties properties, Environment environment) { return KubernetesClientServicesFunctionProvider.servicesFunction(properties, environment); } @Bean @ConditionalOnMissingBean public KubernetesReactiveDiscoveryClient kubernetesReactiveDiscoveryClient(KubernetesClient client, KubernetesDiscoveryProperties properties, KubernetesClientServicesFunction kubernetesClientServicesFunction) { return new KubernetesReactiveDiscoveryClient(client, properties, kubernetesClientServicesFunction); } /** * Post an event so that health indicator is initialized. */ @Bean @ConditionalOnClass(name = "org.springframework.boot.actuate.health.ReactiveHealthIndicator") @ConditionalOnDiscoveryHealthIndicatorEnabled KubernetesDiscoveryClientHealthIndicatorInitializer reactiveIndicatorInitializer( ApplicationEventPublisher applicationEventPublisher, PodUtils<?> podUtils) {<FILL_FUNCTION_BODY>} @Bean @ConditionalOnSpringCloudKubernetesReactiveDiscoveryHealthInitializer public ReactiveDiscoveryClientHealthIndicator kubernetesReactiveDiscoveryClientHealthIndicator( KubernetesReactiveDiscoveryClient client, DiscoveryClientHealthIndicatorProperties properties) { return new ReactiveDiscoveryClientHealthIndicator(client, properties); } }
LOG.debug(() -> "Will publish InstanceRegisteredEvent from reactive implementation"); return new KubernetesDiscoveryClientHealthIndicatorInitializer(podUtils, applicationEventPublisher);
407
50
457
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-istio/src/main/java/org/springframework/cloud/kubernetes/fabric8/client/istio/IstioBootstrapConfiguration.java
IstioDetectionConfiguration
addIstioProfile
class IstioDetectionConfiguration { private final MeshUtils utils; private final ConfigurableEnvironment environment; public IstioDetectionConfiguration(MeshUtils utils, ConfigurableEnvironment environment) { this.utils = utils; this.environment = environment; } @PostConstruct public void detectIstio() { addIstioProfile(this.environment); } void addIstioProfile(ConfigurableEnvironment environment) {<FILL_FUNCTION_BODY>} private boolean hasIstioProfile(Environment environment) { return Arrays.stream(environment.getActiveProfiles()).anyMatch(ISTIO_PROFILE::equalsIgnoreCase); } }
if (utils.isIstioEnabled()) { if (hasIstioProfile(environment)) { if (LOG.isDebugEnabled()) { LOG.debug("'istio' already in list of active profiles"); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Adding 'istio' to list of active profiles"); } environment.addActiveProfile(ISTIO_PROFILE); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Not running inside kubernetes with istio enabled. Skipping 'istio' profile activation."); } }
182
171
353
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-istio/src/main/java/org/springframework/cloud/kubernetes/fabric8/client/istio/utils/MeshUtils.java
MeshUtils
checkIstioServices
class MeshUtils { private static final Log LOG = LogFactory.getLog(MeshUtils.class); private final IstioClientProperties istioClientProperties; private final RestTemplate restTemplate = new RestTemplateBuilder().build(); public MeshUtils(IstioClientProperties istioClientProperties) { this.istioClientProperties = istioClientProperties; } public Boolean isIstioEnabled() { return checkIstioServices(); } private synchronized boolean checkIstioServices() {<FILL_FUNCTION_BODY>} }
try { // Check if Istio Envoy proxy is installed. Notice that the check is done to // localhost. // TODO: We can improve this initial detection if better methods are found. String resource = "http://localhost:" + this.istioClientProperties.getEnvoyPort(); ResponseEntity<String> response = this.restTemplate .getForEntity(resource + "/" + this.istioClientProperties.getTestPath(), String.class); if (response.getStatusCode().is2xxSuccessful()) { LOG.info("Istio Resources Found."); return true; } LOG.warn("Although Envoy proxy did respond at port" + this.istioClientProperties.getEnvoyPort() + ", it did not respond with HTTP 200 to path: " + this.istioClientProperties.getTestPath() + ". You may need to tweak the test path in order to get proper Istio support"); return false; } catch (Throwable t) { if (LOG.isDebugEnabled()) { LOG.debug("Envoy proxy could not be located at port: " + this.istioClientProperties.getEnvoyPort() + ". Assuming that the application is not running inside the Istio Service Mesh"); } return false; }
143
329
472
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-leader/src/main/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeaderAutoConfiguration.java
Fabric8LeaderAutoConfiguration
candidate
class Fabric8LeaderAutoConfiguration { /* * Used for publishing application events that happen: granted, revoked or failed to * acquire mutex. */ @Bean @ConditionalOnMissingBean(LeaderEventPublisher.class) public LeaderEventPublisher defaultLeaderEventPublisher(ApplicationEventPublisher applicationEventPublisher) { return new DefaultLeaderEventPublisher(applicationEventPublisher); } /* * This can be thought as "self" or the pod that participates in leader election * process. The implementation that we return simply logs events that happen during * that process. */ @Bean public Candidate candidate(LeaderProperties leaderProperties) throws UnknownHostException {<FILL_FUNCTION_BODY>} /* * Add an info contributor with leader information. */ @Bean @ConditionalOnClass(InfoContributor.class) public LeaderInfoContributor leaderInfoContributor(Fabric8LeadershipController fabric8LeadershipController, Candidate candidate) { return new LeaderInfoContributor(fabric8LeadershipController, candidate); } @Bean public Fabric8LeadershipController leadershipController(Candidate candidate, LeaderProperties leaderProperties, LeaderEventPublisher leaderEventPublisher, KubernetesClient kubernetesClient) { return new Fabric8LeadershipController(candidate, leaderProperties, leaderEventPublisher, kubernetesClient); } @Bean public Fabric8LeaderRecordWatcher leaderRecordWatcher(LeaderProperties leaderProperties, Fabric8LeadershipController fabric8LeadershipController, KubernetesClient kubernetesClient) { return new Fabric8LeaderRecordWatcher(leaderProperties, fabric8LeadershipController, kubernetesClient); } @Bean public Fabric8PodReadinessWatcher hostPodWatcher(Candidate candidate, KubernetesClient kubernetesClient, Fabric8LeadershipController fabric8LeadershipController) { return new Fabric8PodReadinessWatcher(candidate.getId(), kubernetesClient, fabric8LeadershipController); } @Bean(destroyMethod = "stop") public LeaderInitiator leaderInitiator(LeaderProperties leaderProperties, Fabric8LeadershipController fabric8LeadershipController, Fabric8LeaderRecordWatcher fabric8LeaderRecordWatcher, Fabric8PodReadinessWatcher hostPodWatcher) { return new LeaderInitiator(leaderProperties, fabric8LeadershipController, fabric8LeaderRecordWatcher, hostPodWatcher); } }
String id = LeaderUtils.hostName(); String role = leaderProperties.getRole(); return new DefaultCandidate(id, role);
639
38
677
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-leader/src/main/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeaderRecordWatcher.java
Fabric8LeaderRecordWatcher
onClose
class Fabric8LeaderRecordWatcher implements org.springframework.cloud.kubernetes.commons.leader.LeaderRecordWatcher, Watcher<ConfigMap> { private static final Logger LOGGER = LoggerFactory.getLogger(Fabric8LeaderRecordWatcher.class); private final Object lock = new Object(); private final Fabric8LeadershipController fabric8LeadershipController; private final LeaderProperties leaderProperties; private final KubernetesClient kubernetesClient; private Watch watch; public Fabric8LeaderRecordWatcher(LeaderProperties leaderProperties, Fabric8LeadershipController fabric8LeadershipController, KubernetesClient kubernetesClient) { this.fabric8LeadershipController = fabric8LeadershipController; this.leaderProperties = leaderProperties; this.kubernetesClient = kubernetesClient; } public void start() { if (this.watch == null) { synchronized (this.lock) { if (this.watch == null) { LOGGER.debug("Starting leader record watcher"); this.watch = this.kubernetesClient.configMaps() .inNamespace(this.leaderProperties.getNamespace(this.kubernetesClient.getNamespace())) .withName(this.leaderProperties.getConfigMapName()).watch(this); } } } } public void stop() { if (this.watch != null) { synchronized (this.lock) { if (this.watch != null) { LOGGER.debug("Stopping leader record watcher"); this.watch.close(); this.watch = null; } } } } @Override public void eventReceived(Action action, ConfigMap configMap) { LOGGER.debug("'{}' event received, triggering leadership update", action); if (!Action.ERROR.equals(action)) { this.fabric8LeadershipController.update(); } } @Override public void onClose(WatcherException cause) {<FILL_FUNCTION_BODY>} }
if (cause != null) { synchronized (this.lock) { LOGGER.warn("Watcher stopped unexpectedly, will restart", cause); this.watch = null; start(); } }
535
63
598
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-leader/src/main/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8LeadershipController.java
Fabric8LeadershipController
createConfigMap
class Fabric8LeadershipController extends LeadershipController { private static final Logger LOGGER = LoggerFactory.getLogger(Fabric8LeadershipController.class); private final KubernetesClient kubernetesClient; public Fabric8LeadershipController(Candidate candidate, LeaderProperties leaderProperties, LeaderEventPublisher leaderEventPublisher, KubernetesClient kubernetesClient) { super(candidate, leaderProperties, leaderEventPublisher); this.kubernetesClient = kubernetesClient; } @Override public synchronized void update() { LOGGER.debug("Checking leader state"); ConfigMap configMap = getConfigMap(); if (configMap == null && !leaderProperties.isCreateConfigMap()) { LOGGER.warn("ConfigMap '{}' does not exist and leaderProperties.isCreateConfigMap() " + "is false, cannot acquire leadership", leaderProperties.getConfigMapName()); notifyOnFailedToAcquire(); return; } Leader leader = extractLeader(configMap); if (leader != null && isPodReady(leader.getId())) { handleLeaderChange(leader); return; } if (leader != null && leader.isCandidate(this.candidate)) { revoke(configMap); } else { acquire(configMap); } } public synchronized void revoke() { ConfigMap configMap = getConfigMap(); Leader leader = extractLeader(configMap); if (leader != null && leader.isCandidate(this.candidate)) { revoke(configMap); } } private void revoke(ConfigMap configMap) { LOGGER.debug("Trying to revoke leadership for '{}'", this.candidate); try { String leaderKey = getLeaderKey(); removeConfigMapEntry(configMap, leaderKey); handleLeaderChange(null); } catch (KubernetesClientException e) { LOGGER.warn("Failure when revoking leadership for '{}': {}", this.candidate, e.getMessage()); } } private void acquire(ConfigMap configMap) { LOGGER.debug("Trying to acquire leadership for '{}'", this.candidate); if (!isPodReady(this.candidate.getId())) { LOGGER.debug("Pod of '{}' is not ready at the moment, cannot acquire leadership", this.candidate); return; } try { Map<String, String> data = getLeaderData(this.candidate); if (configMap == null) { createConfigMap(data); } else { updateConfigMapEntry(configMap, data); } Leader newLeader = new Leader(this.candidate.getRole(), this.candidate.getId()); handleLeaderChange(newLeader); } catch (KubernetesClientException e) { LOGGER.warn("Failure when acquiring leadership for '{}': {}", this.candidate, e.getMessage()); notifyOnFailedToAcquire(); } } @Override protected PodReadinessWatcher createPodReadinessWatcher(String localLeaderId) { return new Fabric8PodReadinessWatcher(localLeaderId, this.kubernetesClient, this); } private Leader extractLeader(ConfigMap configMap) { if (configMap == null) { return null; } return extractLeader(configMap.getData()); } private boolean isPodReady(String name) { return this.kubernetesClient.pods().withName(name).isReady(); } private ConfigMap getConfigMap() { return this.kubernetesClient.configMaps() .inNamespace(this.leaderProperties.getNamespace(this.kubernetesClient.getNamespace())) .withName(this.leaderProperties.getConfigMapName()).get(); } private void createConfigMap(Map<String, String> data) {<FILL_FUNCTION_BODY>} private void updateConfigMapEntry(ConfigMap configMap, Map<String, String> newData) { LOGGER.debug("Adding new data to config map: {}", newData); ConfigMap newConfigMap = new ConfigMapBuilder(configMap).addToData(newData).build(); updateConfigMap(configMap, newConfigMap); } private void removeConfigMapEntry(ConfigMap configMap, String key) { LOGGER.debug("Removing config map entry '{}'", key); ConfigMap newConfigMap = new ConfigMapBuilder(configMap).removeFromData(key).build(); updateConfigMap(configMap, newConfigMap); } private void updateConfigMap(ConfigMap oldConfigMap, ConfigMap newConfigMap) { this.kubernetesClient.configMaps() .inNamespace(this.leaderProperties.getNamespace(this.kubernetesClient.getNamespace())) .resource(newConfigMap).lockResourceVersion(oldConfigMap.getMetadata().getResourceVersion()).replace(); } }
LOGGER.debug("Creating new config map with data: {}", data); ConfigMap newConfigMap = new ConfigMapBuilder().withNewMetadata() .withName(this.leaderProperties.getConfigMapName()).addToLabels(PROVIDER_KEY, PROVIDER) .addToLabels(KIND_KEY, KIND).endMetadata().addToData(data).build(); this.kubernetesClient.configMaps() .inNamespace(this.leaderProperties.getNamespace(this.kubernetesClient.getNamespace())) .resource(newConfigMap).create();
1,310
151
1,461
<methods>public void <init>(org.springframework.integration.leader.Candidate, org.springframework.cloud.kubernetes.commons.leader.LeaderProperties, org.springframework.integration.leader.event.LeaderEventPublisher) ,public Optional<org.springframework.cloud.kubernetes.commons.leader.Leader> getLocalLeader() ,public abstract void revoke() ,public abstract void update() <variables>protected static final java.lang.String KIND,protected static final java.lang.String KIND_KEY,private static final org.slf4j.Logger LOGGER,protected static final java.lang.String PROVIDER,protected static final java.lang.String PROVIDER_KEY,protected org.springframework.integration.leader.Candidate candidate,protected org.springframework.integration.leader.event.LeaderEventPublisher leaderEventPublisher,protected org.springframework.cloud.kubernetes.commons.leader.LeaderProperties leaderProperties,protected org.springframework.cloud.kubernetes.commons.leader.PodReadinessWatcher leaderReadinessWatcher,protected org.springframework.cloud.kubernetes.commons.leader.Leader localLeader
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-leader/src/main/java/org/springframework/cloud/kubernetes/fabric8/leader/Fabric8PodReadinessWatcher.java
Fabric8PodReadinessWatcher
stop
class Fabric8PodReadinessWatcher implements PodReadinessWatcher, Watcher<Pod> { private static final Logger LOGGER = LoggerFactory.getLogger(Fabric8PodReadinessWatcher.class); private final Object lock = new Object(); private final String podName; private final KubernetesClient kubernetesClient; private final Fabric8LeadershipController fabric8LeadershipController; private boolean previousState; private Watch watch; public Fabric8PodReadinessWatcher(String podName, KubernetesClient kubernetesClient, Fabric8LeadershipController fabric8LeadershipController) { this.podName = podName; this.kubernetesClient = kubernetesClient; this.fabric8LeadershipController = fabric8LeadershipController; } @Override public void start() { if (this.watch == null) { synchronized (this.lock) { if (this.watch == null) { LOGGER.debug("Starting pod readiness watcher for '{}'", this.podName); PodResource podResource = this.kubernetesClient.pods().withName(this.podName); this.previousState = podResource.isReady(); this.watch = podResource.watch(this); } } } } @Override public void stop() {<FILL_FUNCTION_BODY>} @Override public void eventReceived(Action action, Pod pod) { boolean currentState = Readiness.isPodReady(pod); if (this.previousState != currentState) { synchronized (this.lock) { if (this.previousState != currentState) { LOGGER.debug("'{}' readiness status changed to '{}', triggering leadership update", this.podName, currentState); this.previousState = currentState; this.fabric8LeadershipController.update(); } } } } @Override public void onClose(WatcherException cause) { if (cause != null) { synchronized (this.lock) { LOGGER.warn("Watcher stopped unexpectedly, will restart", cause); this.watch = null; start(); } } } }
if (this.watch != null) { synchronized (this.lock) { if (this.watch != null) { LOGGER.debug("Stopping pod readiness watcher for '{}'", this.podName); this.watch.close(); this.watch = null; } } }
576
88
664
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServiceInstanceMapper.java
Fabric8ServiceInstanceMapper
secure
class Fabric8ServiceInstanceMapper implements KubernetesServiceInstanceMapper<Service> { private static final LogAccessor LOG = new LogAccessor(LogFactory.getLog(Fabric8ServiceInstanceMapper.class)); /** * empty on purpose, load balancer implementation does not need them. */ private static final Map<String, Integer> PORTS_DATA = Map.of(); private final KubernetesLoadBalancerProperties properties; private final KubernetesDiscoveryProperties discoveryProperties; private final ServicePortSecureResolver resolver; Fabric8ServiceInstanceMapper(KubernetesLoadBalancerProperties properties, KubernetesDiscoveryProperties discoveryProperties) { this.properties = properties; this.discoveryProperties = discoveryProperties; resolver = new ServicePortSecureResolver(discoveryProperties); } @Override public KubernetesServiceInstance map(Service service) { ObjectMeta metadata = service.getMetadata(); List<ServicePort> ports = service.getSpec().getPorts(); ServicePort port; if (ports.isEmpty()) { LOG.warn(() -> "service : " + metadata.getName() + " does not have any ServicePort(s)," + " will not consider it for load balancing"); return null; } if (ports.size() == 1) { LOG.debug(() -> "single ServicePort found, will use it as-is " + "(without checking " + PORT_NAME_PROPERTY + ")"); port = ports.get(0); } else { String portNameFromProperties = properties.getPortName(); if (StringUtils.hasText(portNameFromProperties)) { Optional<ServicePort> optionalPort = ports.stream() .filter(x -> Objects.equals(x.getName(), portNameFromProperties)).findAny(); if (optionalPort.isPresent()) { LOG.debug(() -> "found port name that matches : " + portNameFromProperties); port = optionalPort.get(); } else { logWarning(portNameFromProperties); port = ports.get(0); } } else { LOG.warn(() -> PORT_NAME_PROPERTY + " is not set"); LOG.warn(() -> NON_DETERMINISTIC_PORT_MESSAGE); port = ports.get(0); } } String host = KubernetesServiceInstanceMapper.createHost(service.getMetadata().getName(), service.getMetadata().getNamespace(), properties.getClusterDomain()); boolean secure = secure(port, service); return new DefaultKubernetesServiceInstance(metadata.getUid(), metadata.getName(), host, port.getPort(), serviceMetadata(service), secure); } Map<String, String> serviceMetadata(Service service) { ServiceMetadata serviceMetadata = Fabric8Utils.serviceMetadata(service); return DiscoveryClientUtils.serviceInstanceMetadata(PORTS_DATA, serviceMetadata, discoveryProperties); } private boolean secure(ServicePort port, Service service) {<FILL_FUNCTION_BODY>} private void logWarning(String portNameFromProperties) { LOG.warn(() -> "Did not find a port name that is equal to the value " + portNameFromProperties); LOG.warn(() -> NON_DETERMINISTIC_PORT_MESSAGE); } }
ObjectMeta metadata = service.getMetadata(); ServicePortNameAndNumber portNameAndNumber = new ServicePortNameAndNumber(port.getPort(), port.getName()); Input input = new Input(portNameAndNumber, metadata.getName(), metadata.getLabels(), metadata.getAnnotations()); return resolver.resolve(input);
859
84
943
<no_super_class>
spring-cloud_spring-cloud-kubernetes
spring-cloud-kubernetes/spring-cloud-kubernetes-fabric8-loadbalancer/src/main/java/org/springframework/cloud/kubernetes/fabric8/loadbalancer/Fabric8ServicesListSupplier.java
Fabric8ServicesListSupplier
get
class Fabric8ServicesListSupplier extends KubernetesServicesListSupplier<Service> { private static final LogAccessor LOG = new LogAccessor(LogFactory.getLog(Fabric8ServicesListSupplier.class)); private final KubernetesClient kubernetesClient; private final KubernetesNamespaceProvider namespaceProvider; Fabric8ServicesListSupplier(Environment environment, KubernetesClient kubernetesClient, Fabric8ServiceInstanceMapper mapper, KubernetesDiscoveryProperties discoveryProperties) { super(environment, mapper, discoveryProperties); this.kubernetesClient = kubernetesClient; namespaceProvider = new KubernetesNamespaceProvider(environment); } @Override public Flux<List<ServiceInstance>> get() {<FILL_FUNCTION_BODY>} private void addMappedService(KubernetesServiceInstanceMapper<Service> mapper, List<ServiceInstance> services, Service service) { services.add(mapper.map(service)); } }
List<ServiceInstance> result = new ArrayList<>(); String serviceName = getServiceId(); LOG.debug(() -> "serviceID : " + serviceName); if (discoveryProperties.allNamespaces()) { LOG.debug(() -> "discovering services in all namespaces"); List<Service> services = kubernetesClient.services().inAnyNamespace() .withField("metadata.name", serviceName).list().getItems(); services.forEach(service -> addMappedService(mapper, result, service)); } else if (!discoveryProperties.namespaces().isEmpty()) { List<String> selectiveNamespaces = discoveryProperties.namespaces().stream().sorted().toList(); LOG.debug(() -> "discovering services in selective namespaces : " + selectiveNamespaces); selectiveNamespaces.forEach(selectiveNamespace -> { Service service = kubernetesClient.services().inNamespace(selectiveNamespace).withName(serviceName) .get(); if (service != null) { addMappedService(mapper, result, service); } else { LOG.debug(() -> "did not find service with name : " + serviceName + " in namespace : " + selectiveNamespace); } }); } else { String namespace = Fabric8Utils.getApplicationNamespace(kubernetesClient, null, "loadbalancer-service", namespaceProvider); LOG.debug(() -> "discovering services in namespace : " + namespace); Service service = kubernetesClient.services().inNamespace(namespace).withName(serviceName).get(); if (service != null) { addMappedService(mapper, result, service); } else { LOG.debug(() -> "did not find service with name : " + serviceName + " in namespace : " + namespace); } } LOG.debug(() -> "found services : " + result); return Flux.defer(() -> Flux.just(result));
249
520
769
<methods>public void <init>(org.springframework.core.env.Environment, KubernetesServiceInstanceMapper<io.fabric8.kubernetes.api.model.Service>, KubernetesDiscoveryProperties) ,public abstract Flux<List<org.springframework.cloud.client.ServiceInstance>> get() ,public java.lang.String getServiceId() <variables>protected final non-sealed KubernetesDiscoveryProperties discoveryProperties,protected final non-sealed org.springframework.core.env.Environment environment,protected final non-sealed KubernetesServiceInstanceMapper<io.fabric8.kubernetes.api.model.Service> mapper
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaClient.java
CloudEurekaClient
getEurekaHttpClient
class CloudEurekaClient extends DiscoveryClient { private static final Log log = LogFactory.getLog(CloudEurekaClient.class); private final AtomicLong cacheRefreshedCount = new AtomicLong(0); private final ApplicationEventPublisher publisher; private final Field eurekaTransportField; private final ApplicationInfoManager applicationInfoManager; private final AtomicReference<EurekaHttpClient> eurekaHttpClient = new AtomicReference<>(); public CloudEurekaClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config, TransportClientFactories transportClientFactories, ApplicationEventPublisher publisher) { this(applicationInfoManager, config, transportClientFactories, null, publisher); } public CloudEurekaClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config, TransportClientFactories transportClientFactories, AbstractDiscoveryClientOptionalArgs<?> args, ApplicationEventPublisher publisher) { super(applicationInfoManager, config, transportClientFactories, args); this.applicationInfoManager = applicationInfoManager; this.publisher = publisher; this.eurekaTransportField = ReflectionUtils.findField(DiscoveryClient.class, "eurekaTransport"); ReflectionUtils.makeAccessible(this.eurekaTransportField); } public ApplicationInfoManager getApplicationInfoManager() { return applicationInfoManager; } public void cancelOverrideStatus(InstanceInfo info) { getEurekaHttpClient().deleteStatusOverride(info.getAppName(), info.getId(), info); } public InstanceInfo getInstanceInfo(String appname, String instanceId) { EurekaHttpResponse<InstanceInfo> response = getEurekaHttpClient().getInstance(appname, instanceId); HttpStatus httpStatus = HttpStatus.valueOf(response.getStatusCode()); if (httpStatus.is2xxSuccessful() && response.getEntity() != null) { return response.getEntity(); } return null; } EurekaHttpClient getEurekaHttpClient() {<FILL_FUNCTION_BODY>} public void setStatus(InstanceStatus newStatus, InstanceInfo info) { getEurekaHttpClient().statusUpdate(info.getAppName(), info.getId(), newStatus, info); } @Override protected void onCacheRefreshed() { super.onCacheRefreshed(); if (this.cacheRefreshedCount != null) { // might be called during construction and // will be null long newCount = this.cacheRefreshedCount.incrementAndGet(); log.trace("onCacheRefreshed called with count: " + newCount); this.publisher.publishEvent(new HeartbeatEvent(this, newCount)); } } }
if (this.eurekaHttpClient.get() == null) { try { Object eurekaTransport = this.eurekaTransportField.get(this); Field registrationClientField = ReflectionUtils.findField(eurekaTransport.getClass(), "registrationClient"); ReflectionUtils.makeAccessible(registrationClientField); this.eurekaHttpClient.compareAndSet(null, (EurekaHttpClient) registrationClientField.get(eurekaTransport)); } catch (IllegalAccessException e) { log.error("error getting EurekaHttpClient", e); } } return this.eurekaHttpClient.get();
694
180
874
<methods>public void <init>(com.netflix.appinfo.ApplicationInfoManager, com.netflix.discovery.EurekaClientConfig, TransportClientFactories#RAW) ,public void <init>(com.netflix.appinfo.ApplicationInfoManager, com.netflix.discovery.EurekaClientConfig, TransportClientFactories#RAW, AbstractDiscoveryClientOptionalArgs#RAW) ,public void <init>(com.netflix.appinfo.ApplicationInfoManager, com.netflix.discovery.EurekaClientConfig, TransportClientFactories#RAW, AbstractDiscoveryClientOptionalArgs#RAW, com.netflix.discovery.shared.resolver.EndpointRandomizer) ,public Set<java.lang.String> getAllKnownRegions() ,public com.netflix.discovery.shared.Application getApplication(java.lang.String) ,public com.netflix.appinfo.ApplicationInfoManager getApplicationInfoManager() ,public com.netflix.discovery.shared.Applications getApplications() ,public com.netflix.discovery.shared.Applications getApplications(java.lang.String) ,public com.netflix.discovery.shared.Applications getApplicationsForARegion(java.lang.String) ,public List<java.lang.String> getDiscoveryServiceUrls(java.lang.String) ,public static Set<java.lang.String> getEC2DiscoveryUrlsFromZone(java.lang.String, com.netflix.discovery.endpoint.EndpointUtils.DiscoveryUrlType) ,public com.netflix.discovery.EurekaClientConfig getEurekaClientConfig() ,public static List<java.lang.String> getEurekaServiceUrlsFromConfig(java.lang.String, boolean) ,public com.netflix.appinfo.HealthCheckHandler getHealthCheckHandler() ,public com.netflix.appinfo.InstanceInfo.InstanceStatus getInstanceRemoteStatus() ,public List<com.netflix.appinfo.InstanceInfo> getInstancesById(java.lang.String) ,public List<com.netflix.appinfo.InstanceInfo> getInstancesByVipAddress(java.lang.String, boolean) ,public List<com.netflix.appinfo.InstanceInfo> getInstancesByVipAddress(java.lang.String, boolean, java.lang.String) ,public List<com.netflix.appinfo.InstanceInfo> getInstancesByVipAddressAndAppName(java.lang.String, java.lang.String, boolean) ,public long getLastSuccessfulHeartbeatTimePeriod() ,public long getLastSuccessfulRegistryFetchTimePeriod() ,public com.netflix.appinfo.InstanceInfo getNextServerFromEureka(java.lang.String, boolean) ,public static java.lang.String getRegion() ,public List<java.lang.String> getServiceUrlsFromConfig(java.lang.String, boolean) ,public List<java.lang.String> getServiceUrlsFromDNS(java.lang.String, boolean) ,public com.netflix.discovery.DiscoveryClient.Stats getStats() ,public static java.lang.String getZone(com.netflix.appinfo.InstanceInfo) ,public int localRegistrySize() ,public void registerEventListener(com.netflix.discovery.EurekaEventListener) ,public void registerHealthCheck(com.netflix.appinfo.HealthCheckHandler) ,public void registerHealthCheckCallback(com.netflix.appinfo.HealthCheckCallback) ,public synchronized void shutdown() ,public boolean unregisterEventListener(com.netflix.discovery.EurekaEventListener) <variables>private static final java.lang.String COMMA_STRING,private final com.netflix.servo.monitor.Timer FETCH_REGISTRY_TIMER,public static final java.lang.String HTTP_X_DISCOVERY_ALLOW_REDIRECT,private static final java.lang.String PREFIX,private final com.netflix.servo.monitor.Counter RECONCILE_HASH_CODES_MISMATCH,private final com.netflix.servo.monitor.Counter REREGISTER_COUNTER,private static final java.lang.String VALUE_DELIMITER,private java.lang.String appPathIdentifier,private final com.netflix.appinfo.ApplicationInfoManager applicationInfoManager,private final Provider<com.netflix.discovery.BackupRegistry> backupRegistryProvider,private final java.util.concurrent.ThreadPoolExecutor cacheRefreshExecutor,private com.netflix.discovery.TimedSupervisorTask cacheRefreshTask,protected final com.netflix.discovery.EurekaClientConfig clientConfig,private final com.netflix.discovery.shared.resolver.EndpointRandomizer endpointRandomizer,private final com.netflix.discovery.DiscoveryClient.EurekaTransport eurekaTransport,private final CopyOnWriteArraySet<com.netflix.discovery.EurekaEventListener> eventListeners,private final java.util.concurrent.atomic.AtomicLong fetchRegistryGeneration,private final java.util.concurrent.locks.Lock fetchRegistryUpdateLock,private final Provider<com.netflix.appinfo.HealthCheckCallback> healthCheckCallbackProvider,private final Provider<com.netflix.appinfo.HealthCheckHandler> healthCheckHandlerProvider,private final AtomicReference<com.netflix.appinfo.HealthCheckHandler> healthCheckHandlerRef,private final java.util.concurrent.ThreadPoolExecutor heartbeatExecutor,private final com.netflix.discovery.util.ThresholdLevelsMetric heartbeatStalenessMonitor,private com.netflix.discovery.TimedSupervisorTask heartbeatTask,private final int initRegistrySize,private final long initTimestampMs,private final com.netflix.appinfo.InstanceInfo instanceInfo,private com.netflix.discovery.InstanceInfoReplicator instanceInfoReplicator,private final com.netflix.discovery.InstanceRegionChecker instanceRegionChecker,private final java.util.concurrent.atomic.AtomicBoolean isShutdown,private volatile com.netflix.appinfo.InstanceInfo.InstanceStatus lastRemoteInstanceStatus,private volatile long lastSuccessfulHeartbeatTimestamp,private volatile long lastSuccessfulRegistryFetchTimestamp,private final AtomicReference<com.netflix.discovery.shared.Applications> localRegionApps,private static final org.slf4j.Logger logger,private final com.netflix.discovery.PreRegistrationHandler preRegistrationHandler,private volatile int registrySize,private final com.netflix.discovery.util.ThresholdLevelsMetric registryStalenessMonitor,private volatile Map<java.lang.String,com.netflix.discovery.shared.Applications> remoteRegionVsApps,private final AtomicReference<java.lang.String[]> remoteRegionsRef,private final AtomicReference<java.lang.String> remoteRegionsToFetch,private final java.util.concurrent.ScheduledExecutorService scheduler,private static com.netflix.discovery.EurekaClientConfig staticClientConfig,private final com.netflix.discovery.DiscoveryClient.Stats stats,private com.netflix.appinfo.ApplicationInfoManager.StatusChangeListener statusChangeListener,protected final TransportClientFactories#RAW transportClientFactories,protected final com.netflix.discovery.shared.transport.EurekaTransportConfig transportConfig,private final com.netflix.discovery.endpoint.EndpointUtils.ServiceUrlRandomizer urlRandomizer
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/CloudEurekaTransportConfig.java
CloudEurekaTransportConfig
hashCode
class CloudEurekaTransportConfig implements EurekaTransportConfig { private int sessionedClientReconnectIntervalSeconds = 20 * 60; private double retryableClientQuarantineRefreshPercentage = 0.66; private int bootstrapResolverRefreshIntervalSeconds = 5 * 60; private int applicationsResolverDataStalenessThresholdSeconds = 5 * 60; private int asyncResolverRefreshIntervalMs = 5 * 60 * 1000; private int asyncResolverWarmUpTimeoutMs = 5000; private int asyncExecutorThreadPoolSize = 5; private String readClusterVip; private String writeClusterVip; private boolean bootstrapResolverForQuery = true; private String bootstrapResolverStrategy; private boolean applicationsResolverUseIp = false; @Override public boolean useBootstrapResolverForQuery() { return this.bootstrapResolverForQuery; } @Override public boolean applicationsResolverUseIp() { return this.applicationsResolverUseIp; } public int getSessionedClientReconnectIntervalSeconds() { return sessionedClientReconnectIntervalSeconds; } public void setSessionedClientReconnectIntervalSeconds(int sessionedClientReconnectIntervalSeconds) { this.sessionedClientReconnectIntervalSeconds = sessionedClientReconnectIntervalSeconds; } public double getRetryableClientQuarantineRefreshPercentage() { return retryableClientQuarantineRefreshPercentage; } public void setRetryableClientQuarantineRefreshPercentage(double retryableClientQuarantineRefreshPercentage) { this.retryableClientQuarantineRefreshPercentage = retryableClientQuarantineRefreshPercentage; } public int getBootstrapResolverRefreshIntervalSeconds() { return bootstrapResolverRefreshIntervalSeconds; } public void setBootstrapResolverRefreshIntervalSeconds(int bootstrapResolverRefreshIntervalSeconds) { this.bootstrapResolverRefreshIntervalSeconds = bootstrapResolverRefreshIntervalSeconds; } public int getApplicationsResolverDataStalenessThresholdSeconds() { return applicationsResolverDataStalenessThresholdSeconds; } public void setApplicationsResolverDataStalenessThresholdSeconds( int applicationsResolverDataStalenessThresholdSeconds) { this.applicationsResolverDataStalenessThresholdSeconds = applicationsResolverDataStalenessThresholdSeconds; } public int getAsyncResolverRefreshIntervalMs() { return asyncResolverRefreshIntervalMs; } public void setAsyncResolverRefreshIntervalMs(int asyncResolverRefreshIntervalMs) { this.asyncResolverRefreshIntervalMs = asyncResolverRefreshIntervalMs; } public int getAsyncResolverWarmUpTimeoutMs() { return asyncResolverWarmUpTimeoutMs; } public void setAsyncResolverWarmUpTimeoutMs(int asyncResolverWarmUpTimeoutMs) { this.asyncResolverWarmUpTimeoutMs = asyncResolverWarmUpTimeoutMs; } public int getAsyncExecutorThreadPoolSize() { return asyncExecutorThreadPoolSize; } public void setAsyncExecutorThreadPoolSize(int asyncExecutorThreadPoolSize) { this.asyncExecutorThreadPoolSize = asyncExecutorThreadPoolSize; } public String getReadClusterVip() { return readClusterVip; } public void setReadClusterVip(String readClusterVip) { this.readClusterVip = readClusterVip; } public String getWriteClusterVip() { return writeClusterVip; } public void setWriteClusterVip(String writeClusterVip) { this.writeClusterVip = writeClusterVip; } public boolean isBootstrapResolverForQuery() { return bootstrapResolverForQuery; } public void setBootstrapResolverForQuery(boolean bootstrapResolverForQuery) { this.bootstrapResolverForQuery = bootstrapResolverForQuery; } public String getBootstrapResolverStrategy() { return bootstrapResolverStrategy; } public void setBootstrapResolverStrategy(String bootstrapResolverStrategy) { this.bootstrapResolverStrategy = bootstrapResolverStrategy; } public boolean isApplicationsResolverUseIp() { return applicationsResolverUseIp; } public void setApplicationsResolverUseIp(boolean applicationsResolverUseIp) { this.applicationsResolverUseIp = applicationsResolverUseIp; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CloudEurekaTransportConfig that = (CloudEurekaTransportConfig) o; return sessionedClientReconnectIntervalSeconds == that.sessionedClientReconnectIntervalSeconds && Double.compare(retryableClientQuarantineRefreshPercentage, that.retryableClientQuarantineRefreshPercentage) == 0 && bootstrapResolverRefreshIntervalSeconds == that.bootstrapResolverRefreshIntervalSeconds && applicationsResolverDataStalenessThresholdSeconds == that.applicationsResolverDataStalenessThresholdSeconds && asyncResolverRefreshIntervalMs == that.asyncResolverRefreshIntervalMs && asyncResolverWarmUpTimeoutMs == that.asyncResolverWarmUpTimeoutMs && asyncExecutorThreadPoolSize == that.asyncExecutorThreadPoolSize && Objects.equals(readClusterVip, that.readClusterVip) && Objects.equals(writeClusterVip, that.writeClusterVip) && bootstrapResolverForQuery == that.bootstrapResolverForQuery && Objects.equals(bootstrapResolverStrategy, that.bootstrapResolverStrategy) && applicationsResolverUseIp == that.applicationsResolverUseIp; } @Override public int hashCode() {<FILL_FUNCTION_BODY>} @Override public String toString() { return new StringBuilder("CloudEurekaTransportConfig{").append("sessionedClientReconnectIntervalSeconds=") .append(sessionedClientReconnectIntervalSeconds).append(", ") .append("retryableClientQuarantineRefreshPercentage=") .append(retryableClientQuarantineRefreshPercentage).append(", ") .append("bootstrapResolverRefreshIntervalSeconds=").append(bootstrapResolverRefreshIntervalSeconds) .append(", ").append("applicationsResolverDataStalenessThresholdSeconds=") .append(applicationsResolverDataStalenessThresholdSeconds).append(", ") .append("asyncResolverRefreshIntervalMs=").append(asyncResolverRefreshIntervalMs).append(", ") .append("asyncResolverWarmUpTimeoutMs=").append(asyncResolverWarmUpTimeoutMs).append(", ") .append("asyncExecutorThreadPoolSize=").append(asyncExecutorThreadPoolSize).append(", ") .append("readClusterVip='").append(readClusterVip).append("', ").append("writeClusterVip='") .append(writeClusterVip).append("', ").append("bootstrapResolverForQuery=") .append(bootstrapResolverForQuery).append(", ").append("bootstrapResolverStrategy='") .append(bootstrapResolverStrategy).append("', ").append("applicationsResolverUseIp=") .append(applicationsResolverUseIp).append(", ").append("}").toString(); } }
return Objects.hash(sessionedClientReconnectIntervalSeconds, retryableClientQuarantineRefreshPercentage, bootstrapResolverRefreshIntervalSeconds, applicationsResolverDataStalenessThresholdSeconds, asyncResolverRefreshIntervalMs, asyncResolverWarmUpTimeoutMs, asyncExecutorThreadPoolSize, readClusterVip, writeClusterVip, bootstrapResolverForQuery, bootstrapResolverStrategy, applicationsResolverUseIp);
1,811
112
1,923
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaDiscoveryClient.java
EurekaDiscoveryClient
getServices
class EurekaDiscoveryClient implements DiscoveryClient { /** * Client description {@link String}. */ public static final String DESCRIPTION = "Spring Cloud Eureka Discovery Client"; private final EurekaClient eurekaClient; private final EurekaClientConfig clientConfig; public EurekaDiscoveryClient(EurekaClient eurekaClient, EurekaClientConfig clientConfig) { this.clientConfig = clientConfig; this.eurekaClient = eurekaClient; } @Override public String description() { return DESCRIPTION; } @Override public List<ServiceInstance> getInstances(String serviceId) { List<InstanceInfo> infos = this.eurekaClient.getInstancesByVipAddress(serviceId, false); List<ServiceInstance> instances = new ArrayList<>(); for (InstanceInfo info : infos) { instances.add(new EurekaServiceInstance(info)); } return instances; } @Override public List<String> getServices() {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return clientConfig instanceof Ordered ? ((Ordered) clientConfig).getOrder() : DiscoveryClient.DEFAULT_ORDER; } }
Applications applications = this.eurekaClient.getApplications(); if (applications == null) { return Collections.emptyList(); } List<Application> registered = applications.getRegisteredApplications(); List<String> names = new ArrayList<>(); for (Application app : registered) { if (app.getInstances().isEmpty()) { continue; } names.add(app.getName().toLowerCase()); } return names;
322
127
449
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaDiscoveryClientConfiguration.java
EurekaClientConfigurationRefresher
onApplicationEvent
class EurekaClientConfigurationRefresher implements ApplicationListener<RefreshScopeRefreshedEvent> { @Autowired(required = false) private EurekaClient eurekaClient; @Autowired(required = false) private EurekaAutoServiceRegistration autoRegistration; public void onApplicationEvent(RefreshScopeRefreshedEvent event) {<FILL_FUNCTION_BODY>} }
// This will force the creation of the EurekaClient bean if not already // created // to make sure the client will be re-registered after a refresh event if (eurekaClient != null) { eurekaClient.getApplications(); } if (autoRegistration != null) { // register in case meta data changed this.autoRegistration.stop(); this.autoRegistration.start(); }
111
115
226
<no_super_class>