Search in sources :

Example 1 with AbortException

use of hudson.AbortException in project workflow-cps-plugin by jenkinsci.

the class CpsScmFlowDefinition method create.

@Override
public CpsFlowExecution create(FlowExecutionOwner owner, TaskListener listener, List<? extends Action> actions) throws Exception {
    for (Action a : actions) {
        if (a instanceof CpsFlowFactoryAction2) {
            return ((CpsFlowFactoryAction2) a).create(this, owner, actions);
        }
    }
    Queue.Executable _build = owner.getExecutable();
    if (!(_build instanceof Run)) {
        throw new IOException("can only check out SCM into a Run");
    }
    Run<?, ?> build = (Run<?, ?>) _build;
    if (isLightweight()) {
        try (SCMFileSystem fs = SCMFileSystem.of(build.getParent(), scm)) {
            if (fs != null) {
                String script = fs.child(scriptPath).contentAsString();
                listener.getLogger().println("Obtained " + scriptPath + " from " + scm.getKey());
                Queue.Executable exec = owner.getExecutable();
                FlowDurabilityHint hint = (exec instanceof Item) ? DurabilityHintProvider.suggestedFor((Item) exec) : GlobalDefaultFlowDurabilityLevel.getDefaultDurabilityHint();
                return new CpsFlowExecution(script, true, owner, hint);
            } else {
                listener.getLogger().println("Lightweight checkout support not available, falling back to full checkout.");
            }
        }
    }
    FilePath dir;
    Node node = Jenkins.getActiveInstance();
    if (build.getParent() instanceof TopLevelItem) {
        FilePath baseWorkspace = node.getWorkspaceFor((TopLevelItem) build.getParent());
        if (baseWorkspace == null) {
            throw new IOException(node.getDisplayName() + " may be offline");
        }
        dir = getFilePathWithSuffix(baseWorkspace);
    } else {
        // should not happen, but just in case:
        dir = new FilePath(owner.getRootDir());
    }
    listener.getLogger().println("Checking out " + scm.getKey() + " into " + dir + " to read " + scriptPath);
    String script = null;
    Computer computer = node.toComputer();
    if (computer == null) {
        throw new IOException(node.getDisplayName() + " may be offline");
    }
    SCMStep delegate = new GenericSCMStep(scm);
    delegate.setPoll(true);
    delegate.setChangelog(true);
    FilePath acquiredDir;
    try (WorkspaceList.Lease lease = computer.getWorkspaceList().acquire(dir)) {
        for (int retryCount = Jenkins.getInstance().getScmCheckoutRetryCount(); retryCount >= 0; retryCount--) {
            try {
                delegate.checkout(build, dir, listener, node.createLauncher(listener));
                break;
            } catch (AbortException e) {
                // If so, just skip echoing it.
                if (e.getMessage() != null) {
                    listener.error(e.getMessage());
                }
            } catch (InterruptedIOException e) {
                throw e;
            } catch (IOException e) {
                // checkout error not yet reported
                // TODO 2.43+ use Functions.printStackTrace
                listener.error("Checkout failed").println(Functions.printThrowable(e).trim());
            }
            if (// all attempts failed
            retryCount == 0)
                throw new AbortException("Maximum checkout retry attempts reached, aborting");
            listener.getLogger().println("Retrying after 10 seconds");
            Thread.sleep(10000);
        }
        FilePath scriptFile = dir.child(scriptPath);
        if (!scriptFile.absolutize().getRemote().replace('\\', '/').startsWith(dir.absolutize().getRemote().replace('\\', '/') + '/')) {
            // TODO JENKINS-26838
            throw new IOException(scriptFile + " is not inside " + dir);
        }
        if (!scriptFile.exists()) {
            throw new AbortException(scriptFile + " not found");
        }
        script = scriptFile.readToString();
        acquiredDir = lease.path;
    }
    Queue.Executable queueExec = owner.getExecutable();
    FlowDurabilityHint hint = (queueExec instanceof Run) ? DurabilityHintProvider.suggestedFor(((Run) queueExec).getParent()) : GlobalDefaultFlowDurabilityLevel.getDefaultDurabilityHint();
    CpsFlowExecution exec = new CpsFlowExecution(script, true, owner, hint);
    exec.flowStartNodeActions.add(new WorkspaceActionImpl(acquiredDir, null));
    return exec;
}
Also used : FilePath(hudson.FilePath) InterruptedIOException(java.io.InterruptedIOException) Action(hudson.model.Action) Node(hudson.model.Node) TopLevelItem(hudson.model.TopLevelItem) Run(hudson.model.Run) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) WorkspaceList(hudson.slaves.WorkspaceList) FlowDurabilityHint(org.jenkinsci.plugins.workflow.flow.FlowDurabilityHint) GenericSCMStep(org.jenkinsci.plugins.workflow.steps.scm.GenericSCMStep) FlowDurabilityHint(org.jenkinsci.plugins.workflow.flow.FlowDurabilityHint) TopLevelItem(hudson.model.TopLevelItem) Item(hudson.model.Item) WorkspaceActionImpl(org.jenkinsci.plugins.workflow.support.actions.WorkspaceActionImpl) SCMFileSystem(jenkins.scm.api.SCMFileSystem) GenericSCMStep(org.jenkinsci.plugins.workflow.steps.scm.GenericSCMStep) SCMStep(org.jenkinsci.plugins.workflow.steps.scm.SCMStep) Computer(hudson.model.Computer) Queue(hudson.model.Queue) AbortException(hudson.AbortException)

Example 2 with AbortException

use of hudson.AbortException in project artifact-manager-s3-plugin by jenkinsci.

the class JCloudsArtifactManager method copyAllArtifactsAndStashes.

@Override
public void copyAllArtifactsAndStashes(Run<?, ?> to, TaskListener listener) throws IOException, InterruptedException {
    ArtifactManager am = to.pickArtifactManager();
    if (!(am instanceof JCloudsArtifactManager)) {
        throw new AbortException("Cannot copy artifacts and stashes to " + to + " using " + am.getClass().getName());
    }
    JCloudsArtifactManager dest = (JCloudsArtifactManager) am;
    String prefix = getBlobPath("", PREFIX, key, id);
    BlobStore blobStore = getContext(BLOB_CONTAINER).getBlobStore();
    Iterator<StorageMetadata> it = new JCloudsBlobStore.PageSetIterable(blobStore, BLOB_CONTAINER, ListContainerOptions.Builder.prefix(prefix).recursive());
    while (it.hasNext()) {
        StorageMetadata sm = it.next();
        String path = sm.getName();
        assert path.startsWith(prefix);
        String destPath = getBlobPath(path.substring(prefix.length()), PREFIX, dest.key, dest.id);
        LOGGER.fine("copying " + path + " to " + destPath);
        blobStore.copyBlob(BLOB_CONTAINER, path, BLOB_CONTAINER, destPath, CopyOptions.NONE);
    }
// TODO print some summary to listener
}
Also used : StorageMetadata(org.jclouds.blobstore.domain.StorageMetadata) ArtifactManager(jenkins.model.ArtifactManager) BlobStore(org.jclouds.blobstore.BlobStore) AbortException(hudson.AbortException)

Example 3 with AbortException

use of hudson.AbortException in project nodejs-plugin by jenkinsci.

the class NodeJSCommandInterpreter method perform.

/*
     * (non-Javadoc)
     * @see hudson.tasks.CommandInterpreter#perform(hudson.model.AbstractBuild, hudson.Launcher, hudson.model.TaskListener)
     */
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, TaskListener listener) throws InterruptedException {
    try {
        EnvVars env = build.getEnvironment(listener);
        EnvVars newEnv = new EnvVars();
        // get specific installation for the node
        NodeJSInstallation ni = getNodeJS();
        if (ni == null) {
            if (nodeJSInstallationName != null) {
                throw new AbortException(Messages.NodeJSBuilders_noInstallationFound(nodeJSInstallationName));
            }
            // use system NodeJS if any, in case let fails later
            nodeExec = (launcher.isUnix() ? Platform.LINUX : Platform.WINDOWS).nodeFileName;
        } else {
            Node node = build.getBuiltOn();
            if (node == null) {
                throw new AbortException(Messages.NodeJSBuilders_nodeOffline());
            }
            ni = ni.forNode(node, listener);
            ni = ni.forEnvironment(env);
            String exec = ni.getExecutable(launcher);
            if (exec == null) {
                listener.fatalError(Messages.NodeJSBuilders_noExecutableFound(ni.getHome()));
                return false;
            }
            ni.buildEnvVars(newEnv);
            // enhance env with installation environment because is passed to supplyConfig
            env.overrideAll(newEnv);
            nodeExec = ni.getExecutable(launcher);
            if (nodeExec == null) {
                throw new AbortException(Messages.NodeJSBuilders_noExecutableFound(ni.getHome()));
            }
        }
        if (configId != null) {
            // add npmrc config
            ConfigFile cf = new ConfigFile(configId, null, true);
            FilePath configFile = ConfigFileManager.provisionConfigFile(cf, env, build, build.getWorkspace(), listener, new ArrayList<String>());
            newEnv.put(NodeJSConstants.NPM_USERCONFIG, configFile.getRemote());
            build.addAction(new CleanTempFilesAction(configFile.getRemote()));
        }
        // add an Environment so when the in super class is called build.getEnviroment() gets the enhanced env
        build.getEnvironments().add(Environment.create(newEnv));
    } catch (AbortException e) {
        // NOSONAR
        listener.fatalError(e.getMessage());
        return false;
    } catch (IOException e) {
        Util.displayIOException(e, listener);
        e.printStackTrace(listener.fatalError(hudson.tasks.Messages.CommandInterpreter_CommandFailed()));
    }
    return internalPerform(build, launcher, listener);
}
Also used : NodeJSInstallation(jenkins.plugins.nodejs.tools.NodeJSInstallation) FilePath(hudson.FilePath) EnvVars(hudson.EnvVars) ConfigFile(org.jenkinsci.lib.configprovider.model.ConfigFile) CleanTempFilesAction(org.jenkinsci.plugins.configfiles.common.CleanTempFilesAction) Node(hudson.model.Node) IOException(java.io.IOException) AbortException(hudson.AbortException)

Example 4 with AbortException

use of hudson.AbortException in project workflow-job-plugin by jenkinsci.

the class WorkflowRunTest method culprits.

@Test
@Issue("JENKINS-24141")
public void culprits() throws Exception {
    WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition("import org.jvnet.hudson.test.FakeChangeLogSCM\n" + "semaphore 'waitFirst'\n" + "def testScm = new FakeChangeLogSCM()\n" + "testScm.addChange().withAuthor(/alice$BUILD_NUMBER/)\n" + "node {\n" + "    checkout(testScm)\n" + "    semaphore 'waitSecond'\n" + "    def secondScm = new FakeChangeLogSCM()\n" + "    secondScm.addChange().withAuthor(/bob$BUILD_NUMBER/)\n" + "    checkout(secondScm)\n" + "    semaphore 'waitThird'\n" + "    def thirdScm = new FakeChangeLogSCM()\n" + "    thirdScm.addChange().withAuthor(/charlie$BUILD_NUMBER/)\n" + "    checkout(thirdScm)\n" + "}\n", false));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    SemaphoreStep.waitForStart("waitFirst/1", b1);
    assertTrue(b1.getCulpritIds().isEmpty());
    SemaphoreStep.success("waitFirst/1", null);
    SemaphoreStep.waitForStart("waitSecond/1", b1);
    assertCulprits(b1, "alice1");
    SemaphoreStep.success("waitSecond/1", null);
    SemaphoreStep.waitForStart("waitThird/1", b1);
    assertCulprits(b1, "alice1", "bob1");
    SemaphoreStep.failure("waitThird/1", new AbortException());
    r.assertBuildStatus(Result.FAILURE, r.waitForCompletion(b1));
    WorkflowRun b2 = p.scheduleBuild2(0).waitForStart();
    SemaphoreStep.waitForStart("waitFirst/2", b2);
    assertCulprits(b2, "alice1", "bob1");
    SemaphoreStep.success("waitFirst/2", null);
    SemaphoreStep.waitForStart("waitSecond/2", b2);
    assertCulprits(b2, "alice1", "bob1", "alice2");
    SemaphoreStep.success("waitSecond/2", null);
    SemaphoreStep.waitForStart("waitThird/2", b2);
    assertCulprits(b2, "alice1", "bob1", "alice2", "bob2");
    SemaphoreStep.success("waitThird/2", b2);
    r.assertBuildStatusSuccess(r.waitForCompletion(b2));
    assertCulprits(b2, "alice1", "bob1", "alice2", "bob2", "charlie2");
}
Also used : CpsFlowDefinition(org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition) AbortException(hudson.AbortException) Issue(org.jvnet.hudson.test.Issue) Test(org.junit.Test)

Example 5 with AbortException

use of hudson.AbortException in project workflow-job-plugin by jenkinsci.

the class WorkflowJob method poll.

@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "TODO 1.653+ switch to Jenkins.getInstanceOrNull")
@Override
public PollingResult poll(TaskListener listener) {
    if (!isBuildable()) {
        listener.getLogger().println("Build disabled");
        return PollingResult.NO_CHANGES;
    }
    // TODO 2.11+ call SCMDecisionHandler
    // TODO call SCMPollListener
    WorkflowRun lastBuild = getLastBuild();
    if (lastBuild == null) {
        listener.getLogger().println("no previous build to compare to");
        // Note that we have no equivalent of AbstractProject.NoSCM because without an initial build we do not know if this project has any SCM at all.
        return Queue.getInstance().contains(this) ? PollingResult.NO_CHANGES : PollingResult.BUILD_NOW;
    }
    WorkflowRun perhapsCompleteBuild = getLastSuccessfulBuild();
    if (perhapsCompleteBuild == null) {
        perhapsCompleteBuild = lastBuild;
    }
    if (pollingBaselines == null) {
        pollingBaselines = new ConcurrentHashMap<>();
    }
    PollingResult result = PollingResult.NO_CHANGES;
    for (WorkflowRun.SCMCheckout co : perhapsCompleteBuild.checkouts(listener)) {
        if (!co.scm.supportsPolling()) {
            listener.getLogger().println("polling not supported from " + co.workspace + " on " + co.node);
            continue;
        }
        String key = co.scm.getKey();
        SCMRevisionState pollingBaseline = pollingBaselines.get(key);
        if (pollingBaseline == null) {
            // after a restart, transient cache will be empty
            pollingBaseline = co.pollingBaseline;
        }
        if (pollingBaseline == null) {
            listener.getLogger().println("no polling baseline in " + co.workspace + " on " + co.node);
            continue;
        }
        try {
            FilePath workspace;
            Launcher launcher;
            WorkspaceList.Lease lease;
            if (co.scm.requiresWorkspaceForPolling()) {
                Jenkins j = Jenkins.getInstance();
                if (j == null) {
                    listener.error("Jenkins is shutting down");
                    continue;
                }
                Computer c = j.getComputer(co.node);
                if (c == null) {
                    listener.error("no such computer " + co.node);
                    continue;
                }
                workspace = new FilePath(c.getChannel(), co.workspace);
                launcher = workspace.createLauncher(listener).decorateByEnv(getEnvironment(c.getNode(), listener));
                lease = c.getWorkspaceList().acquire(workspace, !isConcurrentBuild());
            } else {
                workspace = null;
                launcher = null;
                lease = null;
            }
            PollingResult r;
            try {
                r = co.scm.compareRemoteRevisionWith(this, launcher, workspace, listener, pollingBaseline);
                if (r.remote != null) {
                    pollingBaselines.put(key, r.remote);
                }
            } finally {
                if (lease != null) {
                    lease.release();
                }
            }
            if (r.change.compareTo(result.change) > 0) {
                // note that if we are using >1 checkout, we can clobber baseline/remote here; anyway SCMTrigger only calls hasChanges()
                result = r;
            }
        } catch (AbortException x) {
            listener.error("polling failed in " + co.workspace + " on " + co.node + ": " + x.getMessage());
        } catch (Exception x) {
            // TODO 2.43+ use Functions.printStackTrace
            listener.error("polling failed in " + co.workspace + " on " + co.node).println(Functions.printThrowable(x).trim());
        }
    }
    return result;
}
Also used : FilePath(hudson.FilePath) WorkspaceList(hudson.slaves.WorkspaceList) ServletException(javax.servlet.ServletException) AbortException(hudson.AbortException) IOException(java.io.IOException) Jenkins(jenkins.model.Jenkins) SCMRevisionState(hudson.scm.SCMRevisionState) PollingResult(hudson.scm.PollingResult) Computer(hudson.model.Computer) Launcher(hudson.Launcher) AbortException(hudson.AbortException) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Aggregations

AbortException (hudson.AbortException)37 IOException (java.io.IOException)13 FilePath (hudson.FilePath)11 EnvVars (hudson.EnvVars)5 ArrayList (java.util.ArrayList)5 Node (hudson.model.Node)4 ArgumentListBuilder (hudson.util.ArgumentListBuilder)4 Launcher (hudson.Launcher)3 Computer (hudson.model.Computer)3 Run (hudson.model.Run)3 WorkspaceList (hudson.slaves.WorkspaceList)3 ServletException (javax.servlet.ServletException)3 StandardCredentials (com.cloudbees.plugins.credentials.common.StandardCredentials)2 AbstractBuild (hudson.model.AbstractBuild)2 ParameterDefinition (hudson.model.ParameterDefinition)2 ParameterValue (hudson.model.ParameterValue)2 PollingResult (hudson.scm.PollingResult)2 SCMRevisionState (hudson.scm.SCMRevisionState)2 File (java.io.File)2 Authentication (org.acegisecurity.Authentication)2