Search in sources :

Example 26 with FilePath

use of hudson.FilePath in project hudson-2.x by hudson.

the class JDKInstaller method performInstallation.

public FilePath performInstallation(ToolInstallation tool, Node node, TaskListener log) throws IOException, InterruptedException {
    FilePath expectedLocation = preferredLocation(tool, node);
    PrintStream out = log.getLogger();
    try {
        if (!acceptLicense) {
            out.println(Messages.JDKInstaller_UnableToInstallUntilLicenseAccepted());
            return expectedLocation;
        }
        // already installed?
        FilePath marker = expectedLocation.child(".installedByHudson");
        if (marker.exists() && marker.readToString().equals(id)) {
            return expectedLocation;
        }
        expectedLocation.deleteRecursive();
        expectedLocation.mkdirs();
        Platform p = Platform.of(node);
        URL url = locate(log, p, CPU.of(node));
        out.println("Downloading " + url);
        FilePath file = expectedLocation.child(p.bundleFileName);
        file.copyFrom(url);
        // JDK6u13 on Windows doesn't like path representation like "/tmp/foo", so make it a strict platform native format by doing 'absolutize'
        install(node.createLauncher(log), p, new FilePathFileSystem(node), log, expectedLocation.absolutize().getRemote(), file.getRemote());
        // successfully installed
        file.delete();
        marker.write(id, null);
    } catch (DetectionFailedException e) {
        out.println("JDK installation skipped: " + e.getMessage());
    }
    return expectedLocation;
}
Also used : FilePath(hudson.FilePath) PrintStream(java.io.PrintStream) URL(java.net.URL)

Example 27 with FilePath

use of hudson.FilePath in project hudson-2.x by hudson.

the class FailureBuildMail method getMail.

/**
     * @inheritDoc
     */
public MimeMessage getMail(AbstractBuild<?, ?> build, BuildListener listener) throws MessagingException, InterruptedException {
    MimeMessage msg = createEmptyMail(build, listener);
    msg.setSubject(getSubject(build, Messages.MailSender_FailureMail_Subject()), getCharset());
    StringBuilder buf = new StringBuilder();
    appendBuildUrl(build, buf);
    boolean firstChange = true;
    for (ChangeLogSet.Entry entry : build.getChangeSet()) {
        if (firstChange) {
            firstChange = false;
            buf.append(Messages.MailSender_FailureMail_Changes()).append("\n\n");
        }
        buf.append('[');
        buf.append(entry.getAuthor().getFullName());
        buf.append("] ");
        String m = entry.getMsg();
        if (m != null) {
            buf.append(m);
            if (!m.endsWith("\n")) {
                buf.append('\n');
            }
        }
        buf.append('\n');
    }
    buf.append("------------------------------------------\n");
    try {
        // Restrict max log size to avoid sending enormous logs over email.
        // Interested users can always look at the log on the web server.
        List<String> lines = build.getLog(MAX_LOG_LINES);
        String workspaceUrl = null, artifactUrl = null;
        Pattern wsPattern = null;
        String baseUrl = Mailer.descriptor().getUrl();
        if (baseUrl != null) {
            // Hyperlink local file paths to the repository workspace or build artifacts.
            // Note that it is possible for a failure mail to refer to a file using a workspace
            // URL which has already been corrected in a subsequent build. To fix, archive.
            workspaceUrl = baseUrl + Util.encode(build.getProject().getUrl()) + "ws/";
            artifactUrl = baseUrl + Util.encode(build.getUrl()) + "artifact/";
            FilePath ws = build.getWorkspace();
            // Match either file or URL patterns, i.e. either
            // c:\hudson\workdir\jobs\foo\workspace\src\Foo.java
            // file:/c:/hudson/workdir/jobs/foo/workspace/src/Foo.java
            // will be mapped to one of:
            // http://host/hudson/job/foo/ws/src/Foo.java
            // http://host/hudson/job/foo/123/artifact/src/Foo.java
            // Careful with path separator between $1 and $2:
            // workspaceDir will not normally end with one;
            // workspaceDir.toURI() will end with '/' if and only if workspaceDir.exists() at time of call
            wsPattern = Pattern.compile("(" + Pattern.quote(ws.getRemote()) + "|" + Pattern.quote(ws.toURI().toString()) + ")[/\\\\]?([^:#\\s]*)");
        }
        for (String line : lines) {
            line = line.replace('\0', // shall we replace other control code? This one is motivated by http://www.nabble.com/Problems-with-NULL-characters-in-generated-output-td25005177.html
            ' ');
            if (wsPattern != null) {
                // Perl: $line =~ s{$rx}{$path = $2; $path =~ s!\\\\!/!g; $workspaceUrl . $path}eg;
                Matcher m = wsPattern.matcher(line);
                int pos = 0;
                while (m.find(pos)) {
                    String path = m.group(2).replace(File.separatorChar, '/');
                    String linkUrl = artifactMatches(path, build) ? artifactUrl : workspaceUrl;
                    String prefix = line.substring(0, m.start()) + '<' + linkUrl + Util.encode(path) + '>';
                    pos = prefix.length();
                    line = prefix + line.substring(m.end());
                    // XXX better style to reuse Matcher and fix offsets, but more work
                    m = wsPattern.matcher(line);
                }
            }
            buf.append(line);
            buf.append('\n');
        }
    } catch (IOException e) {
        // somehow failed to read the contents of the log
        buf.append(Messages.MailSender_FailureMail_FailedToAccessBuildLog()).append("\n\n").append(Functions.printThrowable(e));
    }
    appendFooter(buf);
    msg.setText(buf.toString(), getCharset());
    return msg;
}
Also used : FilePath(hudson.FilePath) Pattern(java.util.regex.Pattern) ChangeLogSet(hudson.scm.ChangeLogSet) MimeMessage(javax.mail.internet.MimeMessage) Matcher(java.util.regex.Matcher) IOException(java.io.IOException)

Example 28 with FilePath

use of hudson.FilePath in project hudson-2.x by hudson.

the class WorkspaceList method allocate.

/**
     * Allocates a workspace by adding some variation to the given base to make it unique.
     */
public synchronized Lease allocate(FilePath base) throws InterruptedException {
    for (int i = 1; ; i++) {
        //Workspace suffix was changed from @ to _, because of some issues with SCMs.
        //see http://issues.hudson-ci.org/browse/HUDSON-4791
        FilePath candidate = i == 1 ? base : base.withSuffix(WORKSPACE_NAME_SUFFIX + i);
        Entry e = inUse.get(candidate);
        if (e != null && !e.quick)
            continue;
        return acquire(candidate);
    }
}
Also used : FilePath(hudson.FilePath)

Example 29 with FilePath

use of hudson.FilePath 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;
    }
}
Also used : FilePath(hudson.FilePath) AntConsoleAnnotator(hudson.tasks._ant.AntConsoleAnnotator) ArrayList(java.util.ArrayList) IOException(java.io.IOException) EnvVars(hudson.EnvVars) ArgumentListBuilder(hudson.util.ArgumentListBuilder)

Example 30 with FilePath

use of hudson.FilePath in project hudson-2.x by hudson.

the class ArtifactArchiver method perform.

@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException {
    if (artifacts.length() == 0) {
        listener.error(Messages.ArtifactArchiver_NoIncludes());
        build.setResult(Result.FAILURE);
        return true;
    }
    File dir = build.getArtifactsDir();
    dir.mkdirs();
    listener.getLogger().println(Messages.ArtifactArchiver_ARCHIVING_ARTIFACTS());
    try {
        FilePath ws = build.getWorkspace();
        if (ws == null) {
            // #3330: slave down?
            return true;
        }
        String artifacts = build.getEnvironment(listener).expand(this.artifacts);
        if (ws.copyRecursiveTo(artifacts, excludes, new FilePath(dir), compressionType) == 0) {
            if (build.getResult().isBetterOrEqualTo(Result.UNSTABLE)) {
                // If the build failed, don't complain that there was no matching artifact.
                // The build probably didn't even get to the point where it produces artifacts.
                listenerWarnOrError(listener, Messages.ArtifactArchiver_NoMatchFound(artifacts));
                String msg = null;
                try {
                    msg = ws.validateAntFileMask(artifacts);
                } catch (Exception e) {
                    listenerWarnOrError(listener, e.getMessage());
                }
                if (msg != null) {
                    listenerWarnOrError(listener, msg);
                }
            }
            if (!allowEmptyArchive) {
                build.setResult(Result.FAILURE);
            }
            return true;
        }
    } catch (IOException e) {
        Util.displayIOException(e, listener);
        e.printStackTrace(listener.error(Messages.ArtifactArchiver_FailedToArchive(artifacts)));
        build.setResult(Result.FAILURE);
        return true;
    }
    return true;
}
Also used : FilePath(hudson.FilePath) IOException(java.io.IOException) File(java.io.File) IOException(java.io.IOException)

Aggregations

FilePath (hudson.FilePath)39 IOException (java.io.IOException)17 File (java.io.File)12 URL (java.net.URL)5 EnvVars (hudson.EnvVars)4 List (java.util.List)4 AbortException (hudson.AbortException)3 Launcher (hudson.Launcher)3 PrintStream (java.io.PrintStream)3 ImmutableList (com.google.common.collect.ImmutableList)2 BuildListener (hudson.model.BuildListener)2 VirtualChannel (hudson.remoting.VirtualChannel)2 NullSCM (hudson.scm.NullSCM)2 SCM (hudson.scm.SCM)2 WorkspaceList (hudson.slaves.WorkspaceList)2 ArgumentListBuilder (hudson.util.ArgumentListBuilder)2 ArrayList (java.util.ArrayList)2 HashSet (java.util.HashSet)2 ImmutableMap (com.google.common.collect.ImmutableMap)1 WindowsSlaveInstaller (hudson.lifecycle.WindowsSlaveInstaller)1