Skip to content

Commit

Permalink
refactor (jkube-kit/enricher) : Reuse Fabric8 KubernetesResourceUtil …
Browse files Browse the repository at this point in the history
…ConfigMap utils methods (eclipse-jkube#2186)

+ Remove deprecated methods of `org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil`
+ Update ConfigMapEnricher to use `io.fabric8.kubernetes.client.utils.KubernetesResourceUtil`

Signed-off-by: Rohan Kumar <rohaan@redhat.com>
  • Loading branch information
rohanKanojia committed Oct 18, 2023
1 parent 68b5225 commit 5288daf
Show file tree
Hide file tree
Showing 4 changed files with 5 additions and 200 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ Usage:
```
### 1.15-SNAPSHOT
* Fix #2138: Support for Spring Boot Native Image
* Fix #2186: Reuse ` io.fabric8.kubernetes.client.utils.KubernetesResourceUtil` ConfigMap utils methods
* Fix #2200: Support for Helm `values.yaml` fragments
* Fix #2356: Helm values.yaml parameter names preserve case
* Fix #2369: Helm chart apiVersion can be configured
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,29 +13,18 @@
*/
package org.eclipse.jkube.kit.enricher.api.util;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Stream;
import java.util.stream.Collectors;

import io.fabric8.kubernetes.api.model.ContainerBuilder;
Expand Down Expand Up @@ -397,96 +386,6 @@ public static HasMetadata mergeResources(HasMetadata item1, HasMetadata item2, K
return item1;
}

/**
* Create a ConfigMap entry based on file contents
*
* @param key key for entry
* @param file file path whose contents would be used in value of entry
* @return an entry containing key and value
* @deprecated Should be replaced with Fabric8 Kubernetes Client's methods
* @throws IOException in case of error while reading file
*/
@Deprecated
public static Map.Entry<String, String> createConfigMapEntry(final String key, final Path file) throws IOException {
final byte[] bytes = Files.readAllBytes(file);
if (isFileWithBinaryContent(file)) {
final String value = Base64.getEncoder().encodeToString(bytes);
return new AbstractMap.SimpleEntry<>(key, value);
} else {
return new AbstractMap.SimpleEntry<>(key, new String(bytes));
}
}

/**
* Whether a file is binary file or not
*
* @param file file to check
* @return boolean value indicating whether file is binary file or not
* @deprecated Should be replaced with Fabric8 Kubernetes Client's methods
* @throws IOException in case of failure while reading file
*/
@Deprecated
public static boolean isFileWithBinaryContent(final Path file) throws IOException {
final byte[] bytes = Files.readAllBytes(file);
try {
StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(bytes));
return false;
} catch (CharacterCodingException e) {
return true;
}
}

/**
* Add ConfigMap entries from a directory to current ConfigMap
* @param configMapBuilder ConfigMap builder object
* @param path path to directory
* @deprecated Should be replaced with Fabric8 Kubernetes Client's methods
* @throws IOException in case of failure while reading directory
*/
@Deprecated
public static void addNewEntriesFromDirectoryToExistingConfigMap(ConfigMapBuilder configMapBuilder, final Path path)
throws IOException {
try (Stream<Path> files = Files.list(path)) {
files.filter(p -> !Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS)).forEach(file -> {
try {
addNewEntryToExistingConfigMap(configMapBuilder, createConfigMapEntry(file.getFileName().toString(), file), file);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
});
}
}

/**
* Add single entry to ConfigMap
*
* @param configMapBuilder ConfigMap builder object
* @param entry key value pair which will be added to data/binaryData
* @param file file which needs to be processed
* @deprecated Should be replaced with Fabric8 Kubernetes Client's methods
* @throws IOException in case of failure while reading file
*/
@Deprecated
public static void addNewEntryToExistingConfigMap(ConfigMapBuilder configMapBuilder, Map.Entry<String, String> entry, final Path file)
throws IOException {
if (isFileWithBinaryContent(file)) {
configMapBuilder.addToBinaryData(entry.getKey(), entry.getValue());
} else {
configMapBuilder.addToData(entry.getKey(), entry.getValue());
}
}

public static void addNewConfigMapEntriesToExistingConfigMap(ConfigMapBuilder configMapBuilder, String key, Path filePath) throws IOException {
if (Files.isDirectory(filePath, LinkOption.NOFOLLOW_LINKS)) {
addNewEntriesFromDirectoryToExistingConfigMap(configMapBuilder, filePath);
} else {
addNewEntryToExistingConfigMap(configMapBuilder, createConfigMapEntry(key, filePath), filePath);
}
}

public static boolean hasInitContainer(PodTemplateSpecBuilder builder, String name) {
return getInitContainer(builder, name) != null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,22 +46,16 @@
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.tuple;
import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.addNewConfigMapEntriesToExistingConfigMap;
import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.createConfigMapEntry;
import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.createNewInitContainersFromConfig;
import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.handleKubernetesClientException;
import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.isContainerImage;
Expand Down Expand Up @@ -202,92 +196,6 @@ void mergePodSpec_withFragmentWithContainerNameAndSidecarEnabled_shouldGetContai
);
}

@Test
void createConfigMapEntry_whenKeyAndPathProvided_thenShouldCreateEntryWithFileContents() throws IOException {
// Given
URL fileUrl = getClass().getResource("/kubernetes-resource-util/configmap-directory/test.properties");
assertThat(fileUrl).isNotNull();

// When
Map.Entry<String, String> entry = createConfigMapEntry("custom-key", Paths.get(fileUrl.getFile()));

// Then
assertThat(entry)
.satisfies(e -> assertThat(e.getKey()).isEqualTo("custom-key"))
.satisfies(e -> assertThat(e.getValue()).isEqualTo("db.url=jdbc:mysql://localhost:3306/sample_db"));
}

@Test
void createConfigMapEntry_whenBinaryFileProvided_thenShouldCreateEntryWithFileContents() throws IOException {
// Given
URL fileUrl = getClass().getResource("/kubernetes-resource-util/test.bin");
assertThat(fileUrl).isNotNull();

// When
Map.Entry<String, String> entry = createConfigMapEntry("custom-key", Paths.get(fileUrl.getFile()));

// Then
assertThat(entry)
.satisfies(e -> assertThat(e.getKey()).isEqualTo("custom-key"))
.satisfies(e -> assertThat(e.getValue()).isEqualTo("wA=="));
}

@Test
void addNewConfigMapEntriesToExistingConfigMap_whenFileProvided_thenShouldCreateConfigMapWithFile() throws IOException {
// Given
URL fileUrl = getClass().getResource("/kubernetes-resource-util/configmap-directory/test.properties");
assertThat(fileUrl).isNotNull();
ConfigMapBuilder configMapBuilder = new ConfigMapBuilder();

// When
addNewConfigMapEntriesToExistingConfigMap(configMapBuilder, "custom-key", Paths.get(fileUrl.getFile()));

// Then
assertThat(configMapBuilder.build())
.asInstanceOf(InstanceOfAssertFactories.type(ConfigMap.class))
.extracting(ConfigMap::getData)
.asInstanceOf(InstanceOfAssertFactories.MAP)
.containsEntry("custom-key", "db.url=jdbc:mysql://localhost:3306/sample_db");
}

@Test
void addNewConfigMapEntriesToExistingConfigMap_whenBinaryFileProvided_thenShouldCreateConfigMapWithBinaryContent() throws IOException {
// Given
URL fileUrl = getClass().getResource("/kubernetes-resource-util/test.bin");
assertThat(fileUrl).isNotNull();
ConfigMapBuilder configMapBuilder = new ConfigMapBuilder();

// When
addNewConfigMapEntriesToExistingConfigMap(configMapBuilder, "custom-key", Paths.get(fileUrl.getFile()));

// Then
assertThat(configMapBuilder.build())
.asInstanceOf(InstanceOfAssertFactories.type(ConfigMap.class))
.extracting(ConfigMap::getBinaryData)
.asInstanceOf(InstanceOfAssertFactories.MAP)
.containsEntry("custom-key", "wA==");
}

@Test
void addNewConfigMapEntriesToExistingConfigMap_whenDirectoryProvided_thenShouldCreateConfigMapWithFilesInDir() throws IOException {
// Given
URL fileUrl = getClass().getResource("/kubernetes-resource-util/configmap-directory");
assertThat(fileUrl).isNotNull();
ConfigMapBuilder configMapBuilder = new ConfigMapBuilder();

// When
addNewConfigMapEntriesToExistingConfigMap(configMapBuilder, "custom-key", Paths.get(fileUrl.getFile()));

// Then
assertThat(configMapBuilder.build())
.asInstanceOf(InstanceOfAssertFactories.type(ConfigMap.class))
.extracting(ConfigMap::getData)
.asInstanceOf(InstanceOfAssertFactories.MAP)
.containsEntry("test.properties", "db.url=jdbc:mysql://localhost:3306/sample_db")
.containsEntry("prod.properties", "db.url=jdbc:mysql://prod.example.com:3306/sample_db");
}


@Test
void removeItemFromKubernetesBuilder_whenInvoked_shouldRemoveItem() {
// Given
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@
*/
package org.eclipse.jkube.enricher.generic;

import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.addNewConfigMapEntriesToExistingConfigMap;
import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.addNewEntryToExistingConfigMap;
import static org.eclipse.jkube.kit.enricher.api.util.KubernetesResourceUtil.createConfigMapEntry;

import java.io.IOException;
import java.nio.file.Paths;
import java.nio.file.Path;
Expand All @@ -34,6 +30,8 @@
import io.fabric8.kubernetes.api.model.ConfigMapBuilder;
import io.fabric8.kubernetes.api.model.KubernetesListBuilder;

import static io.fabric8.kubernetes.client.utils.KubernetesResourceUtil.addEntriesFromDirOrFileToConfigMap;

public class ConfigMapEnricher extends BaseEnricher {

/**
Expand Down Expand Up @@ -80,7 +78,7 @@ private void addConfigMapFromAnnotations(final Map<String, String> annotations,

if (key.startsWith(PREFIX_ANNOTATION) || key.startsWith(CONFIGMAP_PREFIX_ANNOTATION)) {
Path filePath = Paths.get(entry.getValue());
addNewConfigMapEntriesToExistingConfigMap(configMapBuilder, getOutput(key), filePath);
addEntriesFromDirOrFileToConfigMap(configMapBuilder, getOutput(key), filePath);
it.remove();
}
}
Expand Down Expand Up @@ -134,8 +132,7 @@ private io.fabric8.kubernetes.api.model.ConfigMap createConfigMapFromConfigurati
if (name == null) {
name = filePath.getFileName().toString();
}
Map.Entry<String, String> fileEntry = createConfigMapEntry(name, filePath);
addNewEntryToExistingConfigMap(configMapBuilder, fileEntry, filePath);
addEntriesFromDirOrFileToConfigMap(configMapBuilder, name, filePath);
}
}
}
Expand Down

0 comments on commit 5288daf

Please sign in to comment.