use of hudson.EnvVars in project hudson-2.x by hudson.
the class Run method getEnvironment.
/**
* Returns the map that contains environmental variables to be used for launching
* processes for this build.
*
* <p>
* {@link BuildStep}s that invoke external processes should use this.
* This allows {@link BuildWrapper}s and other project configurations (such as JDK selection)
* to take effect.
*
* <p>
* Unlike earlier {@link #getEnvVars()}, this map contains the whole environment,
* not just the overrides, so one can introspect values to change its behavior.
* @since 1.305
*/
public EnvVars getEnvironment(TaskListener log) throws IOException, InterruptedException {
EnvVars env = getCharacteristicEnvVars();
Computer c = Computer.currentComputer();
if (c != null) {
env = c.getEnvironment().overrideAll(env);
}
String rootUrl = Hudson.getInstance().getRootUrl();
if (rootUrl != null) {
env.put("HUDSON_URL", rootUrl);
env.put("BUILD_URL", rootUrl + getUrl());
env.put("JOB_URL", rootUrl + getParent().getUrl());
}
if (!env.containsKey("HUDSON_HOME")) {
env.put("HUDSON_HOME", Hudson.getInstance().getRootDir().getPath());
}
// Update HUDSON_USER property if it is not set. (see HUDSON-4463 discussion)
if (!env.containsKey(EnvVars.HUDSON_USER_ENV_KEY)) {
String value = EnvVars.getHudsonUserEnvValue();
if (null != value) {
env.put(EnvVars.HUDSON_USER_ENV_KEY, value);
}
}
Thread t = Thread.currentThread();
if (t instanceof Executor) {
Executor e = (Executor) t;
env.put("EXECUTOR_NUMBER", String.valueOf(e.getNumber()));
env.put("NODE_NAME", e.getOwner().getName());
Node n = e.getOwner().getNode();
if (n != null) {
env.put("NODE_LABELS", Util.join(n.getAssignedLabels(), " "));
}
}
for (EnvironmentContributor ec : EnvironmentContributor.all()) {
ec.buildEnvironmentFor(this, env, log);
}
return env;
}
use of hudson.EnvVars in project hudson-2.x by hudson.
the class Ant method perform.
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
ArgumentListBuilder args = new ArgumentListBuilder();
EnvVars env = build.getEnvironment(listener);
AntInstallation ai = getAnt();
if (ai == null) {
args.add(launcher.isUnix() ? "ant" : "ant.bat");
} else {
ai = ai.forNode(Computer.currentComputer().getNode(), listener);
ai = ai.forEnvironment(env);
String exe = ai.getExecutable(launcher);
if (exe == null) {
listener.fatalError(Messages.Ant_ExecutableNotFound(ai.getName()));
return false;
}
args.add(exe);
}
VariableResolver<String> vr = build.getBuildVariableResolver();
String buildFile = env.expand(this.buildFile);
String targets = Util.replaceMacro(env.expand(this.targets), vr);
FilePath buildFilePath = buildFilePath(build.getModuleRoot(), buildFile, targets);
if (!buildFilePath.exists()) {
// because of the poor choice of getModuleRoot() with CVS/Subversion, people often get confused
// with where the build file path is relative to. Now it's too late to change this behavior
// due to compatibility issue, but at least we can make this less painful by looking for errors
// and diagnosing it nicely. See HUDSON-1782
// first check if this appears to be a valid relative path from workspace root
FilePath buildFilePath2 = buildFilePath(build.getWorkspace(), buildFile, targets);
if (buildFilePath2.exists()) {
// This must be what the user meant. Let it continue.
buildFilePath = buildFilePath2;
} else {
// neither file exists. So this now really does look like an error.
listener.fatalError("Unable to find build script at " + buildFilePath);
return false;
}
}
if (buildFile != null) {
args.add("-file", buildFilePath.getName());
}
Set<String> sensitiveVars = build.getSensitiveBuildVariables();
args.addKeyValuePairs("-D", build.getBuildVariables(), sensitiveVars);
args.addKeyValuePairsFromPropertyString("-D", properties, vr, sensitiveVars);
args.addTokenized(targets.replaceAll("[\t\r\n]+", " "));
if (ai != null)
env.put("ANT_HOME", ai.getHome());
if (antOpts != null)
env.put("ANT_OPTS", env.expand(antOpts));
if (!launcher.isUnix()) {
args = args.toWindowsCommand();
// For some reason, ant on windows rejects empty parameters but unix does not.
// Add quotes for any empty parameter values:
List<String> newArgs = new ArrayList<String>(args.toList());
newArgs.set(newArgs.size() - 1, newArgs.get(newArgs.size() - 1).replaceAll("(?<= )(-D[^\" ]+)= ", "$1=\"\" "));
args = new ArgumentListBuilder(newArgs.toArray(new String[newArgs.size()]));
}
long startTime = System.currentTimeMillis();
try {
AntConsoleAnnotator aca = new AntConsoleAnnotator(listener.getLogger(), build.getCharset());
int r;
try {
r = launcher.launch().cmds(args).envs(env).stdout(aca).pwd(buildFilePath.getParent()).join();
} finally {
aca.forceEol();
}
return r == 0;
} catch (IOException e) {
Util.displayIOException(e, listener);
String errorMessage = Messages.Ant_ExecFailed();
if (ai == null && (System.currentTimeMillis() - startTime) < 1000) {
if (getDescriptor().getInstallations() == null)
// looks like the user didn't configure any Ant installation
errorMessage += Messages.Ant_GlobalConfigNeeded();
else
// There are Ant installations configured but the project didn't pick it
errorMessage += Messages.Ant_ProjectConfigNeeded();
}
e.printStackTrace(listener.fatalError(errorMessage));
return false;
}
}
use of hudson.EnvVars in project hudson-2.x by hudson.
the class Maven method perform.
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException {
VariableResolver<String> vr = build.getBuildVariableResolver();
EnvVars env = build.getEnvironment(listener);
String targets = Util.replaceMacro(this.targets, vr);
targets = env.expand(targets);
String pom = env.expand(this.pom);
String properties = env.expand(this.properties);
int startIndex = 0;
int endIndex;
do {
// split targets into multiple invokations of maven separated by |
endIndex = targets.indexOf('|', startIndex);
if (-1 == endIndex) {
endIndex = targets.length();
}
String normalizedTarget = targets.substring(startIndex, endIndex).replaceAll("[\t\r\n]+", " ");
ArgumentListBuilder args = new ArgumentListBuilder();
MavenInstallation mi = getMaven();
if (mi == null) {
String execName = build.getWorkspace().act(new DecideDefaultMavenCommand(normalizedTarget));
args.add(execName);
} else {
mi = mi.forNode(Computer.currentComputer().getNode(), listener);
mi = mi.forEnvironment(env);
String exec = mi.getExecutable(launcher);
if (exec == null) {
listener.fatalError(Messages.Maven_NoExecutable(mi.getHome()));
return false;
}
args.add(exec);
}
if (pom != null)
args.add("-f", pom);
Set<String> sensitiveVars = build.getSensitiveBuildVariables();
args.addKeyValuePairs("-D", build.getBuildVariables(), sensitiveVars);
args.addKeyValuePairsFromPropertyString("-D", properties, vr, sensitiveVars);
if (usesPrivateRepository())
args.add("-Dmaven.repo.local=" + build.getWorkspace().child(".repository"));
args.addTokenized(normalizedTarget);
wrapUpArguments(args, normalizedTarget, build, launcher, listener);
buildEnvVars(env, mi);
try {
MavenConsoleAnnotator mca = new MavenConsoleAnnotator(listener.getLogger(), build.getCharset());
int r = launcher.launch().cmds(args).envs(env).stdout(mca).pwd(build.getModuleRoot()).join();
if (0 != r) {
return false;
}
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages.Maven_ExecFailed()));
return false;
}
startIndex = endIndex + 1;
} while (startIndex < targets.length());
return true;
}
use of hudson.EnvVars in project hudson-2.x by hudson.
the class CommandLauncher method launch.
@Override
public void launch(SlaveComputer computer, final TaskListener listener) {
EnvVars _cookie = null;
Process _proc = null;
try {
listener.getLogger().println(hudson.model.Messages.Slave_Launching(getTimestamp()));
if (getCommand().trim().length() == 0) {
listener.getLogger().println(Messages.CommandLauncher_NoLaunchCommand());
return;
}
listener.getLogger().println("$ " + getCommand());
ProcessBuilder pb = new ProcessBuilder(Util.tokenize(getCommand()));
final EnvVars cookie = _cookie = EnvVars.createCookie();
pb.environment().putAll(cookie);
{
// system defined variables
String rootUrl = Hudson.getInstance().getRootUrl();
if (rootUrl != null) {
pb.environment().put("HUDSON_URL", rootUrl);
pb.environment().put("SLAVEJAR_URL", rootUrl + "/jnlpJars/slave.jar");
}
}
if (env != null) {
pb.environment().putAll(env);
}
final Process proc = _proc = pb.start();
// capture error information from stderr. this will terminate itself
// when the process is killed.
new StreamCopyThread("stderr copier for remote agent on " + computer.getDisplayName(), proc.getErrorStream(), listener.getLogger()).start();
computer.setChannel(proc.getInputStream(), proc.getOutputStream(), listener.getLogger(), new Channel.Listener() {
@Override
public void onClosed(Channel channel, IOException cause) {
try {
int exitCode = proc.exitValue();
if (exitCode != 0) {
listener.error("Process terminated with exit code " + exitCode);
}
} catch (IllegalThreadStateException e) {
// hasn't terminated yet
}
try {
ProcessTree.get().killAll(proc, cookie);
} catch (InterruptedException e) {
LOGGER.log(Level.INFO, "interrupted", e);
}
}
});
LOGGER.info("slave agent launched for " + computer.getDisplayName());
} catch (InterruptedException e) {
e.printStackTrace(listener.error(Messages.ComputerLauncher_abortedLaunch()));
} catch (RuntimeException e) {
e.printStackTrace(listener.error(Messages.ComputerLauncher_unexpectedError()));
} catch (Error e) {
e.printStackTrace(listener.error(Messages.ComputerLauncher_unexpectedError()));
} catch (IOException e) {
Util.displayIOException(e, listener);
String msg = Util.getWin32ErrorMessage(e);
if (msg == null) {
msg = "";
} else {
msg = " : " + msg;
}
msg = hudson.model.Messages.Slave_UnableToLaunch(computer.getDisplayName(), msg);
LOGGER.log(Level.SEVERE, msg, e);
e.printStackTrace(listener.error(msg));
if (_proc != null)
try {
ProcessTree.get().killAll(_proc, _cookie);
} catch (InterruptedException x) {
x.printStackTrace(listener.error(Messages.ComputerLauncher_abortedLaunch()));
}
}
}
use of hudson.EnvVars in project blueocean-plugin by jenkinsci.
the class GitUtils method validateCredentials.
/**
* Calls 'git ls-remote -h uri' to check if git uri or supplied credentials are valid
*
* @param uri git repo uri
* @param credentials credential to use when accessing git
* @return list of Errors. Empty list means success.
*/
static List<ErrorMessage.Error> validateCredentials(@Nonnull String uri, @Nullable StandardCredentials credentials) throws GitException {
List<ErrorMessage.Error> errors = new ArrayList<>();
Git git = new Git(TaskListener.NULL, new EnvVars());
try {
GitClient gitClient = git.getClient();
if (credentials != null) {
gitClient.addCredentials(uri, credentials);
}
gitClient.getRemoteReferences(uri, null, true, false);
} catch (IOException | InterruptedException e) {
logger.error("Error running git remote-ls: " + e.getMessage(), e);
throw new ServiceException.UnexpectedErrorException("Failed to create pipeline due to unexpected error: " + e.getMessage(), e);
} catch (IllegalStateException | GitException e) {
logger.error("Error running git remote-ls: " + e.getMessage(), e);
if (credentials != null) {
// this turn very hackhish with upgrade of git plugin as there is more and more and more cause/layers before having the real cause...
if (e instanceof IllegalStateException || e.getMessage().endsWith("not authorized") || e.getMessage().endsWith("not authenticated") || (e instanceof GitException && checkCauseNotAuthenticated((GitException) e))) {
errors.add(new ErrorMessage.Error("scmConfig.credentialId", ErrorMessage.Error.ErrorCodes.INVALID.toString(), "Invalid credentialId: " + credentials.getId()));
} else {
errors.add(new ErrorMessage.Error("scmConfig.uri", ErrorMessage.Error.ErrorCodes.INVALID.toString(), e.getMessage()));
}
} else if (e.getMessage().contains("Authentication is required") || e.getMessage().contains("connection is not authenticated")) {
errors.add(new ErrorMessage.Error("scmConfig.credentialId", ErrorMessage.Error.ErrorCodes.INVALID.toString(), e.getMessage()));
} else {
errors.add(new ErrorMessage.Error("scmConfig.uri", ErrorMessage.Error.ErrorCodes.INVALID.toString(), e.getMessage()));
}
}
return errors;
}
Aggregations