Skip to content

Commit

Permalink
[JENKINS-42262] Add public utility that can be used as API by extension
Browse files Browse the repository at this point in the history
point to manage provisioning of configuration files that delegate to the
config provider the business logic of the content.
  • Loading branch information
nfalco79 committed Mar 20, 2017
1 parent 9e8f0a4 commit 04fc069
Show file tree
Hide file tree
Showing 11 changed files with 277 additions and 157 deletions.
37 changes: 30 additions & 7 deletions src/main/java/org/jenkinsci/lib/configprovider/ConfigProvider.java
Expand Up @@ -23,21 +23,27 @@ of this software and associated documentation files (the "Software"), to deal
*/
package org.jenkinsci.lib.configprovider;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;

import org.jenkinsci.lib.configprovider.model.Config;
import org.jenkinsci.lib.configprovider.model.ContentType;
import org.jenkinsci.plugins.configfiles.GlobalConfigFiles;

import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.FilePath;
import hudson.model.Descriptor;
import hudson.model.ItemGroup;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.util.ReflectionUtils;
import jenkins.model.Jenkins;
import org.jenkinsci.lib.configprovider.model.Config;
import org.jenkinsci.lib.configprovider.model.ContentType;
import org.jenkinsci.plugins.configfiles.GlobalConfigFiles;

import java.lang.reflect.Field;
import java.util.Collection;

/**
* A ConfigProvider represents a configuration file (such as Maven's settings.xml) where the user can choose its actual content among several {@linkplain Config concrete contents} that are
Expand Down Expand Up @@ -190,4 +196,21 @@ public void save(Config config) {
GlobalConfigFiles.get().save(config);
this.save();
}
}

/**
* Provide the given content file.
*
* @param configFile the file content to be provided
* @param workDir target workspace directory
* @param listener the listener
* @param tempFiles temp files created by this method, these files will
* be deleted by the caller
* @return file content
* @throws IOException in case an exception occurs when providing the content or other needed files
* @since 2.16
*/
public String supplyContent(@NonNull Config configFile, Run<?, ?> build, FilePath workDir, TaskListener listener, @NonNull List<String> tempFiles) throws IOException {
return configFile.content;
}

}
@@ -0,0 +1,55 @@
/*
The MIT License
Copyright (c) 2011, Dominik Bartholdi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package org.jenkinsci.lib.configprovider.model;

import java.io.Serializable;

import hudson.Util;

public class ConfigFile implements Serializable {
private static final long serialVersionUID = 1L;

private final String fileId;
protected String targetLocation;
protected boolean replaceTokens;

public ConfigFile(String fileId, String targetLocation, boolean replaceTokens) {
this.fileId = fileId;
this.targetLocation = Util.fixEmptyAndTrim(targetLocation);
this.replaceTokens = replaceTokens;
}

public String getFileId() {
return fileId;
}

public String getTargetLocation() {
return this.targetLocation;
}

public boolean isReplaceTokens() {
return replaceTokens;
}

}
@@ -0,0 +1,130 @@
/*
The MIT License
Copyright (c) 2011, Dominik Bartholdi, Olivier Lamy
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package org.jenkinsci.lib.configprovider.model;

import hudson.AbortException;
import hudson.FilePath;
import hudson.model.*;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.lang.StringUtils;
import org.jenkinsci.lib.configprovider.ConfigProvider;
import org.jenkinsci.lib.configprovider.model.Config;
import org.jenkinsci.plugins.configfiles.ConfigFiles;
import org.jenkinsci.plugins.configfiles.buildwrapper.Messages;
import org.jenkinsci.plugins.tokenmacro.MacroEvaluationException;
import org.jenkinsci.plugins.tokenmacro.TokenMacro;

import hudson.slaves.WorkspaceList;

public class ConfigFileManager {
private final static Logger LOGGER = Logger.getLogger(ConfigFileManager.class.getName());

/**
* TODO use 1.652 use WorkspaceList.tempDir
*
* @param ws workspace of the {@link hudson.model.Build}. See {@link Build#getWorkspace()}
* @return temporary directory, may not have been created so far
*/
public static FilePath tempDir(FilePath ws) {
return ws.sibling(ws.getName() + System.getProperty(WorkspaceList.class.getName(), "@") + "tmp");
}

/**
* Provisions (publishes) the given file to the workspace.
*
* @param managedFile the file to be provisioned
* @param workspace target workspace
* @param listener the listener
* @param tempFiles temp files created by this method, these files should be deleted by the caller
* @return remote location path of the provided file.
* @throws IOException
* @throws InterruptedException
* @throws AbortException config file has not been found
*/
public static FilePath provisionConfigFile(ConfigFile managedFile, Run<?, ?> build, FilePath workspace, TaskListener listener, List<String> tempFiles) throws IOException, InterruptedException {
Config configFile = ConfigFiles.getByIdOrNull(build, managedFile.getFileId());

if (configFile == null) {
String message = "not able to provide the file " + managedFile + ", can't be resolved by any provider - maybe it got deleted by an administrator?";
listener.getLogger().println(message);
throw new AbortException(message);
}

FilePath workDir = tempDir(workspace);
workDir.mkdirs();

boolean createTempFile = StringUtils.isBlank(managedFile.getTargetLocation());

FilePath target;
if (createTempFile) {
target = workDir.createTempFile("config", "tmp");
} else {

String expandedTargetLocation = managedFile.getTargetLocation();
try {
expandedTargetLocation = TokenMacro.expandAll(build, workspace, listener, managedFile.getTargetLocation());
} catch (MacroEvaluationException e) {
listener.getLogger().println("[ERROR] failed to expand variables in target location '" + managedFile.getTargetLocation() + "' : " + e.getMessage());
expandedTargetLocation = managedFile.getTargetLocation();
}

// Should treat given path as the actual filename unless it has a trailing slash (implying a
// directory) or path already exists in workspace as a directory.
target = new FilePath(workspace, expandedTargetLocation);
String immediateFileName = expandedTargetLocation.substring(expandedTargetLocation.lastIndexOf("/") + 1);

if (immediateFileName.length() == 0 || (target.exists() && target.isDirectory())) {
target = new FilePath(target, configFile.name.replace(" ", "_"));
}
}

ConfigProvider provider = configFile.getDescriptor();
String fileContent = provider.supplyContent(configFile, build, workDir, listener, tempFiles);

if (managedFile.isReplaceTokens()) {
try {
fileContent = TokenMacro.expandAll(build, workspace, listener, fileContent);
} catch (MacroEvaluationException e) {
listener.getLogger().println("[ERROR] failed to expand variables in content of " + configFile.name + " - " + e.getMessage());
}
}

LOGGER.log(Level.FINE, "Create file {0} for configuration {1} mapped as {2}", new Object[]{target.getRemote(), configFile, managedFile});
listener.getLogger().println(Messages.console_output(configFile.name, target.toURI()));
ByteArrayInputStream bs = new ByteArrayInputStream(fileContent.getBytes("UTF-8"));
target.copyFrom(bs);
target.chmod(0640);

return target;
}

}
Expand Up @@ -70,7 +70,7 @@ public void setUp(Context context, Run<?, ?> build, FilePath workspace, Launcher
if (!StringUtils.isBlank(mf.variable)) {
context.env(mf.variable, fp.getRemote());
}
boolean noTargetGiven = StringUtils.isBlank(entry.getKey().targetLocation);
boolean noTargetGiven = StringUtils.isBlank(entry.getKey().getTargetLocation());
if (noTargetGiven) {
tempFiles.add(entry.getValue().getRemote());
}
Expand Down
Expand Up @@ -33,6 +33,7 @@ of this software and associated documentation files (the "Software"), to deal
import jenkins.model.Jenkins;
import org.jenkinsci.Symbol;
import org.jenkinsci.lib.configprovider.model.Config;
import org.jenkinsci.lib.configprovider.model.ConfigFile;
import org.jenkinsci.plugins.configfiles.ConfigFiles;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
Expand All @@ -43,17 +44,9 @@ of this software and associated documentation files (the "Software"), to deal
/**
* @author domi
*/
public class ManagedFile implements ExtensionPoint, Describable<ManagedFile>, Serializable {
public class ManagedFile extends ConfigFile implements ExtensionPoint, Describable<ManagedFile>, Serializable {

public final String fileId;
public String targetLocation;
public String variable;
/**
* whether tokens in the content of the file must be replaced by the TokenMacro plugin
*
* @since 2.10.2
*/
private Boolean replaceTokens;

/**
* @param fileId the id of the file to be provided
Expand All @@ -62,30 +55,22 @@ public class ManagedFile implements ExtensionPoint, Describable<ManagedFile>, Se
*/
@DataBoundConstructor
public ManagedFile(String fileId) {
this.fileId = fileId;
super(fileId, null, false);
}

public ManagedFile(String fileId, String targetLocation, String variable, Boolean replaceTokens) {
this.fileId = fileId;
this.targetLocation = Util.fixEmpty(targetLocation);
this.variable = Util.fixEmpty(variable);
this.replaceTokens = replaceTokens;
super(fileId, targetLocation, replaceTokens);
this.variable = Util.fixEmptyAndTrim(variable);
}

public ManagedFile(String fileId, String targetLocation, String variable) {
this.fileId = fileId;
this.targetLocation = Util.fixEmpty(targetLocation);
this.variable = Util.fixEmpty(variable);
this.replaceTokens = false;
}

public String getTargetLocation() {
return this.targetLocation;
super(fileId, targetLocation, false);
this.variable = Util.fixEmptyAndTrim(variable);
}

@DataBoundSetter
public void setTargetLocation(String targetLocation) {
this.targetLocation = Util.fixEmpty(targetLocation);
this.targetLocation = Util.fixEmptyAndTrim(targetLocation);
}

public String getVariable() {
Expand All @@ -94,21 +79,17 @@ public String getVariable() {

@DataBoundSetter
public void setVariable(String variable) {
this.variable = Util.fixEmpty(variable);
this.variable = Util.fixEmptyAndTrim(variable);
}

@DataBoundSetter
public void setReplaceTokens(Boolean replaceTokens) {
this.replaceTokens = replaceTokens;
this.replaceTokens = replaceTokens != null ? replaceTokens : false;
}

@Override
public String toString() {
return "[ManagedFile: id=" + fileId + ", targetLocation=" + targetLocation + ", variable=" + variable + "]";
}

public Boolean getReplaceTokens() {
return replaceTokens != null ? replaceTokens : false;
return "[ManagedFile: id=" + getFileId() + ", targetLocation=" + getTargetLocation() + ", variable=" + variable + "]";
}

@Override
Expand Down

0 comments on commit 04fc069

Please sign in to comment.