@Override public FilePath performInstallation(ToolInstallation tool, Node node, TaskListener log) throws IOException, InterruptedException { FilePath dir = preferredLocation(tool, node); // TODO support Unix scripts with interpreter line (see Shell.buildCommandLine) FilePath script = dir.createTextTempFile("hudson", getCommandFileExtension(), command); try { String cmd[] = getCommandCall(script); int r = node.createLauncher(log).launch().cmds(cmd).stdout(log).pwd(dir).join(); if (r != 0) { throw new IOException("Command returned status " + r); } } finally { script.delete(); } return dir.child(getToolHome()); }
.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); return false; args.add(exec); args.add("-Dmaven.repo.local=" + build.getWorkspace().child(".repository")); args.addTokenized(normalizedTarget); wrapUpArguments(args,normalizedTarget,build,launcher,listener); if (!launcher.isUnix()) { args = args.toWindowsCommand(); int r = launcher.launch().cmds(args).envs(env).stdout(mca).pwd(build.getModuleRoot()).join(); if (0 != r) { return false;
@Override public boolean checkImageExists(TaskListener listener, String image) throws IOException, InterruptedException { ArgumentListBuilder args = new ArgumentListBuilder() .add("inspect") .add("-f", "'{{.Id}}'") .add(image); ByteArrayOutputStream out = new ByteArrayOutputStream(); Launcher launcher = new Launcher.LocalLauncher(listener); return launchDockerCLI(launcher, args) .stdout(out).stderr(launcher.getListener().getLogger()).join() == 0; }
private String getMavenVersionFromConsole() throws Exception { ArgumentListBuilder args = new ArgumentListBuilder(); args.add(getExecutable()); args.add("--version"); env.put(M2_HOME, getHome().getRemote()); env.put(MAVEN_SKIP_RC, TRUE); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); Proc process = launcher.launch() .cmds(args) .envs(env) .pwd(build.getWorkspace()) .stdout(buffer) .start(); String output = new String(buffer.toByteArray()); if (muxlog.isTraceEnabled()) { muxlog.trace("Process output:\n{}", output);
/** * Runs the command and captures the output. */ public String popen(FilePath repository, TaskListener listener, boolean useTimeout, ArgumentListBuilder args) throws IOException, InterruptedException { args = seed(false).add(args.toCommandArray()); ByteArrayOutputStream rev = new ByteArrayOutputStream(); if (MercurialSCM.joinWithPossibleTimeout(l(args).pwd(repository).stdout(rev), useTimeout, listener) == 0) { return rev.toString(); } else { listener.error("Failed to run " + args.toStringWithQuote()); listener.getLogger().write(rev.toByteArray()); throw new AbortException(); } }
@Override public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { Charset charset = Charset.defaultCharset(); FilePath basePath = new FilePath(f); Launcher launcher = basePath.createLauncher(new StreamTaskListener(new NullOutputStream(), charset)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Proc starter = launcher.launch().cmdAsSingleString("uname -m").stdout(baos).start(); int exitCode = starter.join(); if (exitCode != 0) { throw new IOException("Fail to execute 'uname -m' because: " + baos.toString(charset.name())); } return new String(baos.toByteArray(), charset).trim(); } };
public boolean pullImage(String image) throws IOException, InterruptedException { ArgumentListBuilder args = dockerCommand() .add("pull", image); OutputStream out = verbose ? listener.getLogger() : new ByteArrayOutputStream(); OutputStream err = verbose ? listener.getLogger() : new ByteArrayOutputStream(); int status = launcher.launch() .envs(getEnvVars()) .cmds(args) .stdout(out).stderr(err).join(); return status == 0; }
public String buildImage(FilePath workspace, String dockerfile, boolean forcePull, boolean noCache) throws IOException, InterruptedException { .add("build"); args.add("--pull"); args.add("--no-cache"); args.add("--file", dockerfile) .add(workspace.getRemote()); args.add("--label", "jenkins-project=" + this.build.getProject().getName()); args.add("--label", "jenkins-build-number=" + this.build.getNumber()); OutputStream logOutputStream = listener.getLogger(); OutputStream err = listener.getLogger(); ByteArrayOutputStream resultOutputStream = new ByteArrayOutputStream(); TeeOutputStream teeOutputStream = new TeeOutputStream(logOutputStream, resultOutputStream); int status = launcher.launch() .envs(getEnvVars()) .cmds(args) .stdout(teeOutputStream).stderr(err).join(); if (status != 0) { throw new RuntimeException("Failed to build docker image from project Dockerfile"); Matcher matcher = pattern.matcher(resultOutputStream.toString("UTF-8")); if (!matcher.find())
private LaunchResult launch(@CheckForNull @Nonnull EnvVars launchEnv, boolean quiet, FilePath pwd, @Nonnull ArgumentListBuilder args) throws IOException, InterruptedException { // Prepend the docker command args.prepend(DockerTool.getExecutable(toolName, node, launcher.getListener(), launchEnv)); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Executing docker command {0}", args.toString()); } Launcher.ProcStarter procStarter = launcher.launch(); if (pwd != null) { procStarter.pwd(pwd); } LaunchResult result = new LaunchResult(); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream err = new ByteArrayOutputStream(); result.setStatus(procStarter.quiet(quiet).cmds(args).envs(launchEnv).stdout(out).stderr(err).start().joinWithTimeout(CLIENT_TIMEOUT, TimeUnit.SECONDS, launcher.getListener())); final String charsetName = Charset.defaultCharset().name(); result.setOut(out.toString(charsetName)); result.setErr(err.toString(charsetName)); return result; }
/** * Who is executing this {@link DockerClient} instance. * * @return a {@link String} containing the <strong>uid:gid</strong>. */ public String whoAmI() throws IOException, InterruptedException { ByteArrayOutputStream userId = new ByteArrayOutputStream(); launcher.launch().cmds("id", "-u").quiet(true).stdout(userId).start().joinWithTimeout(CLIENT_TIMEOUT, TimeUnit.SECONDS, launcher.getListener()); ByteArrayOutputStream groupId = new ByteArrayOutputStream(); launcher.launch().cmds("id", "-g").quiet(true).stdout(groupId).start().joinWithTimeout(CLIENT_TIMEOUT, TimeUnit.SECONDS, launcher.getListener()); final String charsetName = Charset.defaultCharset().name(); return String.format("%s:%s", userId.toString(charsetName).trim(), groupId.toString(charsetName).trim()); }
private String whoAmI(Launcher launcher) throws IOException, InterruptedException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); launcher.launch().cmds("id", "-u").stdout(bos).quiet(true).join(); String uid = bos.toString().trim(); String gid = group; if (isEmpty(group)) { ByteArrayOutputStream bos2 = new ByteArrayOutputStream(); launcher.launch().cmds("id", "-g").stdout(bos2).quiet(true).join(); gid = bos2.toString().trim(); } return uid+":"+gid; }
public void doListViews(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Hudson.getInstance().createLauncher(TaskListener.NULL).launch().cmds(getCleartoolExe(), "lsview", "-short").stdout(baos).join(); rsp.setContentType("text/plain"); rsp.getOutputStream().println("ClearCase Views found:\n"); baos.writeTo(rsp.getOutputStream()); }
boolean skipNpmPackageInstallation = areNpmPackagesUpToDate(expected, globalPackages, getNpmPackagesRefreshHours()); if (!skipNpmPackageInstallation) { expected.child(NPM_PACKAGES_RECORD_FILENAME).delete(); ArgumentListBuilder npmScriptArgs = new ArgumentListBuilder(); if (platform == Platform.WINDOWS) { npmScriptArgs.add("cmd"); npmScriptArgs.add("/c"); FilePath binFolder = expected.child(platform.binFolder); FilePath npmExe = binFolder.child(platform.npmFileName); npmScriptArgs.add(npmExe); buildProxyEnvVars(env, log); } catch (URISyntaxException e) { log.error("Wrong proxy URL: " + e.getMessage()); int returnCode = launcher.launch().envs(env).cmds(npmScriptArgs).stdout(log).join();
public static void exeConan(ArgumentListBuilder args, FilePath pwd, Launcher launcher, TaskListener listener, Run build, EnvVars env) { boolean failed; try { if (!pwd.exists()) { pwd.mkdirs(); if (launcher.isUnix()) { boolean hasMaskedArguments = args.hasMaskedArguments(); StringBuilder sb = new StringBuilder(); for (String arg : args.toList()) { sb.append(escapeUnixArgument(arg)).append(" "); args.clear(); args.add("sh", "-c"); if (hasMaskedArguments) { args = args.toWindowsCommand(); int exitValue = launcher.launch().cmds(args).envs(env).stdout(listener).pwd(pwd).join(); failed = (exitValue != 0); } catch (Exception e) { listener.error("Couldn't execute the conan client executable. " + e.getMessage()); build.setResult(Result.FAILURE); throw new Run.RunnerAbortedException();
private void runCommentsRemoverProcess(FilePath workspace, Launcher launcher, TaskListener listener, File removerScriptDir, File outputDirPath) throws IOException, InterruptedException { String pythonPath = getDescriptor().getPythonPath(); String pipPath = getDescriptor().getPipPath(); String pipExecutable = StringUtils.isEmpty(pythonPath) ? "pip" : pipPath; String[] pipCommand = new String[]{pipExecutable, "install", "-r", removerScriptDir + File.separator + "requirements.txt", "-q"}; listener.getLogger().println("Installing pip requirements [" + StringUtils.join(pipCommand, " ") + "]..."); runProcess(launcher.launch().cmds(pipCommand).readStdout().start(), listener); String pythonExecutable = StringUtils.isEmpty(pythonPath) ? "python" : pythonPath; String[] commentsRemoverCommand = new String[]{pythonExecutable, removerScriptDir + File.separator + COMMENTS_REMOVER_ENTRY_FILE, workspace.getRemote() + File.separator + filename, language, outputDirPath.getAbsolutePath()}; listener.getLogger().println("Executing script [" + StringUtils.join(commentsRemoverCommand, " ") + "]..."); runProcess(launcher.launch().cmds(commentsRemoverCommand).readStdout().start(), listener); }
@Override public KeyMaterial materialize() throws IOException, InterruptedException { FilePath dockerConfig = createSecretsDirectory(); try { // TODO on Docker 17.07+ use --password-stdin EnvVars envWithConfig = new EnvVars(env); envWithConfig.put("DOCKER_CONFIG", dockerConfig.getRemote()); if (launcher.launch().cmds(new ArgumentListBuilder(dockerExecutable, "login", "-u", username, "-p").add(password, true).add(endpoint)).envs(envWithConfig).stdout(listener).join() != 0) { throw new AbortException("docker login failed"); } } catch (IOException | InterruptedException x) { try { dockerConfig.deleteRecursive(); } catch (Exception x2) { x.addSuppressed(x2); } throw x; } return new RegistryKeyMaterial(dockerConfig, new EnvVars("DOCKER_CONFIG", dockerConfig.getRemote())); }
@Override public Proc execInContainer(TaskListener listener, String containerId, Launcher.ProcStarter starter) throws IOException, InterruptedException { ArgumentListBuilder args = new ArgumentListBuilder() .add("exec", containerId); if (starter.pwd() != null) { args.add("/trampoline", "cdexec", starter.pwd().getRemote()); } args.add("env").add(starter.envs()); List<String> originalCmds = starter.cmds(); boolean[] originalMask = starter.masks(); for (int i = 0; i < originalCmds.size(); i++) { boolean masked = originalMask == null ? false : i < originalMask.length ? originalMask[i] : false; args.add(originalCmds.get(i), masked); } Launcher launcher = new Launcher.LocalLauncher(listener); Launcher.ProcStarter procStarter = launchDockerCLI(launcher, args); if (starter.stdout() != null) { procStarter.stdout(starter.stdout()); } return procStarter.start(); }