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 dd8bd36
Show file tree
Hide file tree
Showing 12 changed files with 261 additions and 107 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 @@ -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 Down Expand Up @@ -723,7 +723,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 +839,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 +863,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 +875,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 +912,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 +925,15 @@ 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);
.filter(filename -> isReadableKubeconfFile(new File(filename)))
.toArray(String[]::new);
}

private static boolean isReadableKubeconfFile(File file) {
Expand Down Expand Up @@ -971,7 +965,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 +1129,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 +1230,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 +1244,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 +1764,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 +1782,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 @@ -59,7 +60,9 @@ public Config build() {
fluent.getCurrentContext(), fluent.getContexts(),
Optional.ofNullable(fluent.getAutoConfigure()).orElse(!disableAutoConfig()), true);
buildable.setAuthProvider(fluent.getAuthProvider());
buildable.setFile(fluent.getFile());
if (Utils.isNotNullOrEmpty(fluent.getFiles())) {
buildable.setFiles(fluent.getFiles());
}
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 @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
Expand Down Expand Up @@ -291,16 +292,32 @@ public static boolean isNullOrEmpty(String str) {
return str == null || str.isEmpty();
}

public static boolean isNotNullOrEmpty(Map map) {
return !(map == null || map.isEmpty());
public static boolean isNotNullOrEmpty(Map<?, ?> map) {
return !isNullOrEmpty(map);
}

public static boolean isNullOrEmpty(Map<?, ?> map) {
return map == null || map.isEmpty();
}

public static boolean isNotNullOrEmpty(Collection<?> collection) {
return !isNullOrEmpty(collection);
}

public static boolean isNullOrEmpty(Collection<?> collection) {
return collection == null || collection.isEmpty();
}

public static boolean isNotNullOrEmpty(String str) {
return !isNullOrEmpty(str);
}

public static boolean isNotNullOrEmpty(String[] array) {
return !(array == null || array.length == 0);
return !isNullOrEmpty(array);
}

public static boolean isNullOrEmpty(String[] array) {
return array == null || array.length == 0;
}

public static <T> boolean isNotNull(T... refList) {
Expand Down
Loading

0 comments on commit dd8bd36

Please sign in to comment.