Search in sources :

Example 21 with Jenkins

use of jenkins.model.Jenkins in project promoted-builds-plugin by jenkinsci.

the class PromotedBuildParameterDefinition method getRuns.

/**
 * Gets a list of promoted builds for the project.
 * @param base Base item for the relative addressing
 * @return List of {@link AbstractBuild}s, which have been promoted.
 *         May return an empty list if {@link Jenkins} instance is not ready
 * @since 2.22
 */
@Nonnull
public List<Run<?, ?>> getRuns(@CheckForNull Item base) {
    final List<Run<?, ?>> runs = new ArrayList<Run<?, ?>>();
    final Jenkins jenkins = Jenkins.getInstanceOrNull();
    if (jenkins == null) {
        return runs;
    }
    // JENKINS-25011: also look for jobs in folders.
    final AbstractProject<?, ?> job = ItemPathResolver.getByPath(projectName, base, AbstractProject.class);
    if (job == null) {
        return runs;
    }
    PromotedProjectAction promotedProjectAction = job.getAction(PromotedProjectAction.class);
    if (promotedProjectAction == null) {
        return runs;
    }
    for (Run<?, ?> run : job.getBuilds()) {
        List<PromotedBuildAction> actions = run.getActions(PromotedBuildAction.class);
        for (PromotedBuildAction buildAction : actions) {
            if (buildAction.contains(promotionProcessName)) {
                runs.add(run);
                break;
            }
        }
    }
    return runs;
}
Also used : Jenkins(jenkins.model.Jenkins) PromotedProjectAction(hudson.plugins.promoted_builds.PromotedProjectAction) ArrayList(java.util.ArrayList) Run(hudson.model.Run) PromotedBuildAction(hudson.plugins.promoted_builds.PromotedBuildAction) Nonnull(javax.annotation.Nonnull)

Example 22 with Jenkins

use of jenkins.model.Jenkins in project blueocean-plugin by jenkinsci.

the class BlueOceanConfigStatePreloader method getStateJson.

/**
 * {@inheritDoc}
 */
@Override
public String getStateJson() {
    StringWriter writer = new StringWriter();
    Jenkins jenkins = Jenkins.get();
    VersionNumber versionNumber = Jenkins.getVersion();
    String version = versionNumber != null ? versionNumber.toString() : Jenkins.VERSION;
    AuthorizationStrategy authorizationStrategy = jenkins.getAuthorizationStrategy();
    boolean allowAnonymousRead = true;
    if (authorizationStrategy instanceof FullControlOnceLoggedInAuthorizationStrategy) {
        allowAnonymousRead = ((FullControlOnceLoggedInAuthorizationStrategy) authorizationStrategy).isAllowAnonymousRead();
    }
    String jwtTokenEndpointHostUrl = Jenkins.get().getRootUrl();
    JwtTokenServiceEndpoint jwtTokenServiceEndpoint = JwtTokenServiceEndpoint.first();
    if (jwtTokenServiceEndpoint != null) {
        jwtTokenEndpointHostUrl = jwtTokenServiceEndpoint.getHostUrl();
    }
    addFeatures(new JSONBuilder(writer).object().key("version").value(getBlueOceanPluginVersion()).key("jenkinsConfig").object().key("analytics").value(Analytics.isAnalyticsEnabled()).key("version").value(version).key("security").object().key("enabled").value(jenkins.isUseSecurity()).key("loginUrl").value(jenkins.getSecurityRealm() == SecurityRealm.NO_AUTHENTICATION ? null : jenkins.getSecurityRealm().getLoginUrl()).key("authorizationStrategy").object().key("allowAnonymousRead").value(allowAnonymousRead).endObject().key("enableJWT").value(BlueOceanConfigProperties.BLUEOCEAN_FEATURE_JWT_AUTHENTICATION).key("jwtServiceHostUrl").value(jwtTokenEndpointHostUrl).endObject().endObject()).endObject();
    return writer.toString();
}
Also used : Jenkins(jenkins.model.Jenkins) FullControlOnceLoggedInAuthorizationStrategy(hudson.security.FullControlOnceLoggedInAuthorizationStrategy) AuthorizationStrategy(hudson.security.AuthorizationStrategy) JwtTokenServiceEndpoint(io.jenkins.blueocean.auth.jwt.JwtTokenServiceEndpoint) FullControlOnceLoggedInAuthorizationStrategy(hudson.security.FullControlOnceLoggedInAuthorizationStrategy) JSONBuilder(net.sf.json.util.JSONBuilder) StringWriter(java.io.StringWriter) VersionNumber(hudson.util.VersionNumber)

Example 23 with Jenkins

use of jenkins.model.Jenkins in project blueocean-plugin by jenkinsci.

the class PipelineBranchRunStatePreloader method getFetchData.

@Override
protected FetchData getFetchData(@NonNull BlueUrlTokenizer blueUrl) {
    // 
    if (!blueUrl.hasPart(BlueUrlTokenizer.UrlPart.BRANCH) || !blueUrl.hasPart(BlueUrlTokenizer.UrlPart.PIPELINE_RUN_DETAIL_ID)) {
        // Not interested in it
        return null;
    }
    Jenkins jenkins = Jenkins.get();
    String pipelineFullName = blueUrl.getPart(BlueUrlTokenizer.UrlPart.PIPELINE);
    String branchName = blueUrl.getPart(BlueUrlTokenizer.UrlPart.BRANCH);
    String runId = blueUrl.getPart(BlueUrlTokenizer.UrlPart.PIPELINE_RUN_DETAIL_ID);
    Item pipelineJobItem = jenkins.getItemByFullName(pipelineFullName);
    if (pipelineJobItem instanceof MultiBranchProject) {
        try {
            MultiBranchProject pipelineMBP = (MultiBranchProject) pipelineJobItem;
            Job pipelineBranchJob = pipelineMBP.getItem(branchName);
            if (pipelineBranchJob != null) {
                Run run = pipelineBranchJob.getBuild(runId);
                if (run != null) {
                    BlueRun blueRun = BlueRunFactory.getRun(run, BluePipelineFactory.resolve(pipelineBranchJob));
                    if (blueRun != null) {
                        try {
                            return new FetchData(blueRun.getLink().getHref(), Export.toJson(blueRun));
                        } catch (IOException e) {
                            LOGGER.log(Level.FINE, String.format("Unable to preload run for pipeline '%s'. Run serialization error.", run.getUrl()), e);
                            return null;
                        }
                    } else {
                        LOGGER.log(Level.FINE, String.format("Unable to find run %s on branch named %s on pipeline named '%s'.", runId, branchName, pipelineFullName));
                        return null;
                    }
                }
            } else {
                LOGGER.log(Level.FINE, String.format("Unable to find branch named %s on pipeline named '%s'.", branchName, pipelineFullName));
                return null;
            }
        } catch (Exception e) {
            LOGGER.log(Level.FINE, String.format("Unable to find run from pipeline named '%s'.", pipelineFullName), e);
            return null;
        }
    } else {
        LOGGER.log(Level.FINE, String.format("Unable to find pipeline named '%s'.", pipelineFullName));
        return null;
    }
    // Don't preload any data on the page.
    return null;
}
Also used : Jenkins(jenkins.model.Jenkins) Item(hudson.model.Item) BlueRun(io.jenkins.blueocean.rest.model.BlueRun) MultiBranchProject(jenkins.branch.MultiBranchProject) BlueRun(io.jenkins.blueocean.rest.model.BlueRun) Run(hudson.model.Run) IOException(java.io.IOException) Job(hudson.model.Job) IOException(java.io.IOException)

Example 24 with Jenkins

use of jenkins.model.Jenkins in project blueocean-plugin by jenkinsci.

the class PipelineNodeTest method sequentialParallelStagesWithPost.

@Test
@Issue("JENKINS-49779")
public void sequentialParallelStagesWithPost() throws Exception {
    WorkflowJob p = createWorkflowJobWithJenkinsfile(getClass(), "sequentialParallelWithPost.jenkinsfile");
    Slave s = j.createOnlineSlave();
    s.setNumExecutors(2);
    // Run until completed
    j.buildAndAssertSuccess(p);
    List<Map> nodes = get("/organizations/jenkins/pipelines/" + p.getName() + "/runs/1/nodes/", List.class);
    assertEquals(9, nodes.size());
    Optional<Map> thirdSeqStage = nodes.stream().filter(map -> map.get("displayName").equals("third-sequential-stage")).findFirst();
    assertTrue(thirdSeqStage.isPresent());
    List<Map> steps = get("/organizations/jenkins/pipelines/" + p.getName() + "/runs/1/nodes/" + thirdSeqStage.get().get("id") + "/steps/", List.class);
    assertEquals(2, steps.size());
    assertEquals("echo 'dummy text third-sequential-stage'", steps.get(0).get("displayDescription"));
    assertEquals("echo 'dummy text post multiple-stages'", steps.get(1).get("displayDescription"));
}
Also used : CpsFlowDefinition(org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition) Arrays(java.util.Arrays) CoreMatchers.hasItem(org.hamcrest.CoreMatchers.hasItem) Issue(org.jvnet.hudson.test.Issue) QueueTaskFuture(hudson.model.queue.QueueTaskFuture) URL(java.net.URL) InputAction(org.jenkinsci.plugins.workflow.support.steps.input.InputAction) PARAMETERS_ELEMENT(io.jenkins.blueocean.rest.impl.pipeline.PipelineStepImpl.PARAMETERS_ELEMENT) StringUtils(org.apache.commons.lang3.StringUtils) RunList(hudson.util.RunList) MemoryFlowChunk(org.jenkinsci.plugins.workflow.graphanalysis.MemoryFlowChunk) Map(java.util.Map) FlowExecution(org.jenkinsci.plugins.workflow.flow.FlowExecution) BluePipelineNode(io.jenkins.blueocean.rest.model.BluePipelineNode) Jenkins(jenkins.model.Jenkins) MapsHelper(io.jenkins.blueocean.commons.MapsHelper) TypeSafeMatcher(org.hamcrest.TypeSafeMatcher) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Run(hudson.model.Run) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) NodeDownstreamBuildAction(io.jenkins.blueocean.listeners.NodeDownstreamBuildAction) FilePath(hudson.FilePath) Result(hudson.model.Result) JSONObject(net.sf.json.JSONObject) WorkflowMultiBranchProject(org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject) Optional(java.util.Optional) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) Link(io.jenkins.blueocean.rest.hal.Link) FlowNode(org.jenkinsci.plugins.workflow.graph.FlowNode) BeforeClass(org.junit.BeforeClass) SemaphoreStep(org.jenkinsci.plugins.workflow.test.steps.SemaphoreStep) FreeStyleProject(hudson.model.FreeStyleProject) CpsFlowExecution(org.jenkinsci.plugins.workflow.cps.CpsFlowExecution) FlowGraphTable(org.jenkinsci.plugins.workflow.support.visualization.table.FlowGraphTable) UnstableStep(org.jenkinsci.plugins.workflow.steps.UnstableStep) GitSampleRepoRule(jenkins.plugins.git.GitSampleRepoRule) Unirest(com.mashape.unirest.http.Unirest) SCMSource(jenkins.scm.api.SCMSource) Util(hudson.Util) WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) Description(org.hamcrest.Description) Iterator(java.util.Iterator) BluePipelineStep(io.jenkins.blueocean.rest.model.BluePipelineStep) BlueRun(io.jenkins.blueocean.rest.model.BlueRun) Test(org.junit.Test) BranchSource(jenkins.branch.BranchSource) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Rule(org.junit.Rule) Ignore(org.junit.Ignore) Matcher(org.hamcrest.Matcher) Assert(org.junit.Assert) Slave(hudson.model.Slave) ExtensionList(hudson.ExtensionList) GitSCMSource(jenkins.plugins.git.GitSCMSource) Slave(hudson.model.Slave) WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) Map(java.util.Map) Issue(org.jvnet.hudson.test.Issue) Test(org.junit.Test)

Example 25 with Jenkins

use of jenkins.model.Jenkins in project blueocean-plugin by jenkinsci.

the class UserImplPermissionTest method setup.

@Before
public void setup() throws IOException {
    testOrganization = new TestOrganization("org", "orgDisplayName");
    user = mock(User.class);
    when(user.getId()).thenReturn("some_user");
    authentication = new Authentication() {

        public String getName() {
            return "some_user";
        }

        public GrantedAuthority[] getAuthorities() {
            return null;
        }

        public Object getCredentials() {
            return null;
        }

        public Object getDetails() {
            return null;
        }

        public Object getPrincipal() {
            return null;
        }

        public boolean isAuthenticated() {
            return false;
        }

        public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        }
    };
    jenkins = mock(Jenkins.class);
    when(jenkins.getACL()).thenReturn(new ACL() {

        public boolean hasPermission(Authentication a, Permission permission) {
            return false;
        }
    });
    mockStatic(Jenkins.class);
    when(Jenkins.getAuthentication()).thenReturn(authentication);
    when(Jenkins.get()).thenReturn(jenkins);
    try {
        // After Jenkins 2.77 hasPermission is no longer in Node.class and is not final so we need to mock it
        // prior to it is called as being final and mocking it will fail for the same reason.
        // TODO remove after core base line is >= 2.77
        Node.class.getDeclaredMethod("hasPermission", Permission.class);
    } catch (NoSuchMethodException e) {
        when(jenkins.hasPermission(Mockito.any())).thenAnswer(new Answer<Boolean>() {

            public Boolean answer(InvocationOnMock invocation) {
                Permission permission = invocation.getArgument(0);
                Jenkins j = (Jenkins) invocation.getMock();
                ACL acl = j.getACL();
                try {
                    return acl.hasPermission(permission);
                } catch (NullPointerException x) {
                    throw new AssumptionViolatedException("TODO cannot be made to work prior to Spring Security update", x);
                }
            }
        });
    }
    mockStatic(User.class);
    when(User.get("some_user", false, Collections.EMPTY_MAP)).thenReturn(user);
}
Also used : BlueUser(io.jenkins.blueocean.rest.model.BlueUser) User(hudson.model.User) AssumptionViolatedException(org.junit.AssumptionViolatedException) ACL(hudson.security.ACL) Jenkins(jenkins.model.Jenkins) Answer(org.mockito.stubbing.Answer) Authentication(org.acegisecurity.Authentication) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Permission(hudson.security.Permission) BlueUserPermission(io.jenkins.blueocean.rest.model.BlueUserPermission) Before(org.junit.Before)

Aggregations

Jenkins (jenkins.model.Jenkins)73 Test (org.junit.Test)22 ConfiguredWithCode (org.jenkinsci.plugins.casc.misc.ConfiguredWithCode)13 IOException (java.io.IOException)10 File (java.io.File)9 WorkflowRun (org.jenkinsci.plugins.workflow.job.WorkflowRun)9 FlowExecution (org.jenkinsci.plugins.workflow.flow.FlowExecution)8 ArrayList (java.util.ArrayList)7 List (java.util.List)7 Map (java.util.Map)7 Statement (org.junit.runners.model.Statement)7 CheckForNull (javax.annotation.CheckForNull)6 FilePath (hudson.FilePath)5 Computer (hudson.model.Computer)5 URL (java.net.URL)5 FlowNode (org.jenkinsci.plugins.workflow.graph.FlowNode)5 Issue (org.jvnet.hudson.test.Issue)5 Item (hudson.model.Item)4 Node (hudson.model.Node)4 Date (java.util.Date)4