Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add remoting workdir #352

Merged
merged 6 commits into from May 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
122 changes: 122 additions & 0 deletions src/main/java/hudson/os/WindowsUtil.java
@@ -0,0 +1,122 @@
/*
* The MIT License
*
* Copyright (c) 2019 CloudBees, Inc.
*
* 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.
*/

//TODO: Have this added to core
//https://github.com/jenkinsci/ec2-plugin/pull/352/
package hudson.os;

import hudson.Functions;
import org.apache.commons.io.IOUtils;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;

import javax.annotation.Nonnull;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

// adapted from:
// https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
@Restricted(NoExternalUse.class)
public class WindowsUtil {
res0nance marked this conversation as resolved.
Show resolved Hide resolved
private static final Pattern NEEDS_QUOTING = Pattern.compile("[\\s\"]");

/**
* Quotes an argument while escaping special characters interpreted by CreateProcess.
*/
public static @Nonnull String quoteArgument(@Nonnull String argument) {
if (!NEEDS_QUOTING.matcher(argument).find()) return argument;
StringBuilder sb = new StringBuilder();
sb.append('"');
int end = argument.length();
for (int i = 0; i < end; i++) {
int nrBackslashes = 0;
while (i < end && argument.charAt(i) == '\\') {
i++;
nrBackslashes++;
}

if (i == end) {
// backslashes at the end of the argument must be escaped so the terminate quote isn't
nrBackslashes = nrBackslashes * 2;
} else if (argument.charAt(i) == '"') {
// backslashes preceding a quote all need to be escaped along with the quote
nrBackslashes = nrBackslashes * 2 + 1;
}
// else backslashes have no special meaning and don't need to be escaped here

for (int j = 0; j < nrBackslashes; j++) {
sb.append('\\');
}

if (i < end) {
sb.append(argument.charAt(i));
}
}
return sb.append('"').toString();
}

private static final Pattern CMD_METACHARS = Pattern.compile("[()%!^\"<>&|]");

/**
* Quotes an argument while escaping special characters suitable for use as an argument to {@code cmd.exe}.
*/
public static @Nonnull String quoteArgumentForCmd(@Nonnull String argument) {
return CMD_METACHARS.matcher(quoteArgument(argument)).replaceAll("^$0");
}

/**
* Executes a command and arguments using {@code cmd.exe /C ...}.
*/
public static @Nonnull Process execCmd(String... argv) throws IOException {
String command = Arrays.stream(argv).map(WindowsUtil::quoteArgumentForCmd).collect(Collectors.joining(" "));
return Runtime.getRuntime().exec(new String[]{"cmd.exe", "/C", command});
}

/**
* Creates an NTFS junction point if supported. Similar to symbolic links, NTFS provides junction points which
* provide different features than symbolic links.
* @param junction NTFS junction point to create
* @param target target directory to junction
* @return the newly created junction point
* @throws IOException if the call to mklink exits with a non-zero status code
* @throws InterruptedException if the call to mklink is interrupted before completing
* @throws UnsupportedOperationException if this method is called on a non-Windows platform
*/
public static @Nonnull File createJunction(@Nonnull File junction, @Nonnull File target) throws IOException, InterruptedException {
if(Functions.isWindows() == false) {
throw new UnsupportedOperationException("Can only be called on windows platform");
}
Process mklink = execCmd("mklink", "/J", junction.getAbsolutePath(), target.getAbsolutePath());
int result = mklink.waitFor();
if (result != 0) {
String stderr = IOUtils.toString(mklink.getErrorStream());
String stdout = IOUtils.toString(mklink.getInputStream());
throw new IOException("Process exited with " + result + "\nStandard Output:\n" + stdout + "\nError Output:\n" + stderr);
}
return junction;
}
}
9 changes: 5 additions & 4 deletions src/main/java/hudson/plugins/ec2/ssh/EC2UnixLauncher.java
Expand Up @@ -218,10 +218,11 @@ protected void launchScript(EC2Computer computer, TaskListener listener) throws
logInfo(computer, listener, "Copying remoting.jar to: " + tmpDir);
scp.put(Jenkins.getInstance().getJnlpJars("remoting.jar").readFully(), "remoting.jar", tmpDir);

String jvmopts = node.jvmopts;
String prefix = computer.getSlaveCommandPrefix();
String suffix = computer.getSlaveCommandSuffix();
String launchString = prefix + " java " + (jvmopts != null ? jvmopts : "") + " -jar " + tmpDir + "/remoting.jar" + suffix;
final String jvmopts = node.jvmopts;
final String prefix = computer.getSlaveCommandPrefix();
final String suffix = computer.getSlaveCommandSuffix();
final String remoteFS = node.getRemoteFS();
String launchString = prefix + " java " + (jvmopts != null ? jvmopts : "") + " -jar " + tmpDir + "/remoting.jar -workDir " + remoteFS + suffix;
// launchString = launchString.trim();

SlaveTemplate slaveTemplate = computer.getSlaveTemplate();
Expand Down
10 changes: 7 additions & 3 deletions src/main/java/hudson/plugins/ec2/win/EC2WindowsLauncher.java
Expand Up @@ -11,6 +11,8 @@
import hudson.remoting.Channel;
import hudson.remoting.Channel.Listener;
import hudson.slaves.ComputerLauncher;
import hudson.Util;
import hudson.os.WindowsUtil;

import java.io.IOException;
import java.io.OutputStream;
Expand Down Expand Up @@ -42,7 +44,7 @@ protected void launchScript(EC2Computer computer, TaskListener listener) throws

try {
String initScript = node.initScript;
String tmpDir = (node.tmpDir != null && !node.tmpDir.equals("") ? node.tmpDir
String tmpDir = (node.tmpDir != null && !node.tmpDir.equals("") ? WindowsUtil.quoteArgument(Util.ensureEndsWith(node.tmpDir,"\\"))
: "C:\\Windows\\Temp\\");

logger.println("Creating tmp directory if it does not exist");
Expand Down Expand Up @@ -73,8 +75,10 @@ protected void launchScript(EC2Computer computer, TaskListener listener) throws
logger.println("remoting.jar sent remotely. Bootstrapping it");

final String jvmopts = node.jvmopts;
final WindowsProcess process = connection.execute("java " + (jvmopts != null ? jvmopts : "") + " -jar "
+ tmpDir + AGENT_JAR, 86400);
final String remoteFS = WindowsUtil.quoteArgument(node.getRemoteFS());
final String launchString = "java " + (jvmopts != null ? jvmopts : "") + " -jar " + tmpDir + AGENT_JAR + " -workDir " + remoteFS;
logger.println("Launching via WinRM:" + launchString);
final WindowsProcess process = connection.execute(launchString, 86400);
computer.setChannel(process.getStdout(), process.getStdin(), logger, new Listener() {
@Override
public void onClosed(Channel channel, IOException cause) {
Expand Down