Skip to content

Commit

Permalink
using Utils to check parameters
Browse files Browse the repository at this point in the history
Signed-off-by: Andre Dietisheim <[email protected]>
  • Loading branch information
adietish committed Aug 29, 2024
1 parent dcff6bd commit 7d4eddc
Show file tree
Hide file tree
Showing 14 changed files with 267 additions and 132 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
Expand Down Expand Up @@ -236,7 +237,6 @@ public class Config {

private Boolean autoConfigure;

@Deprecated
private List<File> files = new ArrayList<>();

@JsonIgnore
Expand Down Expand Up @@ -268,7 +268,7 @@ private Config(boolean autoConfigure) {
null, null, null,
null, null, null,
null, null, null, null,
null, autoConfigure, true);
null, autoConfigure, true, null);
}

/**
Expand Down Expand Up @@ -376,7 +376,7 @@ public Config(String masterUrl, String apiVersion, String namespace, Boolean tru
httpProxy, httpsProxy, noProxy, userAgent, tlsVersions, websocketPingInterval, proxyUsername, proxyPassword,
trustStoreFile, trustStorePassphrase, keyStoreFile, keyStorePassphrase, impersonateUsername, impersonateGroups,
impersonateExtras, oauthTokenProvider, customHeaders, requestRetryBackoffLimit, requestRetryBackoffInterval,
uploadRequestTimeout, onlyHttpWatches, currentContext, contexts, false, true);
uploadRequestTimeout, onlyHttpWatches, currentContext, contexts, false, true, null);
}

public Config(String masterUrl, String apiVersion, String namespace, Boolean trustCerts, Boolean disableHostnameVerification,
Expand All @@ -400,7 +400,7 @@ public Config(String masterUrl, String apiVersion, String namespace, Boolean tru
httpProxy, httpsProxy, noProxy, userAgent, tlsVersions, websocketPingInterval, proxyUsername, proxyPassword,
trustStoreFile, trustStorePassphrase, keyStoreFile, keyStorePassphrase, impersonateUsername, impersonateGroups,
impersonateExtras, oauthTokenProvider, customHeaders, requestRetryBackoffLimit, requestRetryBackoffInterval,
uploadRequestTimeout, onlyHttpWatches, currentContext, contexts, autoConfigure, true);
uploadRequestTimeout, onlyHttpWatches, currentContext, contexts, autoConfigure, true, null);
}

/*
Expand All @@ -419,7 +419,7 @@ public Config(String masterUrl, String apiVersion, String namespace, Boolean tru
String impersonateUsername, String[] impersonateGroups, Map<String, List<String>> impersonateExtras,
OAuthTokenProvider oauthTokenProvider, Map<String, String> customHeaders, Integer requestRetryBackoffLimit,
Integer requestRetryBackoffInterval, Integer uploadRequestTimeout, Boolean onlyHttpWatches, NamedContext currentContext,
List<NamedContext> contexts, Boolean autoConfigure, Boolean shouldSetDefaultValues) {
List<NamedContext> contexts, Boolean autoConfigure, Boolean shouldSetDefaultValues, List<File> files) {
if (Boolean.TRUE.equals(shouldSetDefaultValues)) {
this.masterUrl = DEFAULT_MASTER_URL;
this.apiVersion = "v1";
Expand Down Expand Up @@ -587,7 +587,7 @@ public Config(String masterUrl, String apiVersion, String namespace, Boolean tru
if (Utils.isNotNullOrEmpty(autoOAuthToken)) {
this.autoOAuthToken = autoOAuthToken;
}
if (contexts != null && !contexts.isEmpty()) {
if (Utils.isNotNullOrEmpty(contexts)) {
this.contexts = contexts;
}
if (Utils.isNotNull(currentContext)) {
Expand All @@ -601,6 +601,10 @@ public Config(String masterUrl, String apiVersion, String namespace, Boolean tru
this.oauthTokenProvider = oauthTokenProvider;
this.customHeaders = customHeaders;
this.onlyHttpWatches = onlyHttpWatches;
if (!Utils.isNullOrEmpty(files)) {
this.files = files;
}

}

public static void configFromSysPropsOrEnvVars(Config config) {
Expand Down Expand Up @@ -723,7 +727,7 @@ public static void configFromSysPropsOrEnvVars(Config config) {
}

String tlsVersionsVar = Utils.getSystemPropertyOrEnvVar(KUBERNETES_TLS_VERSIONS);
if (tlsVersionsVar != null && !tlsVersionsVar.isEmpty()) {
if (Utils.isNotNullOrEmpty(tlsVersionsVar)) {
String[] tlsVersionsSplit = tlsVersionsVar.split(",");
TlsVersion[] tlsVersions = new TlsVersion[tlsVersionsSplit.length];
for (int i = 0; i < tlsVersionsSplit.length; i++) {
Expand Down Expand Up @@ -839,7 +843,7 @@ public static Config fromKubeconfig(String context, String kubeconfigContents, S
*/
public Config refresh() {
final String currentContextName = this.getCurrentContext() != null ? this.getCurrentContext().getName() : null;
if (this.oauthToken != null && !this.oauthToken.isEmpty()) {
if (Utils.isNotNullOrEmpty(this.oauthToken)) {
return this;
}
if (this.autoConfigure) {
Expand All @@ -863,8 +867,7 @@ private static boolean tryKubeConfig(Config config, String context) {
return false;
}
String[] kubeConfigFilenames = getKubeconfigFilenames();
if (kubeConfigFilenames == null
|| kubeConfigFilenames.length == 0) {
if (Utils.isNullOrEmpty(kubeConfigFilenames)) {
return false;
}
List<File> allFiles = Arrays.stream(kubeConfigFilenames)
Expand All @@ -876,28 +879,26 @@ private static boolean tryKubeConfig(Config config, String context) {
}

private static io.fabric8.kubernetes.api.model.Config mergeKubeConfigs(List<File> files) {
if (files == null
|| files.isEmpty()) {
if (Utils.isNullOrEmpty(files)) {
return null;
}
return files.stream()
.map(Config::createKubeconfig)
.reduce(null, (merged, additionalConfig) -> {
if (additionalConfig != null) {
return KubeConfigUtils.merge(additionalConfig, merged);
} else {
return merged;
}
});
.map(Config::createKubeconfig)
.reduce(null, (merged, additionalConfig) -> {
if (additionalConfig != null) {
return KubeConfigUtils.merge(additionalConfig, merged);
} else {
return merged;
}
});
}

private static io.fabric8.kubernetes.api.model.Config createKubeconfig(File file) {
io.fabric8.kubernetes.api.model.Config kubeConfig = null;
LOGGER.debug("Found for Kubernetes config at: [{}].", file.getPath());
try {
String content = getKubeconfigContents(file);
if (content != null
&& !content.isEmpty()) {
if (Utils.isNotNullOrEmpty(content)) {
kubeConfig = KubeConfigUtils.parseConfigFromString(content);
}
} catch (KubernetesClientException e) {
Expand All @@ -915,7 +916,6 @@ public static String getKubeconfigFilename() {
String fileName = null;
String[] fileNames = getKubeconfigFilenames();
// if system property/env var contains multiple files take the first one based on the environment
// we are running in (eg. : for Linux, ; for Windows)
if (fileNames.length >= 1) {
fileName = fileNames[0];
if (fileNames.length > 1) {
Expand All @@ -929,17 +929,13 @@ public static String getKubeconfigFilename() {
public static String[] getKubeconfigFilenames() {
String[] fileNames = null;
String fileName = Utils.getSystemPropertyOrEnvVar(KUBERNETES_KUBECONFIG_FILES);
if (fileName != null
&& !fileName.isEmpty()) {
if (Utils.isNotNullOrEmpty(fileName)) {
fileNames = fileName.split(File.pathSeparator);
}
if (fileNames == null
|| fileNames.length == 0) {
if (Utils.isNullOrEmpty(fileNames)) {
fileNames = new String[] { DEFAULT_KUBECONFIG_FILE.toString() };
}
return Arrays.stream(fileNames)
.filter(filename -> isReadableKubeconfFile(new File(filename)))
.toArray(String[]::new);
return fileNames;
}

private static boolean isReadableKubeconfFile(File file) {
Expand Down Expand Up @@ -971,7 +967,7 @@ private static String getKubeconfigContents(File kubeConfigFile) {
// It is only used to rewrite relative tls asset paths inside kubeconfig when a file is passed, and in the case that
// the kubeconfig references some assets via relative paths.
private static boolean loadFromKubeconfig(Config config, String context, String kubeconfigContents) {
if (kubeconfigContents != null && !kubeconfigContents.isEmpty()) {
if (Utils.isNotNullOrEmpty(kubeconfigContents)) {
return loadFromKubeconfig(config, context, KubeConfigUtils.parseConfigFromString(kubeconfigContents));
} else {
return false;
Expand Down Expand Up @@ -1135,7 +1131,7 @@ protected static List<String> getAuthenticatorCommandFromExecConfig(ExecConfig e
command = shellQuote(command);

List<String> args = exec.getArgs();
if (args != null && !args.isEmpty()) {
if (Utils.isNotNullOrEmpty(args)) {
command += " " + args
.stream()
.map(Config::shellQuote)
Expand Down Expand Up @@ -1236,7 +1232,7 @@ private static String getSystemEnvVariable(String envVariableName) {

protected static String getHomeDir(Predicate<String> directoryExists, UnaryOperator<String> getEnvVar) {
String home = getEnvVar.apply("HOME");
if (home != null && !home.isEmpty() && directoryExists.test(home)) {
if (Utils.isNotNullOrEmpty(home) && directoryExists.test(home)) {
return home;
}
String osName = System.getProperty("os.name").toLowerCase(Locale.ROOT);
Expand All @@ -1250,7 +1246,7 @@ protected static String getHomeDir(Predicate<String> directoryExists, UnaryOpera
}
}
String userProfile = getEnvVar.apply("USERPROFILE");
if (userProfile != null && !userProfile.isEmpty() && directoryExists.test(userProfile)) {
if (Utils.isNotNullOrEmpty(userProfile) && directoryExists.test(userProfile)) {
return userProfile;
}
}
Expand Down Expand Up @@ -1770,8 +1766,7 @@ public void setCurrentContext(NamedContext context) {
*/
@Deprecated
public File getFile() {
if (files != null
&& !files.isEmpty()) {
if (Utils.isNotNullOrEmpty(files)) {
return files.get(0);
} else {
return null;
Expand All @@ -1789,30 +1784,34 @@ public List<File> getFiles() {
return files;
}

public KubeConfigFile getFile(String username) {
if (username == null
|| username.isEmpty()) {
public KubeConfigFile getFileWithAuthInfo(String name) {
if (Utils.isNullOrEmpty(name)
|| Utils.isNullOrEmpty(getFiles())) {
return null;
}
return Arrays.stream(getKubeconfigFilenames())
.map(File::new)
.map(file -> {
try {
return new KubeConfigFile(file, KubeConfigUtils.parseConfig(file));
} catch (IOException e) {
return null;
}
})
.filter(entry -> entry != null
&& entry.getConfig() != null
&& hasAuthInfo(username, entry.getConfig()))
.findFirst()
.orElse(null);
return getFiles().stream()
.filter(Config::isReadableKubeconfFile)
.map(file -> {
try {
return new KubeConfigFile(file, KubeConfigUtils.parseConfig(file));
} catch (IOException e) {
return null;
}
})
.filter(Objects::nonNull)
.filter(entry -> hasAuthInfoNamed(name, entry.getConfig()))
.findFirst()
.orElse(null);
}

private boolean hasAuthInfo(String username, io.fabric8.kubernetes.api.model.Config kubeConfig) {
private boolean hasAuthInfoNamed(String username, io.fabric8.kubernetes.api.model.Config kubeConfig) {
if (Utils.isNullOrEmpty(username)
|| kubeConfig == null
|| kubeConfig.getUsers() == null) {
return false;
}
return kubeConfig.getUsers().stream()
.anyMatch(namedAuthInfo -> username.equals(namedAuthInfo.getUser().getUsername()));
.anyMatch(namedAuthInfo -> username.equals(namedAuthInfo.getName()));
}

public static class KubeConfigFile {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package io.fabric8.kubernetes.client;

import io.fabric8.kubernetes.api.builder.VisitableBuilder;
import io.fabric8.kubernetes.client.utils.Utils;

import java.util.Optional;

Expand Down Expand Up @@ -57,9 +58,8 @@ public Config build() {
fluent.getOauthTokenProvider(), fluent.getCustomHeaders(), fluent.getRequestRetryBackoffLimit(),
fluent.getRequestRetryBackoffInterval(), fluent.getUploadRequestTimeout(), fluent.getOnlyHttpWatches(),
fluent.getCurrentContext(), fluent.getContexts(),
Optional.ofNullable(fluent.getAutoConfigure()).orElse(!disableAutoConfig()), true);
Optional.ofNullable(fluent.getAutoConfigure()).orElse(!disableAutoConfig()), true, fluent.getFiles());
buildable.setAuthProvider(fluent.getAuthProvider());
buildable.setFile(fluent.getFile());
return buildable;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public void copyInstance(Config instance) {
this.withContexts(instance.getContexts());
this.withAutoConfigure(instance.getAutoConfigure());
this.withAuthProvider(instance.getAuthProvider());
this.withFile(instance.getFile());
this.withFiles(instance.getFiles());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import io.fabric8.kubernetes.client.http.TlsVersion;
import io.sundr.builder.annotations.Buildable;

import java.io.File;
import java.util.List;
import java.util.Map;

Expand Down Expand Up @@ -50,14 +51,14 @@ public SundrioConfig(String masterUrl, String apiVersion, String namespace, Bool
String impersonateUsername, String[] impersonateGroups, Map<String, List<String>> impersonateExtras,
OAuthTokenProvider oauthTokenProvider, Map<String, String> customHeaders, Integer requestRetryBackoffLimit,
Integer requestRetryBackoffInterval, Integer uploadRequestTimeout, Boolean onlyHttpWatches, NamedContext currentContext,
List<NamedContext> contexts, Boolean autoConfigure) {
List<NamedContext> contexts, Boolean autoConfigure, List<File> files) {
super(masterUrl, apiVersion, namespace, trustCerts, disableHostnameVerification, caCertFile, caCertData,
clientCertFile, clientCertData, clientKeyFile, clientKeyData, clientKeyAlgo, clientKeyPassphrase, username,
password, oauthToken, autoOAuthToken, watchReconnectInterval, watchReconnectLimit, connectionTimeout, requestTimeout,
scaleTimeout, loggingInterval, maxConcurrentRequests, maxConcurrentRequestsPerHost, http2Disable,
httpProxy, httpsProxy, noProxy, userAgent, tlsVersions, websocketPingInterval, proxyUsername, proxyPassword,
trustStoreFile, trustStorePassphrase, keyStoreFile, keyStorePassphrase, impersonateUsername, impersonateGroups,
impersonateExtras, oauthTokenProvider, customHeaders, requestRetryBackoffLimit, requestRetryBackoffInterval,
uploadRequestTimeout, onlyHttpWatches, currentContext, contexts, autoConfigure, true);
uploadRequestTimeout, onlyHttpWatches, currentContext, contexts, autoConfigure, true, files);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import io.fabric8.kubernetes.api.model.NamedExtension;
import io.fabric8.kubernetes.api.model.PreferencesBuilder;
import io.fabric8.kubernetes.client.utils.Serialization;
import io.fabric8.kubernetes.client.utils.Utils;

import java.io.File;
import java.io.FileInputStream;
Expand Down Expand Up @@ -183,17 +184,16 @@ public static Config merge(Config thisConfig, Config thatConfig) {
builder.addAllToExtensions(thisConfig.getExtensions());
}
if (!builder.hasCurrentContext()
&& thisConfig.getCurrentContext() != null
&& !thisConfig.getCurrentContext().isEmpty()) {
&& Utils.isNotNullOrEmpty(thisConfig.getCurrentContext())) {
builder.withCurrentContext(thisConfig.getCurrentContext());
}
Config merged = builder.build();
mergePreferences(thisConfig, merged);
return merged;

}

public static void mergePreferences(io.fabric8.kubernetes.api.model.Config source, io.fabric8.kubernetes.api.model.Config destination) {
public static void mergePreferences(io.fabric8.kubernetes.api.model.Config source,
io.fabric8.kubernetes.api.model.Config destination) {
if (source.getPreferences() != null) {
PreferencesBuilder builder = new PreferencesBuilder(destination.getPreferences());
if (source.getPreferences() != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,10 +198,11 @@ public static OAuthToken persistOAuthToken(Config currentConfig, OAuthToken oAut
}

private static void persistOAuthTokenToFile(Config currentConfig, String token, Map<String, String> authProviderConfig) {
if (currentConfig.getFile() != null && currentConfig.getCurrentContext() != null) {
if (currentConfig.getCurrentContext() != null
&& currentConfig.getCurrentContext().getContext() != null) {
try {
final String userName = currentConfig.getCurrentContext().getContext().getUser();
Config.KubeConfigFile kubeConfigFile = currentConfig.getFile(userName);
Config.KubeConfigFile kubeConfigFile = currentConfig.getFileWithAuthInfo(userName);
if (kubeConfigFile == null) {
LOGGER.warn("oidc: failure while persisting new tokens into KUBECONFIG: file for user {} not found", userName);
return;
Expand Down Expand Up @@ -242,6 +243,9 @@ private static NamedAuthInfo getOrCreateNamedAuthInfo(String userName, io.fabric
}

private static void persistOAuthTokenToFile(AuthProviderConfig config, Map<String, String> authProviderConfig) {
if (config == null) {
return;
}
Optional.of(config)
.map(AuthProviderConfig::getConfig)
.ifPresent(c -> c.putAll(authProviderConfig));
Expand Down
Loading

0 comments on commit 7d4eddc

Please sign in to comment.