org.zodic.kubernetes.base.env.KubernetesProfileEnvironmentPostProcessor Maven / Gradle / Ivy
package org.zodic.kubernetes.base.env;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.config.ConfigFileApplicationListener;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.zodic.kubernetes.base.support.StandardPodOperations;
public class KubernetesProfileEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
private static final Logger LOG = LoggerFactory.getLogger(KubernetesProfileEnvironmentPostProcessor.class);
// Before ConfigFileApplicationListener so values there can use these ones
private static final int ORDER = ConfigFileApplicationListener.DEFAULT_ORDER - 1;
private static final String KUBERNETES_PROFILE = "kubernetes";
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
final StandardPodOperations podUtils = new StandardPodOperations(new DefaultKubernetesClient());
if (podUtils.isInsideKubernetes()) {
if (hasKubernetesProfile(environment)) {
if (LOG.isDebugEnabled()) {
LOG.debug("'kubernetes' already in list of active profiles");
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Adding 'kubernetes' to list of active profiles");
}
environment.addActiveProfile(KUBERNETES_PROFILE);
}
} else {
if (LOG.isDebugEnabled()) {
LOG.warn("Not running inside kubernetes. Skipping 'kubernetes' profile activation.");
}
}
}
private boolean hasKubernetesProfile(Environment environment) {
for (String activeProfile : environment.getActiveProfiles()) {
if (KUBERNETES_PROFILE.equalsIgnoreCase(activeProfile)) {
return true;
}
}
return false;
}
@Override
public int getOrder() {
return ORDER;
}
}