@Override public Environment setUp(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { if (!StringUtils.isEmpty(location) && !StringUtils.isEmpty(file.getName())) { listener.getLogger().println("Copying file to "+location); FilePath ws = build.getWorkspace(); if (ws == null) { throw new IllegalStateException("The workspace should be created when setUp method is called"); } if (!ALLOW_FOLDER_TRAVERSAL_OUTSIDE_WORKSPACE && !ws.isDescendant(location)) { listener.error("Rejecting file path escaping base directory with relative path: " + location); // force the build to fail return null; } FilePath locationFilePath = ws.child(location); locationFilePath.getParent().mkdirs(); locationFilePath.copyFrom(file); locationFilePath.copyTo(new FilePath(getLocationUnderBuild(build))); } return new Environment() {}; } };
/** * Prints out the command line to the listener so that users know what we are doing. */ protected final void printCommandLine(@Nonnull String[] cmd, @CheckForNull FilePath workDir) { StringBuilder buf = new StringBuilder(); if (workDir != null) { buf.append('['); if(showFullPath) buf.append(workDir.getRemote()); else buf.append(workDir.getRemote().replaceFirst("^.+[/\\\\]", "")); buf.append("] "); } buf.append('$'); for (String c : cmd) { buf.append(' '); if(c.indexOf(' ')>=0) { if(c.indexOf('"')>=0) buf.append('\'').append(c).append('\''); else buf.append('"').append(c).append('"'); } else buf.append(c); } listener.getLogger().println(buf.toString()); }
/** * Checks if the specified expected location already contains the installed version of the tool. * * This check needs to run fairly efficiently. The current implementation uses the source URL of {@link Installable}, * based on the assumption that released bits do not change its content. */ protected boolean isUpToDate(FilePath expectedLocation, Installable i) throws IOException, InterruptedException { FilePath marker = expectedLocation.child(".installedFrom"); return marker.exists() && marker.readToString().equals(i.url); }
public FilePath performInstallation(ToolInstallation tool, Node node, TaskListener log) throws IOException, InterruptedException { FilePath expected = preferredLocation(tool, node); Installable inst = getInstallable(); if(inst==null) { log.getLogger().println("Invalid tool ID "+id); return expected; } if (inst instanceof NodeSpecific) { inst = (Installable) ((NodeSpecific) inst).forNode(node, log); } if(isUpToDate(expected,inst)) return expected; if(expected.installIfNecessaryFrom(new URL(inst.url), log, "Unpacking " + inst.url + " to " + expected + " on " + node.getDisplayName())) { expected.child(".timestamp").delete(); // we don't use the timestamp FilePath base = findPullUpDirectory(expected); if(base!=null && base!=expected) base.moveAllChildrenTo(expected); // leave a record for the next up-to-date check expected.child(".installedFrom").write(inst.url,"UTF-8"); expected.act(new ZipExtractionInstaller.ChmodRecAPlusX()); } return expected; }
@Override public void perform(Run<?,?> build, FilePath workspace, Launcher launcher, TaskListener listener) throws InterruptedException, IOException { listener.getLogger().println(Messages.JavadocArchiver_Publishing()); EnvVars env = build.getEnvironment(listener); FilePath javadoc = workspace.child(env.expand(javadocDir)); FilePath target = new FilePath(keepAll ? getJavadocDir(build) : getJavadocDir(build.getParent())); try { if (javadoc.copyRecursiveTo("**/*",target)==0) { if(build.getResult().isBetterOrEqualTo(Result.UNSTABLE)) { // If the build failed, don't complain that there was no javadoc. // The build probably didn't even get to the point where it produces javadoc. listener.error(Messages.JavadocArchiver_NoMatchFound(javadoc,javadoc.validateAntFileMask("**/*"))); } build.setResult(Result.FAILURE); return; } } catch (IOException e) { Util.displayIOException(e,listener); e.printStackTrace(listener.fatalError(Messages.JavadocArchiver_UnableToCopy(javadoc,target))); build.setResult(Result.FAILURE); return; } build.addAction(new JavadocBuildAction()); }
private boolean installIfNecessaryFrom(@Nonnull URL archive, @CheckForNull TaskListener listener, @Nonnull String message, int maxRedirects) throws InterruptedException, IOException { try { FilePath timestamp = this.child(".timestamp"); long lastModified = timestamp.lastModified(); URLConnection con; try { if (this.exists()) { listener.getLogger().println("Following redirect " + archive.toExternalForm() + " -> " + location); return installIfNecessaryFrom(getUrlFactory().newURL(location), listener, message, maxRedirects - 1); } else { listener.getLogger().println("Skipping installation of " + archive + " to " + remote + " due to too many redirects."); return false; if(this.exists()) { if (lastModified != 0 && sourceTimestamp == lastModified) return false; // already up to date this.deleteContents(); } else { this.mkdirs(); if (isRemote()) { act(new Unpack(archive)); timestamp.touch(sourceTimestamp); return true; } catch (IOException x) { try {
private WorkspaceOfflineReason workspaceOffline(R build) throws IOException, InterruptedException { FilePath ws = build.getWorkspace(); Label label = getAssignedLabel(); if (isAllSuitableNodesOffline(build)) { Collection<Cloud> applicableClouds = label == null ? Jenkins.getInstance().clouds : label.getClouds(); return applicableClouds.isEmpty() ? WorkspaceOfflineReason.all_suitable_nodes_are_offline : WorkspaceOfflineReason.use_ondemand_slave; } if (ws==null || !ws.exists()) { return WorkspaceOfflineReason.nonexisting_workspace; } Node builtOn = build.getBuiltOn(); if (builtOn == null) { // node built-on doesn't exist anymore return WorkspaceOfflineReason.builton_node_gone; } if (builtOn.toComputer() == null) { // node still exists, but has 0 executors - o.s.l.t. return WorkspaceOfflineReason.builton_node_no_executors; } return null; }
private void assertRevision(@CheckForNull SCMRevision rev, @CheckForNull String expectedFile, @NonNull SCMSource source, @NonNull Run<?,?> run, @NonNull TaskListener listener) throws Exception { if (rev == null) { assertNull(expectedFile); return; } FilePath ws = new FilePath(run.getRootDir()).child("tmp"); try { source.build(rev.getHead(), rev).checkout(run, new Launcher.LocalLauncher(listener), ws, listener, null, SCMRevisionState.NONE); } catch (Exception x) { x.printStackTrace(listener.error("could not check out")); assertNull(expectedFile); return; } FilePath file = ws.child("file"); assertEquals(expectedFile, file.exists() ? file.readToString() : null); }
@Url("http://hudson.pastebin.com/m3ea34eea") @Test @Ignore("TODO use docker-fixtures for a reproducible test case") public void remoteCheckOut() throws Exception { DumbSlave s = r.createSlave(); FreeStyleProject p = r.createFreeStyleProject(); p.setAssignedLabel(s.getSelfLabel()); p.setScm(new SubversionSCM("https://svn.jenkins-ci.org/trunk/hudson/test-projects/trivial-ant/")); FreeStyleBuild b = r.assertBuildStatusSuccess(p.scheduleBuild2(0, new Cause.UserIdCause()).get()); assertTrue(b.getWorkspace().child("build.xml").exists()); r.assertBuildStatusSuccess(p.scheduleBuild2(0).get()); }
public String getToolHome(Node node, ToolInstallation tool, TaskListener log) throws IOException, InterruptedException { if (node.getRootPath() == null) { log.error(node.getDisplayName() + " is offline; cannot locate " + tool.getName()); return null; return installer.performInstallation(tool, node, log).getRemote(); } finally { semaphore.release(); installer.getDescriptor().getDisplayName(), tool.getName(), node.getDisplayName())); log.getLogger().println(message);
Jenkins jenkins = Jenkins.get(); setCurrentLevel(Jenkins.getVersion()); if(jenkins.getSecurityRealm() == null || jenkins.getSecurityRealm() == SecurityRealm.NO_AUTHENTICATION) { // this seems very fragile try (BulkChange bc = new BulkChange(jenkins)) { HudsonPrivateSecurityRealm securityRealm = new HudsonPrivateSecurityRealm(false, false, null); iapf.touch(System.currentTimeMillis()); iapf.chmod(0640); iapf.write(randomUUID + System.lineSeparator(), "UTF-8"); if(iapf.exists()) { String setupKey = iapf.readToString().trim(); String ls = System.lineSeparator(); LOGGER.info(ls + ls + "*************************************************************" + ls + setupKey + ls + ls + "This may also be found at: " + iapf.getRemote() + ls + ls + "*************************************************************" + ls
Result result = build.getResult(); if (onlyIfSuccessful && result != null && result.isWorseThan(Result.UNSTABLE)) { listener.getLogger().println(Messages.ArtifactArchiver_SkipBecauseOnlyIfSuccessful()); return; listener.getLogger().println(Messages.ArtifactArchiver_ARCHIVING_ARTIFACTS()); try { String artifacts = build.getEnvironment(listener).expand(this.artifacts); Map<String,String> files = ws.act(new ListFiles(artifacts, excludes, defaultExcludes, caseSensitive)); if (!files.isEmpty()) { build.pickArtifactManager().archive(ws, launcher, BuildListenerAdapter.wrap(listener), files); if (fingerprint) { new Fingerprinter(artifacts).perform(build, ws, launcher, listener); if (result == null || result.isBetterOrEqualTo(Result.UNSTABLE)) { try { String msg = ws.validateAntFileMask(artifacts, FilePath.VALIDATE_ANT_FILE_MASK_BOUND, caseSensitive); if (msg != null) { listener.getLogger().println(msg);
public String buildAndCheck(FreeStyleProject p, String name, Action... actions) throws Exception { FreeStyleBuild b = j.assertBuildStatusSuccess(p.scheduleBuild2(0, null, actions).get()); // for (String line : b.getLog(Integer.MAX_VALUE)) { // System.err.println(">> " + line); // } if (!b.getWorkspace().child(name).exists()) { Set<String> children = new TreeSet<>(); for (FilePath child : b.getWorkspace().list()) { children.add(child.getName()); } fail("Could not find " + name + " among " + children); } assertNotNull(b.getAction(MercurialTagAction.class)); @SuppressWarnings("deprecation") String log = b.getLog(); return log; }
PrintStream log = taskListener.getLogger(); if (Util.isRelativePath(remoteFS)) { remoteFS = channel.call(new AbsolutePath(remoteFS)); log.println("NOTE: Relative remote path resolved to: "+remoteFS); log.println("WARNING: "+remoteFS +" looks suspiciously like Windows path. Maybe you meant "+remoteFS.replace('\\','/')+"?"); FilePath root = new FilePath(channel,remoteFS); Jenkins.get().getQueue().scheduleMaintenance();
@Override public EnvVars getEnvironment(TaskListener log) throws IOException, InterruptedException { EnvVars env = super.getEnvironment(log); FilePath ws = getWorkspace(); if (ws!=null) // if this is done very early on in the build, workspace may not be decided yet. see HUDSON-3997 env.put("WORKSPACE", ws.getRemote()); project.getScm().buildEnvVars(this,env); if (buildEnvironments!=null) for (Environment e : buildEnvironments) e.buildEnvVars(env); for (EnvironmentContributingAction a : getActions(EnvironmentContributingAction.class)) a.buildEnvVars(this,env); EnvVars.resolve(env); return env; }
private String expandStashURL(Run<?, ?> run, final TaskListener listener) { String url = stashServerBaseUrl; DescriptorImpl descriptor = getDescriptor(); if (url == null || url.isEmpty()) { url = descriptor.getStashRootUrl(); } try { if (!(run instanceof AbstractBuild<?, ?>)) { url = TokenMacro.expandAll(run, new FilePath(run.getRootDir()), listener, url); } else { url = TokenMacro.expandAll((AbstractBuild<?, ?>) run, listener, url); } } catch (IOException | InterruptedException | MacroEvaluationException ex) { PrintStream logger = listener.getLogger(); logger.println("Unable to expand Stash Server URL"); ex.printStackTrace(logger); } return url; }
private R getSomeBuildWithExistingWorkspace() throws IOException, InterruptedException { int cnt=0; for (R b = getLastBuild(); cnt<5 && b!=null; b=b.getPreviousBuild()) { FilePath ws = b.getWorkspace(); if (ws!=null && ws.exists()) return b; } return null; }
@Override protected Void run() throws Exception { FilePath ws = getContext().get(FilePath.class); ws.mkdirs(); TaskListener listener = getContext().get(TaskListener.class); if (listener != null) { listener.getLogger().println(Messages.ArtifactArchiverStepExecution_Deprecated()); } Map<String,String> files = ws.act(new ListFiles(step.getIncludes(), step.getExcludes())); if (files.isEmpty()) { if (step.getExcludes() != null && !step.getExcludes().equals("")) { listener.getLogger().println(Messages.ArtifactArchiverStepExecution_NoFilesWithExcludes(step.getIncludes(), step.getExcludes())); } else { listener.getLogger().println(Messages.ArtifactArchiverStepExecution_NoFiles(step.getIncludes())); } } else { getContext().get(Run.class).pickArtifactManager().archive(ws, getContext().get(Launcher.class), new BuildListenerAdapter(getContext().get(TaskListener.class)), files); } return null; }