Skip to content
This repository has been archived by the owner on Jun 19, 2024. It is now read-only.

Commit

Permalink
Refactor: Move XML configuration code from Mojo to enrichers
Browse files Browse the repository at this point in the history
Right now there is lot of code in ResourceMojo which should ideally be in
enrichers, Mojo should stay as slim as possible.
  • Loading branch information
rohanKanojia committed Feb 15, 2019
1 parent 66cb664 commit cfb79a1
Show file tree
Hide file tree
Showing 8 changed files with 251 additions and 317 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ After this we will switch probably to real [Semantic Versioning 2.0.0](http://se
* Fix 690: Removes deprecated _legacyPortMapping_ property.
* Fix 1458: Support for from Image configuration in openshift docker build strategy
* Fix 732: Added 'skip' options to goals.
* Refactor 1520: Move XML configuration code from Mojo to enrichers
* Fix 1486: Remove Kompose Support
* Fix 1467: Wait timeout for build pod is too small
* Fix 1466: Allow to configure noCache option for openshift docker build strategy
Expand Down
44 changes: 44 additions & 0 deletions core/src/main/java/io/fabric8/maven/core/util/FileUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,18 @@
*/
package io.fabric8.maven.core.util;

import org.apache.maven.plugin.MojoExecutionException;
import io.fabric8.maven.docker.util.Logger;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
* File related methods which cannot be found elsewhere
Expand Down Expand Up @@ -80,4 +85,43 @@ public static String getAbsolutePath(URL url) {
throw new RuntimeException(e);
}
}

public static void downloadRemotes(final File outputDirectory, List<String> remotes, Logger log) {

if (!outputDirectory.exists()) {
try {
Files.createDirectories(outputDirectory.toPath());
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}

remotes.stream()
.map(remote -> {
try {
return new URL(remote);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
})
.forEach(url -> {
try {
IoUtil.download(log, url, new File(outputDirectory, getOutputName(url)));
} catch (MojoExecutionException e) {
throw new IllegalArgumentException(e);
}
});
}

private static String getOutputName(URL url) {
final String path = url.getPath();

final int slashIndex = path.lastIndexOf('/');
if (slashIndex >= 0) {
return path.substring(slashIndex + 1);
} else {
throw new IllegalArgumentException(String.format("URL %s should contain a name file to be downloaded.", url.toString()));
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
import java.util.Optional;
import java.util.Set;

import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import io.fabric8.maven.core.config.ProcessorConfig;
import io.fabric8.maven.core.config.ResourceConfig;
import io.fabric8.maven.core.model.Configuration;
Expand Down Expand Up @@ -53,6 +55,8 @@ public class MavenEnricherContext implements EnricherContext {
// overall configuration for the build
private Configuration configuration;

private Settings settings;

private MavenProject project;
private Logger log;

Expand All @@ -66,6 +70,10 @@ public Configuration getConfiguration() {
return configuration;
}

public Settings getSettings() {
return settings;
}

@Override
public Logger getLog() {
return log;
Expand Down Expand Up @@ -133,6 +141,48 @@ public MavenProject getProject() {
return project;
}

//Method used in MOJO
public String getDockerJsonConfigString(final Settings settings, final String serverId) {
Server server = getServer(settings, serverId);
if (server == null) {
return "";
}

JsonObject auth = new JsonObject();
auth.add("username", new JsonPrimitive(server.getUsername()));
auth.add("password", new JsonPrimitive(server.getPassword()));

String mail = getConfigurationValue(server, "email");
if (!StringUtils.isBlank(mail)) {
auth.add("email", new JsonPrimitive(mail));
}

JsonObject json = new JsonObject();
json.add(serverId, auth);
return json.toString();
}

public Server getServer(final Settings settings, final String serverId) {
if (settings == null || StringUtils.isBlank(serverId)) {
return null;
}
return settings.getServer(serverId);
}

private String getConfigurationValue(final Server server, final String key) {

final Xpp3Dom configuration = (Xpp3Dom) server.getConfiguration();
if (configuration == null) {
return null;
}

final Xpp3Dom node = configuration.getChild(key);
if (node == null) {
return null;
}

return node.getValue();
}
// =======================================================================================================
public static class Builder {

Expand Down Expand Up @@ -177,6 +227,11 @@ public Builder openshiftDependencyResources(OpenShiftDependencyResources openShi
return this;
}

public Builder settings(Settings settings) {
ctx.settings = settings;
return this;
}

public MavenEnricherContext build() {
ctx.configuration =
new Configuration.Builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
import io.fabric8.kubernetes.api.builder.TypedVisitor;
import io.fabric8.kubernetes.api.model.ConfigMapBuilder;
import io.fabric8.kubernetes.api.model.KubernetesListBuilder;
import io.fabric8.maven.core.config.ConfigMapEntry;
import io.fabric8.maven.core.config.ResourceConfig;
import io.fabric8.maven.enricher.api.BaseEnricher;
import io.fabric8.maven.enricher.api.MavenEnricherContext;
import java.io.IOException;
Expand All @@ -39,6 +41,7 @@ public ConfigMapEnricher(MavenEnricherContext enricherContext) {
@Override
public void addMissingResources(KubernetesListBuilder builder) {
addAnnotations(builder);
addConfigMapFromXmlConfigurations(builder);
}

private void addAnnotations(KubernetesListBuilder builder) {
Expand Down Expand Up @@ -82,4 +85,52 @@ private String getOutput(String key) {
return key.substring(PREFIX_ANNOTATION.length());
}

private void addConfigMapFromXmlConfigurations(KubernetesListBuilder builder) {
io.fabric8.maven.core.config.ConfigMap configMap = getConfigMapFromXmlConfiguration();
final Map<String, String> configMapFromConfiguration;
try {
configMapFromConfiguration = createConfigMapFromConfiguration(configMap);
if(!configMapFromConfiguration.isEmpty()) {
ConfigMapBuilder element = new ConfigMapBuilder();
element.withNewMetadata().withName("xmlconfig").endMetadata();
element.addToData(configMapFromConfiguration);

builder.addToConfigMapItems(element.build());
}
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}

private io.fabric8.maven.core.config.ConfigMap getConfigMapFromXmlConfiguration() {
ResourceConfig resourceConfig = getConfiguration().getResource().orElse(null);
if(resourceConfig != null && resourceConfig.getConfigMap() != null) {
return resourceConfig.getConfigMap();
}
return null;
}

private Map<String, String> createConfigMapFromConfiguration(io.fabric8.maven.core.config.ConfigMap configMap) throws IOException {
final Map<String, String> configMapData = new HashMap<>();

if (configMap != null) {
for (ConfigMapEntry configMapEntry : configMap.getEntries()) {
String name = configMapEntry.getName();
final String value = configMapEntry.getValue();
if (name != null && value != null) {
configMapData.put(name, value);
} else {
final String file = configMapEntry.getFile();
if (file != null) {
if (name == null) {
name = Paths.get(file).getFileName().toString();
}
configMapData.put(name, readContent(file));
}
}
}
}
return configMapData;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
import io.fabric8.kubernetes.api.model.ServicePort;
import io.fabric8.kubernetes.api.model.ServicePortBuilder;
import io.fabric8.kubernetes.api.model.ServiceSpec;
import io.fabric8.maven.core.config.ResourceConfig;
import io.fabric8.maven.core.config.ServiceConfig;
import io.fabric8.maven.core.handler.ServiceHandler;
import io.fabric8.maven.core.util.Configs;
import io.fabric8.maven.core.util.MavenUtil;
import io.fabric8.maven.core.util.kubernetes.KubernetesHelper;
Expand Down Expand Up @@ -104,10 +107,39 @@ public void addMissingResources(KubernetesListBuilder builder) {
} else {
addDefaultService(builder, defaultService);
}

// Add Services configured via XML
addServices(builder);
}

// =======================================================================================================

private void addServices(KubernetesListBuilder builder) {
ResourceConfig resources = new ResourceConfig();

if (resources != null && resources.getServices() != null) {
List<ServiceConfig> serviceConfig = resources.getServices();
ServiceHandler serviceHandler = new ServiceHandler();
builder.addToServiceItems(toArray(serviceHandler.getServices(serviceConfig)));
}
}

// convert list to array, never returns null.
private Service[] toArray(List<Service> services) {
if (services == null) {
return new Service[0];
}
if (services instanceof ArrayList) {
return ((ArrayList<Service>) services).toArray(new Service[services.size()]);
} else {
Service[] ret = new Service[services.size()];
for (int i = 0; i < services.size(); i++) {
ret[i] = services.get(i);
}
return ret;
}
}

private Service getDefaultService() {

// No image config, no service
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,23 @@
*/
package io.fabric8.maven.enricher.standard;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.fabric8.kubernetes.api.builder.TypedVisitor;
import io.fabric8.kubernetes.api.model.KubernetesListBuilder;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.ObjectMetaBuilder;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.SecretBuilder;
import io.fabric8.maven.core.config.ResourceConfig;
import io.fabric8.maven.core.config.SecretConfig;
import io.fabric8.maven.core.util.Base64Util;
import io.fabric8.maven.core.util.SecretConstants;
import io.fabric8.maven.enricher.api.BaseEnricher;
import io.fabric8.maven.enricher.api.MavenEnricherContext;
import org.apache.commons.lang3.StringUtils;

public abstract class SecretEnricher extends BaseEnricher {

Expand Down Expand Up @@ -58,6 +67,61 @@ public void visit(SecretBuilder secretBuilder) {
secretBuilder.addToData(data);
}
});

addSecretsFromXmlConfiguration(builder);
}

private void addSecretsFromXmlConfiguration(KubernetesListBuilder builder) {
log.verbose("Adding secrets resources from plugin configuration");
List<SecretConfig> secrets = getSecretsFromXmlConfig();
if (secrets == null || secrets.isEmpty()) {
return;
}
for (int i = 0; i < secrets.size(); i++) {
SecretConfig secretConfig = secrets.get(i);
if (StringUtils.isBlank(secretConfig.getName())) {
log.warn("Secret name is empty. You should provide a proper name for the secret");
continue;
}

Map<String, String> data = new HashMap<>();
String type = "";
ObjectMeta metadata = new ObjectMetaBuilder()
.withNamespace(secretConfig.getNamespace())
.withName(secretConfig.getName())
.build();

// docker-registry
if (secretConfig.getDockerServerId() != null) {
MavenEnricherContext mavenContext = ((MavenEnricherContext)getContext());
String dockerSecret = (mavenContext).getDockerJsonConfigString(mavenContext.getSettings(), secretConfig.getDockerServerId());
if (StringUtils.isBlank(dockerSecret)) {
log.warn("Docker secret with id "
+ secretConfig.getDockerServerId()
+ " cannot be found in maven settings");
continue;
}
data.put(SecretConstants.DOCKER_DATA_KEY, Base64Util.encodeToString(dockerSecret));
type = SecretConstants.DOCKER_CONFIG_TYPE;
}
// TODO: generic secret (not supported for now)

if (StringUtils.isBlank(type) || data.isEmpty()) {
log.warn("No data can be found for docker secret with id " + secretConfig.getDockerServerId());
continue;
}

Secret secret = new SecretBuilder().withData(data).withMetadata(metadata).withType(type).build();
builder.addToSecretItems(i, secret);
}
}

private List<SecretConfig> getSecretsFromXmlConfig() {
ResourceConfig resourceConfig = getConfiguration().getResource().orElse(null);
if(resourceConfig != null && resourceConfig.getSecrets() != null) {
return resourceConfig.getSecrets();
}
return null;
}

protected abstract String getAnnotationKey();
Expand Down
Loading

0 comments on commit cfb79a1

Please sign in to comment.