Search in sources :

Example 1 with TopLevelItem

use of hudson.model.TopLevelItem 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 TopLevelItem

use of hudson.model.TopLevelItem in project configuration-as-code-plugin by jenkinsci.

the class TopLevelItemConfigurator method configure.

@Override
public TopLevelItem configure(Object c) throws Exception {
    Map config = (Map) c;
    final Jenkins jenkins = Jenkins.getInstance();
    final TopLevelItemDescriptor descriptor = (TopLevelItemDescriptor) jenkins.getDescriptorOrDie(target);
    final String name = (String) config.remove("name");
    final TopLevelItem item = descriptor.newInstance(jenkins, name);
    configure(config, item);
    return item;
}
Also used : Jenkins(jenkins.model.Jenkins) TopLevelItem(hudson.model.TopLevelItem) TopLevelItemDescriptor(hudson.model.TopLevelItemDescriptor) Map(java.util.Map)

Example 3 with TopLevelItem

use of hudson.model.TopLevelItem in project promoted-builds-plugin by jenkinsci.

the class PromotionsDslContextExtensionTest method testShouldGenerateTheJobWithBuildWrappers.

@Test
public void testShouldGenerateTheJobWithBuildWrappers() throws Exception {
    // Given
    String dsl = FileUtils.readFileToString(new File("src/test/resources/buildwrapper-example-dsl.groovy"));
    System.out.println(dsl);
    FreeStyleProject seedJob = j.createFreeStyleProject();
    seedJob.getBuildersList().add(createScript(dsl));
    // When
    QueueTaskFuture<FreeStyleBuild> scheduleBuild2 = seedJob.scheduleBuild2(0);
    // Then (unstable b/c we aren't including the Timestamper dependency)
    j.assertBuildStatus(Result.UNSTABLE, scheduleBuild2.get());
    TopLevelItem item = j.jenkins.getItem("build-wrapper-test");
    assertNotNull(item);
    File config = new File(item.getRootDir(), "promotions/build-wrapper-promotion/config.xml");
    String content = Files.toString(config, Charset.forName("UTF-8"));
    assertTrue(Pattern.compile("<buildWrappers>\\s+<hudson\\.plugins\\.timestamper\\.TimestamperBuildWrapper/>\\s+</buildWrappers>").matcher(content).find());
}
Also used : TopLevelItem(hudson.model.TopLevelItem) FreeStyleBuild(hudson.model.FreeStyleBuild) FreeStyleProject(hudson.model.FreeStyleProject) File(java.io.File) Test(org.junit.Test)

Example 4 with TopLevelItem

use of hudson.model.TopLevelItem in project hudson-2.x by hudson.

the class Functions method getRelativeLinkTo.

/**
 * Computes the relative path from the current page to the given item.
 */
public static String getRelativeLinkTo(Item p) {
    Map<Object, String> ancestors = new HashMap<Object, String>();
    View view = null;
    StaplerRequest request = Stapler.getCurrentRequest();
    for (Ancestor a : request.getAncestors()) {
        ancestors.put(a.getObject(), a.getRelativePath());
        if (a.getObject() instanceof View)
            view = (View) a.getObject();
    }
    String path = ancestors.get(p);
    if (path != null)
        return path;
    Item i = p;
    String url = "";
    while (true) {
        ItemGroup ig = i.getParent();
        url = i.getShortUrl() + url;
        if (ig == Hudson.getInstance()) {
            assert i instanceof TopLevelItem;
            if (view != null && view.contains((TopLevelItem) i)) {
                // if p and the current page belongs to the same view, then return a relative path
                return ancestors.get(view) + '/' + url;
            } else {
                // otherwise return a path from the root Hudson
                return request.getContextPath() + '/' + p.getUrl();
            }
        }
        path = ancestors.get(ig);
        if (path != null)
            return path + '/' + url;
        // if not, ig must have been the Hudson instance
        assert ig instanceof Item;
        i = (Item) ig;
    }
}
Also used : Item(hudson.model.Item) TopLevelItem(hudson.model.TopLevelItem) ItemGroup(hudson.model.ItemGroup) HashMap(java.util.HashMap) StaplerRequest(org.kohsuke.stapler.StaplerRequest) TopLevelItem(hudson.model.TopLevelItem) SearchableModelObject(hudson.search.SearchableModelObject) ModelObject(hudson.model.ModelObject) View(hudson.model.View) Ancestor(org.kohsuke.stapler.Ancestor)

Example 5 with TopLevelItem

use of hudson.model.TopLevelItem in project hudson-2.x by hudson.

the class ProjectServiceImplTest method createProjectFromXMLSecurity.

@Test
public void createProjectFromXMLSecurity() throws IOException {
    // mocks
    TopLevelItem toProject = Mockito.mock(TopLevelItem.class);
    ProjectService inst = spy(getInst());
    // make method succeed
    doReturn(false).when(inst).projectExists("toProject");
    when(hudson.createProjectFromXML("toProject", input)).thenReturn(toProject);
    assertThat(inst.createProjectFromXML("toProject", input), equalTo(toProject));
    Mockito.verify(securityService).checkPermission(Item.CREATE);
}
Also used : TopLevelItem(hudson.model.TopLevelItem) ProjectService(org.hudsonci.service.ProjectService) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

TopLevelItem (hudson.model.TopLevelItem)16 Test (org.junit.Test)5 File (java.io.File)3 IOException (java.io.IOException)3 Map (java.util.Map)3 OrganizationFolder (jenkins.branch.OrganizationFolder)3 Jenkins (jenkins.model.Jenkins)3 WorkflowMultiBranchProject (org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject)3 Domain (com.cloudbees.plugins.credentials.domains.Domain)2 Cause (hudson.model.Cause)2 FreeStyleBuild (hudson.model.FreeStyleBuild)2 FreeStyleProject (hudson.model.FreeStyleProject)2 Hudson (hudson.model.Hudson)2 Item (hudson.model.Item)2 User (hudson.model.User)2 ErrorMessage (io.jenkins.blueocean.commons.ErrorMessage)2 ServiceException (io.jenkins.blueocean.commons.ServiceException)2 BlueOceanCredentialsProvider (io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanCredentialsProvider)2 BlueOceanDomainRequirement (io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement)2 ConfiguredWithCode (org.jenkinsci.plugins.casc.misc.ConfiguredWithCode)2