org.jenkinsci.plugins.workflow.test.steps.SemaphoreStep Java Examples

The following examples show how to use org.jenkinsci.plugins.workflow.test.steps.SemaphoreStep. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultsBinderTest.java    From pipeline-multibranch-defaults-plugin with MIT License 6 votes vote down vote up
@Test
public void testDefaultJenkinsFile() throws Exception {
    GlobalConfigFiles globalConfigFiles = r.jenkins.getExtensionList(GlobalConfigFiles.class).get(GlobalConfigFiles.class);
    ConfigFileStore store = globalConfigFiles.get();

    Config config = new GroovyScript("Jenkinsfile", "Jenkinsfile", "",
        "semaphore 'wait'; node {checkout scm; echo readFile('file')}");
    store.save(config);

    sampleGitRepo.init();
    sampleGitRepo.write("file", "initial content");
    sampleGitRepo.git("commit", "--all", "--message=flow");
    WorkflowMultiBranchProject mp = r.jenkins.createProject(PipelineMultiBranchDefaultsProject.class, "p");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleGitRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    WorkflowJob p = PipelineMultiBranchDefaultsProjectTest.scheduleAndFindBranchProject(mp, "master");
    SemaphoreStep.waitForStart("wait/1", null);
    WorkflowRun b1 = p.getLastBuild();
    assertNotNull(b1);
    assertEquals(1, b1.getNumber());
    SemaphoreStep.success("wait/1", null);
    r.assertLogContains("initial content", r.waitForCompletion(b1));
}
 
Example #2
Source File: DefaultsBinderTest.java    From pipeline-multibranch-defaults-plugin with MIT License 6 votes vote down vote up
@Test
public void testDefaultJenkinsFileLoadFromWorkspace() throws Exception {
    GlobalConfigFiles globalConfigFiles = r.jenkins.getExtensionList(GlobalConfigFiles.class).get(GlobalConfigFiles.class);
    ConfigFileStore store = globalConfigFiles.get();
    Config config = new GroovyScript("Jenkinsfile", "Jenkinsfile", "",
        "semaphore 'wait'; node {checkout scm; load 'Jenkinsfile'}");
    store.save(config);


    sampleGitRepo.init();
    sampleGitRepo.write("Jenkinsfile", "echo readFile('file')");
    sampleGitRepo.git("add", "Jenkinsfile");
    sampleGitRepo.write("file", "initial content");
    sampleGitRepo.git("commit", "--all", "--message=flow");
    WorkflowMultiBranchProject mp = r.jenkins.createProject(PipelineMultiBranchDefaultsProject.class, "p");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleGitRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    WorkflowJob p = PipelineMultiBranchDefaultsProjectTest.scheduleAndFindBranchProject(mp, "master");
    SemaphoreStep.waitForStart("wait/1", null);
    WorkflowRun b1 = p.getLastBuild();
    assertNotNull(b1);
    assertEquals(1, b1.getNumber());
    SemaphoreStep.success("wait/1", null);
    r.assertLogContains("initial content", r.waitForCompletion(b1));
}
 
Example #3
Source File: KubernetesPipelineTest.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void podTemplateWithMultipleLabels() throws Exception {
    PodTemplate pt = new PodTemplate();
    pt.setName("podTemplate");
    pt.setLabel("label1 label2");
    ContainerTemplate jnlp = new ContainerTemplate("jnlp", "jenkins/jnlp-slave:3.35-5-alpine");
    pt.setContainers(Collections.singletonList(jnlp));
    cloud.addTemplate(pt);
    SemaphoreStep.waitForStart("pod/1", b);
    Map<String, String> labels = getLabels(cloud, this, name);
    labels.put("jenkins/label","label1_label2");
    KubernetesSlave node = r.jenkins.getNodes().stream()
            .filter(KubernetesSlave.class::isInstance)
            .map(KubernetesSlave.class::cast)
            .findAny().get();
    assertTrue(node.getAssignedLabels().containsAll(Label.parse("label1 label2")));
    PodList pods = cloud.connect().pods().withLabels(labels).list();
    assertThat(
            "Expected one pod with labels " + labels + " but got: "
                    + pods.getItems().stream().map(pod -> pod.getMetadata()).collect(Collectors.toList()),
            pods.getItems(), hasSize(1));
    SemaphoreStep.success("pod/1", null);
    r.assertBuildStatusSuccess(r.waitForCompletion(b));
}
 
Example #4
Source File: KubernetesPipelineTest.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void computerCantBeConfigured() throws Exception {
    r.jenkins.setSecurityRealm(r.createDummySecurityRealm());
    r.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().
            grant(Jenkins.ADMINISTER).everywhere().to("admin"));
    SemaphoreStep.waitForStart("pod/1", b);
    Optional<KubernetesSlave> optionalNode = r.jenkins.getNodes().stream().filter(KubernetesSlave.class::isInstance).map(KubernetesSlave.class::cast).findAny();
    assertTrue(optionalNode.isPresent());
    KubernetesSlave node = optionalNode.get();

    JenkinsRule.WebClient wc = r.createWebClient().login("admin");
    wc.getOptions().setPrintContentOnFailingStatusCode(false);

    HtmlPage nodeIndex = wc.getPage(node);
    assertNotXPath(nodeIndex, "//*[text() = 'configure']");
    wc.assertFails(node.toComputer().getUrl()+"configure", 403);
    SemaphoreStep.success("pod/1", null);
}
 
Example #5
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 6 votes vote down vote up
private void waitAndClear(int semaphoreIndex, List<WorkflowRun> nextRuns) throws Exception {
  WorkflowRun toClear = nextRuns.get(0);

  System.err.println("Waiting for semaphore to start for " + toClear.getNumber());
  SemaphoreStep.waitForStart("wait-inside-2/" + semaphoreIndex, toClear);

  List<WorkflowRun> remainingRuns = new ArrayList<>();

  if (nextRuns.size() > 1) {
    remainingRuns.addAll(nextRuns.subList(1, nextRuns.size()));

    for (WorkflowRun r : remainingRuns) {
      System.err.println("Verifying no semaphore yet for " + r.getNumber());
      j.assertLogNotContains("Entering semaphore now", r);
    }
  }

  SemaphoreStep.success("wait-inside-2/" + semaphoreIndex, null);
  System.err.println("Waiting for " + toClear.getNumber() + " to complete");
  j.assertBuildStatusSuccess(j.waitForCompletion(toClear));

  if (!remainingRuns.isEmpty()) {
    waitAndClear(semaphoreIndex + 1, remainingRuns);
  }
}
 
Example #6
Source File: KubernetesPipelineTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Test
@Issue("JENKINS-58602")
public void jenkinsSecretHidden() throws Exception {
    SemaphoreStep.waitForStart("pod/1", b);
    Optional<SlaveComputer> scOptional = Arrays.stream(r.jenkins.getComputers())
            .filter(SlaveComputer.class::isInstance)
            .map(SlaveComputer.class::cast)
            .findAny();
    assertTrue(scOptional.isPresent());
    String jnlpMac = scOptional.get().getJnlpMac();
    SemaphoreStep.success("pod/1", b);
    r.assertBuildStatusSuccess(r.waitForCompletion(b));
    r.assertLogNotContains(jnlpMac, b);
}
 
Example #7
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 5 votes vote down vote up
@Test
public void lockInverseOrder() throws Exception {
  LockableResourcesManager.get().createResource("resource1");
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "lock(resource: 'resource1', inversePrecedence: true) {\n"
              + "	semaphore 'wait-inside'\n"
              + "}\n"
              + "echo 'Finish'",
          true));
  WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
  SemaphoreStep.waitForStart("wait-inside/1", b1);

  WorkflowRun b2 = p.scheduleBuild2(0).waitForStart();
  // Ensure that b2 reaches the lock before b3
  j.waitForMessage("[resource1] is locked by " + b1.getFullDisplayName() + ", waiting...", b2);
  isPaused(b2, 1, 1);
  WorkflowRun b3 = p.scheduleBuild2(0).waitForStart();
  // Both 2 and 3 are waiting for locking resource1

  j.waitForMessage("[resource1] is locked by " + b1.getFullDisplayName() + ", waiting...", b3);
  isPaused(b3, 1, 1);

  // Unlock resource1
  SemaphoreStep.success("wait-inside/1", null);
  j.waitForMessage("Lock released on resource [resource1]", b1);
  isPaused(b1, 1, 0);

  // #3 gets the lock before #2 because of inversePrecedence
  j.waitForMessage("Lock acquired on [resource1]", b3);
  SemaphoreStep.success("wait-inside/2", null);
  isPaused(b3, 1, 0);
  j.waitForMessage("Lock acquired on [resource1]", b2);
  SemaphoreStep.success("wait-inside/3", null);
  j.waitForMessage("Finish", b3);
  isPaused(b2, 1, 0);
}
 
Example #8
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 5 votes vote down vote up
@Test
public void lockOrder() throws Exception {
  LockableResourcesManager.get().createResource("resource1");
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "lock('resource1') {\n" + "	semaphore 'wait-inside'\n" + "}\n" + "echo 'Finish'",
          true));
  WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
  SemaphoreStep.waitForStart("wait-inside/1", b1);

  WorkflowRun b2 = p.scheduleBuild2(0).waitForStart();
  // Ensure that b2 reaches the lock before b3
  j.waitForMessage("[resource1] is locked by " + b1.getFullDisplayName() + ", waiting...", b2);
  isPaused(b2, 1, 1);
  WorkflowRun b3 = p.scheduleBuild2(0).waitForStart();
  // Both 2 and 3 are waiting for locking resource1

  j.waitForMessage("[resource1] is locked by " + b1.getFullDisplayName() + ", waiting...", b3);
  isPaused(b3, 1, 1);

  // Unlock resource1
  SemaphoreStep.success("wait-inside/1", null);
  j.waitForMessage("Lock released on resource [resource1]", b1);
  isPaused(b1, 1, 0);

  // #2 gets the lock before #3 (in the order as they requested the lock)
  j.waitForMessage("Lock acquired on [resource1]", b2);
  SemaphoreStep.success("wait-inside/2", null);
  isPaused(b2, 1, 0);
  j.waitForMessage("Lock acquired on [resource1]", b3);
  SemaphoreStep.success("wait-inside/3", null);
  j.waitForMessage("Finish", b3);
  isPaused(b3, 1, 0);
}
 
Example #9
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 5 votes vote down vote up
@Test
public void parallelLock() throws Exception {
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "parallel a: {\n"
              + "	semaphore 'before-a'\n"
              + "	lock('resource1') {\n"
              + "		semaphore 'inside-a'\n"
              + "	}\n"
              + "}, b: {\n"
              + "	lock('resource1') {\n"
              + "		semaphore 'wait-b'\n"
              + "	}\n"
              + "}\n",
          true));

  WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
  SemaphoreStep.waitForStart("wait-b/1", b1);
  SemaphoreStep.waitForStart("before-a/1", b1);
  // both messages are in the log because branch b acquired the lock and branch a is waiting to
  // lock
  j.waitForMessage("Lock acquired on [resource1]", b1);
  SemaphoreStep.success("before-a/1", null);
  j.waitForMessage("[resource1] is locked by " + b1.getFullDisplayName() + ", waiting...", b1);
  isPaused(b1, 2, 1);

  SemaphoreStep.success("wait-b/1", null);

  j.waitForMessage("Lock acquired on [resource1]", b1);
  SemaphoreStep.waitForStart("inside-a/1", b1);
  isPaused(b1, 2, 0);
  SemaphoreStep.success("inside-a/1", null);

  j.waitForCompletion(b1);
  assertNull(LockableResourcesManager.get().fromName("resource1"));
}
 
Example #10
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 5 votes vote down vote up
@Test
public void unlockButtonWithWaitingRuns() throws Exception {
  LockableResourcesManager.get().createResource("resource1");
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "retry(99) {\n"
              + "    lock('resource1') {\n"
              + "        semaphore('wait-inside')\n"
              + "     }\n"
              + "}",
          true));

  JenkinsRule.WebClient wc = j.createWebClient();

  WorkflowRun prevBuild = null;
  for (int i = 0; i < 3; i++) {
    WorkflowRun rNext = p.scheduleBuild2(0).waitForStart();
    if (prevBuild != null) {
      j.waitForMessage(
          "[resource1] is locked by " + prevBuild.getFullDisplayName() + ", waiting...", rNext);
      isPaused(rNext, 1, 1);
      wc.goTo("lockable-resources/unlock?resource=resource1");
    }

    j.waitForMessage("Lock acquired on [resource1]", rNext);
    SemaphoreStep.waitForStart("wait-inside/" + (i + 1), rNext);
    isPaused(rNext, 1, 0);

    if (prevBuild != null) {
      SemaphoreStep.success("wait-inside/" + i, null);
      j.assertBuildStatusSuccess(j.waitForCompletion(prevBuild));
    }
    prevBuild = rNext;
  }
  SemaphoreStep.success("wait-inside/3", null);
  j.assertBuildStatus(Result.SUCCESS, j.waitForCompletion(prevBuild));
}
 
Example #11
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-40879")
@Test
public void parallelLockRelease() throws Exception {
  LockableResourcesManager.get().createResource("resource1");
  LockableResourcesManager.get().createResource("resource2");
  WorkflowJob job = j.jenkins.createProject(WorkflowJob.class, "j");
  job.setDefinition(
      new CpsFlowDefinition(
          "lock(resource: 'resource1') {\n"
              + "    semaphore 'wait-inside-1'\n"
              + "}\n"
              + "lock(resource: 'resource2') { \n"
              + "    echo 'Entering semaphore now'\n"
              + "    semaphore 'wait-inside-2'\n"
              + "}\n",
          true));

  List<WorkflowRun> nextRuns = new ArrayList<>();

  WorkflowRun toUnlock = null;
  for (int i = 0; i < 5; i++) {
    WorkflowRun rNext = job.scheduleBuild2(0).waitForStart();
    if (toUnlock != null) {
      j.waitForMessage(
          "[resource1] is locked by " + toUnlock.getFullDisplayName() + ", waiting...", rNext);
      isPaused(rNext, 1, 1);
      SemaphoreStep.success("wait-inside-1/" + i, null);
    }
    SemaphoreStep.waitForStart("wait-inside-1/" + (i + 1), rNext);
    isPaused(rNext, 1, 0);
    nextRuns.add(rNext);
    toUnlock = rNext;
  }
  SemaphoreStep.success("wait-inside-1/" + nextRuns.size(), null);
  waitAndClear(1, nextRuns);
}
 
Example #12
Source File: LockStepHardKillTest.java    From lockable-resources-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-40368")
@Test
public void hardKillWithWaitingRuns() throws Exception {
  LockableResourcesManager.get().createResource("resource1");
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "retry(99) {\n"
              + "    lock('resource1') {\n"
              + "        semaphore('wait-inside')\n"
              + "     }\n"
              + "}",
          true));

  WorkflowRun prevBuild = null;
  for (int i = 0; i < 3; i++) {
    WorkflowRun rNext = p.scheduleBuild2(0).waitForStart();
    if (prevBuild != null) {
      j.waitForMessage(
          "[resource1] is locked by " + prevBuild.getFullDisplayName() + ", waiting...", rNext);
      isPaused(rNext, 1, 1);
      interruptTermKill(prevBuild);
    }

    j.waitForMessage("Lock acquired on [resource1]", rNext);

    SemaphoreStep.waitForStart("wait-inside/" + (i + 1), rNext);
    isPaused(rNext, 1, 0);
    prevBuild = rNext;
  }
  SemaphoreStep.success("wait-inside/3", null);
  j.assertBuildStatus(Result.SUCCESS, j.waitForCompletion(prevBuild));
}
 
Example #13
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("JENKINS-50176")
public void lockWithLabelFillsVariable() throws Exception {
  LockableResourcesManager.get().createResourceWithLabel("resource1", "label1");
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "lock(label: 'label1', variable: 'someVar') {\n"
              + "  semaphore 'wait-inside'\n"
              + "  echo \"VAR IS $env.someVar\"\n"
              + "}",
          true));
  WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
  SemaphoreStep.waitForStart("wait-inside/1", b1);

  WorkflowJob p2 = j.jenkins.createProject(WorkflowJob.class, "p2");
  p2.setDefinition(
      new CpsFlowDefinition(
          "lock(label: 'label1', variable: 'someVar2') {\n"
              + "  echo \"VAR2 IS $env.someVar2\"\n"
              + "}",
          true));
  WorkflowRun b2 = p2.scheduleBuild2(0).waitForStart();
  j.waitForMessage("is locked, waiting...", b2);
  isPaused(b2, 1, 1);

  // Unlock resources
  SemaphoreStep.success("wait-inside/1", null);
  j.waitForMessage("Lock released on resource", b1);
  isPaused(b1, 1, 0);

  // Now job 2 should get and release the lock...
  j.waitForCompletion(b1);
  j.waitForCompletion(b2);
  isPaused(b2, 1, 0);

  // Variable should have been filled in both cases
  j.assertLogContains("VAR IS resource1", b1);
  j.assertLogContains("VAR2 IS resource1", b2);
}
 
Example #14
Source File: KubernetesPipelineTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void runWithActiveDeadlineSeconds() throws Exception {
    SemaphoreStep.waitForStart("podTemplate/1", b);
    PodTemplate deadlineTemplate = cloud.getAllTemplates().stream().filter(x -> name.getMethodName().equals(x.getLabel())).findAny().orElse(null);
    assertNotNull(deadlineTemplate);
    SemaphoreStep.success("podTemplate/1", null);
    assertEquals(10, deadlineTemplate.getActiveDeadlineSeconds());
    b.getExecutor().interrupt();
    r.assertBuildStatus(Result.ABORTED, r.waitForCompletion(b));
}
 
Example #15
Source File: KubernetesPipelineTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void runIn2Pods() throws Exception {
    SemaphoreStep.waitForStart("podTemplate1/1", b);
    String label1 = name.getMethodName() + "-1";
    PodTemplate template1 = podTemplatesWithLabel(label1, cloud.getAllTemplates()).get(0);
    SemaphoreStep.success("podTemplate1/1", null);
    assertEquals(Integer.MAX_VALUE, template1.getInstanceCap());
    assertThat(template1.getLabelsMap(), hasEntry("jenkins/label", label1));
    SemaphoreStep.waitForStart("pod1/1", b);
    Map<String, String> labels1 = getLabels(cloud, this, name);
    labels1.put("jenkins/label",label1);
    PodList pods = cloud.connect().pods().withLabels(labels1).list();
    assertTrue(!pods.getItems().isEmpty());
    SemaphoreStep.success("pod1/1", null);

    SemaphoreStep.waitForStart("podTemplate2/1", b);
    String label2 = name.getMethodName() + "-2";
    PodTemplate template2 = podTemplatesWithLabel(label2, cloud.getAllTemplates()).get(0);
    SemaphoreStep.success("podTemplate2/1", null);
    assertEquals(Integer.MAX_VALUE, template2.getInstanceCap());
    assertThat(template2.getLabelsMap(), hasEntry("jenkins/label", label2));
    assertNull(label2 + " should not inherit from anything", template2.getInheritFrom());
    SemaphoreStep.waitForStart("pod2/1", b);
    Map<String, String> labels2 = getLabels(cloud, this, name);
    labels1.put("jenkins/label", label2);
    PodList pods2 = cloud.connect().pods().withLabels(labels2).list();
    assertTrue(!pods2.getItems().isEmpty());
    SemaphoreStep.success("pod2/1", null);
    r.assertBuildStatusSuccess(r.waitForCompletion(b));
    r.assertLogContains("script file contents: ", b);
    r.assertLogContains("Started container jnlp", b);
    assertFalse("There are pods leftover after test execution, see previous logs",
            deletePods(cloud.connect(), getLabels(cloud, this, name), true));
}
 
Example #16
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-34433")
@Test
public void manualUnreserveUnblocksJob() throws Exception {
  LockableResourcesManager.get().createResource("resource1");
  JenkinsRule.WebClient wc = j.createWebClient();

  wc.goTo("lockable-resources/reserve?resource=resource1");
  LockableResource resource1 = LockableResourcesManager.get().fromName("resource1");
  assertNotNull(resource1);
  resource1.setReservedBy("someone");
  assertTrue(resource1.isReserved());

  JSONObject apiRes = TestHelpers.getResourceFromApi(j, "resource1", false);
  assertThat(apiRes, hasEntry("reserved", true));
  assertThat(apiRes, hasEntry("reservedBy", "someone"));

  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "retry(99) {\n"
              + "    lock('resource1') {\n"
              + "        semaphore('wait-inside')\n"
              + "     }\n"
              + "}",
          true));

  WorkflowRun r = p.scheduleBuild2(0).waitForStart();
  j.waitForMessage("[resource1] is locked, waiting...", r);
  wc.goTo("lockable-resources/unreserve?resource=resource1");
  SemaphoreStep.waitForStart("wait-inside/1", r);
  SemaphoreStep.success("wait-inside/1", null);
  j.assertBuildStatusSuccess(j.waitForCompletion(r));
}
 
Example #17
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 4 votes vote down vote up
@Test
public void lockWithLabelAndLabeledResourceQuantity() throws Exception {
  LockableResourcesManager.get().createResourceWithLabel("resource1", "label1");
  LockableResourcesManager.get().createResourceWithLabel("resource2", "label1");
  LockableResourcesManager.get().createResourceWithLabel("resource3", "label1");
  LockableResourcesManager.get().createResourceWithLabel("resource4", "label1");
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "lock(variable: 'var', extra: [[resource: 'resource4'], [resource: 'resource2'], [label: 'label1', quantity: 2]]) {\n"
              + "  def lockedResources = env.var.split(',').sort()\n"
              + "  echo \"Resources locked: ${lockedResources}\"\n"
              + "  semaphore 'wait-inside'\n"
              + "}\n"
              + "echo 'Finish'",
          true));
  // #1 should lock as few resources as possible
  WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
  SemaphoreStep.waitForStart("wait-inside/1", b1);

  WorkflowJob p2 = j.jenkins.createProject(WorkflowJob.class, "p2");
  p2.setDefinition(
      new CpsFlowDefinition(
          "lock(label: 'label1', variable: 'var', quantity: 3) {\n"
              + "	def lockedResources = env.var.split(',').sort()\n"
              + "	echo \"Resources locked: ${lockedResources}\"\n"
              + "	semaphore 'wait-inside-quantity3'\n"
              + "}\n"
              + "echo 'Finish'",
          true));
  WorkflowRun b2 = p2.scheduleBuild2(0).waitForStart();
  j.waitForMessage("[Label: label1, Quantity: 3] is locked, waiting...", b2);
  j.waitForMessage("Found 2 available resource(s). Waiting for correct amount: 3.", b2);
  isPaused(b2, 1, 1);

  WorkflowJob p3 = j.jenkins.createProject(WorkflowJob.class, "p3");
  p3.setDefinition(
      new CpsFlowDefinition(
          "lock(label: 'label1', variable: 'var', quantity: 2) {\n"
              + "	def lockedResources = env.var.split(',').sort()\n"
              + "	echo \"Resources locked: ${lockedResources}\"\n"
              + "	semaphore 'wait-inside-quantity2'\n"
              + "}\n"
              + "echo 'Finish'",
          true));
  WorkflowRun b3 = p3.scheduleBuild2(0).waitForStart();
  // While 2 continues waiting, 3 can continue directly
  SemaphoreStep.waitForStart("wait-inside-quantity2/1", b3);
  // Let 3 finish
  SemaphoreStep.success("wait-inside-quantity2/1", null);
  j.waitForMessage("Finish", b3);
  j.assertLogContains("Resources locked: [resource1, resource3]", b3);
  isPaused(b3, 1, 0);

  // Unlock resources
  SemaphoreStep.success("wait-inside/1", null);
  j.waitForMessage(
      "Lock released on resource [{resource4},{resource2},{Label: label1, Quantity: 2}]", b1);
  j.assertLogContains("Resources locked: [resource2, resource4]", b1);
  isPaused(b1, 1, 0);

  // #2 gets the lock
  j.waitForMessage("Lock acquired on [Label: label1, Quantity: 3]", b2);
  SemaphoreStep.success("wait-inside-quantity3/1", null);
  j.waitForMessage("Finish", b2);
  // Could be any 3 resources, so just check the beginning of the message
  j.assertLogContains("Resources locked: [resource", b2);
  isPaused(b2, 1, 0);

  assertNotNull(LockableResourcesManager.get().fromName("resource1"));
  assertNotNull(LockableResourcesManager.get().fromName("resource2"));
  assertNotNull(LockableResourcesManager.get().fromName("resource3"));
  assertNotNull(LockableResourcesManager.get().fromName("resource4"));
}
 
Example #18
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 4 votes vote down vote up
@Test
public void lockMultipleResources() throws Exception {
  LockableResourcesManager.get().createResource("resource1");
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "lock(resource: 'resource1', extra: [[resource: 'resource2']]) {\n"
              + "	semaphore 'wait-inside'\n"
              + "}\n"
              + "echo 'Finish'",
          true));
  WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
  SemaphoreStep.waitForStart("wait-inside/1", b1);

  WorkflowJob p2 = j.jenkins.createProject(WorkflowJob.class, "p2");
  p2.setDefinition(
      new CpsFlowDefinition(
          "lock('resource1') {\n" + "	semaphore 'wait-inside-p2'\n" + "}\n" + "echo 'Finish'",
          true));
  WorkflowRun b2 = p2.scheduleBuild2(0).waitForStart();
  j.waitForMessage("[resource1] is locked by " + b1.getFullDisplayName() + ", waiting...", b2);
  isPaused(b2, 1, 1);

  WorkflowJob p3 = j.jenkins.createProject(WorkflowJob.class, "p3");
  p3.setDefinition(
      new CpsFlowDefinition(
          "lock('resource2') {\n" + "	semaphore 'wait-inside-p3'\n" + "}\n" + "echo 'Finish'",
          true));
  WorkflowRun b3 = p3.scheduleBuild2(0).waitForStart();
  j.waitForMessage("[resource2] is locked by " + b1.getFullDisplayName() + ", waiting...", b3);
  isPaused(b3, 1, 1);

  // Unlock resources
  SemaphoreStep.success("wait-inside/1", null);
  j.waitForMessage("Lock released on resource [{resource1},{resource2}]", b1);
  isPaused(b1, 1, 0);

  // Both get their lock
  j.waitForMessage("Lock acquired on [resource1]", b2);
  j.waitForMessage("Lock acquired on [resource2]", b3);

  SemaphoreStep.success("wait-inside-p2/1", null);
  SemaphoreStep.success("wait-inside-p3/1", null);
  j.waitForMessage("Finish", b2);
  j.waitForMessage("Finish", b3);
  isPaused(b2, 1, 0);
  isPaused(b3, 1, 0);
}
 
Example #19
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 4 votes vote down vote up
@Test
public void lockWithLabelAndResource() throws Exception {
  LockableResourcesManager.get().createResource("resource1");
  LockableResourcesManager.get().createResourceWithLabel("resource2", "label1");
  LockableResourcesManager.get().createResourceWithLabel("resource3", "label1");
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "lock(label: 'label1', extra: [[resource: 'resource1']]) {\n"
              + "	semaphore 'wait-inside'\n"
              + "}\n"
              + "echo 'Finish'",
          true));
  WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
  SemaphoreStep.waitForStart("wait-inside/1", b1);

  WorkflowJob p2 = j.jenkins.createProject(WorkflowJob.class, "p2");
  p2.setDefinition(
      new CpsFlowDefinition(
          "lock('resource1') {\n" + "	semaphore 'wait-inside-p2'\n" + "}\n" + "echo 'Finish'",
          true));
  WorkflowRun b2 = p2.scheduleBuild2(0).waitForStart();
  j.waitForMessage("[resource1] is locked by " + b1.getFullDisplayName() + ", waiting...", b2);
  isPaused(b2, 1, 1);

  WorkflowJob p3 = j.jenkins.createProject(WorkflowJob.class, "p3");
  p3.setDefinition(
      new CpsFlowDefinition(
          "lock(label: 'label1') {\n" + "	semaphore 'wait-inside-p3'\n" + "}\n" + "echo 'Finish'",
          true));
  WorkflowRun b3 = p3.scheduleBuild2(0).waitForStart();
  j.waitForMessage("[Label: label1] is locked, waiting...", b3);
  isPaused(b3, 1, 1);

  // Unlock resources
  SemaphoreStep.success("wait-inside/1", null);
  j.waitForMessage("Lock released on resource [{Label: label1},{resource1}]", b1);
  isPaused(b2, 1, 0);

  // Both get their lock
  j.waitForMessage("Lock acquired on [resource1]", b2);
  j.waitForMessage("Lock acquired on [Label: label1]", b3);

  SemaphoreStep.success("wait-inside-p2/1", null);
  SemaphoreStep.success("wait-inside-p3/1", null);
  j.waitForMessage("Finish", b2);
  j.waitForMessage("Finish", b3);
  isPaused(b2, 1, 0);
  isPaused(b3, 1, 0);
}
 
Example #20
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 4 votes vote down vote up
@Test
public void lockWithLabelAndLabeledResource() throws Exception {
  LockableResourcesManager.get().createResourceWithLabel("resource1", "label1");
  LockableResourcesManager.get().createResourceWithLabel("resource2", "label1");
  LockableResourcesManager.get().createResourceWithLabel("resource3", "label1");
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "lock(label: 'label1', extra: [[resource: 'resource1']]) {\n"
              + "	semaphore 'wait-inside'\n"
              + "}\n"
              + "echo 'Finish'",
          true));
  WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
  SemaphoreStep.waitForStart("wait-inside/1", b1);

  WorkflowJob p2 = j.jenkins.createProject(WorkflowJob.class, "p2");
  p2.setDefinition(
      new CpsFlowDefinition(
          "lock('resource1') {\n" + "	semaphore 'wait-inside-p2'\n" + "}\n" + "echo 'Finish'",
          true));
  WorkflowRun b2 = p2.scheduleBuild2(0).waitForStart();
  j.waitForMessage("[resource1] is locked by " + b1.getFullDisplayName() + ", waiting...", b2);
  isPaused(b2, 1, 1);

  WorkflowJob p3 = j.jenkins.createProject(WorkflowJob.class, "p3");
  p3.setDefinition(
      new CpsFlowDefinition(
          "lock(label: 'label1') {\n" + "	semaphore 'wait-inside-p3'\n" + "}\n" + "echo 'Finish'",
          true));
  WorkflowRun b3 = p3.scheduleBuild2(0).waitForStart();
  j.waitForMessage("[Label: label1] is locked, waiting...", b3);
  isPaused(b3, 1, 1);

  // Unlock resources
  SemaphoreStep.success("wait-inside/1", null);
  j.waitForMessage("Lock released on resource [{Label: label1},{resource1}]", b1);
  isPaused(b1, 1, 0);

  // #2 gets the lock before #3 (in the order as they requested the lock)
  j.waitForMessage("Lock acquired on [resource1]", b2);
  SemaphoreStep.success("wait-inside-p2/1", null);
  j.waitForMessage("Finish", b2);
  isPaused(b2, 1, 0);
  j.waitForMessage("Lock acquired on [Label: label1]", b3);
  SemaphoreStep.success("wait-inside-p3/1", null);
  j.waitForMessage("Finish", b3);
  isPaused(b3, 1, 0);

  assertNotNull(LockableResourcesManager.get().fromName("resource1"));
  assertNotNull(LockableResourcesManager.get().fromName("resource2"));
  assertNotNull(LockableResourcesManager.get().fromName("resource3"));
}
 
Example #21
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 4 votes vote down vote up
@Test
public void lockOrderLabelQuantityFreedResources() throws Exception {
  LockableResourcesManager.get().createResourceWithLabel("resource1", "label1");
  LockableResourcesManager.get().createResourceWithLabel("resource2", "label1");
  LockableResourcesManager.get().createResourceWithLabel("resource3", "label1");
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "lock(label: 'label1') {\n" + "	semaphore 'wait-inside'\n" + "}\n" + "echo 'Finish'",
          true));
  WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
  SemaphoreStep.waitForStart("wait-inside/1", b1);

  JSONObject apiRes = TestHelpers.getResourceFromApi(j, "resource1", true);
  assertThat(apiRes, hasEntry("labels", "label1"));

  WorkflowJob p2 = j.jenkins.createProject(WorkflowJob.class, "p2");
  p2.setDefinition(
      new CpsFlowDefinition(
          "lock(label: 'label1', quantity: 2) {\n"
              + "	semaphore 'wait-inside-quantity2'\n"
              + "}\n"
              + "echo 'Finish'",
          true));
  WorkflowRun b2 = p2.scheduleBuild2(0).waitForStart();
  // Ensure that b2 reaches the lock before b3
  j.waitForMessage("[Label: label1, Quantity: 2] is locked, waiting...", b2);
  j.waitForMessage("Found 0 available resource(s). Waiting for correct amount: 2.", b2);
  isPaused(b2, 1, 1);

  WorkflowJob p3 = j.jenkins.createProject(WorkflowJob.class, "p3");
  p3.setDefinition(
      new CpsFlowDefinition(
          "lock(label: 'label1', quantity: 1) {\n"
              + "	semaphore 'wait-inside-quantity1'\n"
              + "}\n"
              + "echo 'Finish'",
          true));
  WorkflowRun b3 = p3.scheduleBuild2(0).waitForStart();
  j.waitForMessage("[Label: label1, Quantity: 1] is locked, waiting...", b3);
  j.waitForMessage("Found 0 available resource(s). Waiting for correct amount: 1.", b3);
  isPaused(b3, 1, 1);

  // Unlock Label: label1
  SemaphoreStep.success("wait-inside/1", null);
  j.waitForMessage("Lock released on resource [Label: label1]", b1);
  isPaused(b1, 1, 0);

  // Both get their lock
  j.waitForMessage("Lock acquired on [Label: label1, Quantity: 2]", b2);
  j.waitForMessage("Lock acquired on [Label: label1, Quantity: 1]", b3);

  SemaphoreStep.success("wait-inside-quantity2/1", null);
  SemaphoreStep.success("wait-inside-quantity1/1", null);
  j.waitForMessage("Finish", b2);
  j.waitForMessage("Finish", b3);
  isPaused(b2, 1, 0);
  isPaused(b3, 1, 0);

  assertNotNull(LockableResourcesManager.get().fromName("resource1"));
  assertNotNull(LockableResourcesManager.get().fromName("resource2"));
  assertNotNull(LockableResourcesManager.get().fromName("resource3"));
}
 
Example #22
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 4 votes vote down vote up
@Test
@Issue("JENKINS-50176")
public void parallelLockWithLabelFillsVariable() throws Exception {
  LockableResourcesManager.get().createResourceWithLabel("resource1", "label1");
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "parallel p1: {\n"
              + "  lock(label: 'label1', variable: 'someVar') {\n"
              + "    semaphore 'wait-inside'\n"
              + "    echo \"VAR IS $env.someVar\"\n"
              + "  }\n"
              + "},\n"
              + "p2: {\n"
              + "  semaphore 'wait-outside'\n"
              + "  lock(label: 'label1', variable: 'someVar2') {\n"
              + "    echo \"VAR2 IS $env.someVar2\"\n"
              + "  }\n"
              + "}",
          true));
  WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
  SemaphoreStep.waitForStart("wait-outside/1", b1);
  SemaphoreStep.waitForStart("wait-inside/1", b1);
  SemaphoreStep.success("wait-outside/1", null);

  j.waitForMessage("is locked, waiting...", b1);
  isPaused(b1, 2, 1);

  // Unlock resources
  SemaphoreStep.success("wait-inside/1", null);
  j.waitForMessage("Lock released on resource", b1);
  isPaused(b1, 2, 0);

  // Now the second parallel branch should get and release the lock...
  j.waitForCompletion(b1);
  isPaused(b1, 2, 0);

  // Variable should have been filled in both cases
  j.assertLogContains("VAR IS resource1", b1);
  j.assertLogContains("VAR2 IS resource1", b1);
}
 
Example #23
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 4 votes vote down vote up
@Issue("JENKINS-36479")
@Test
public void deleteRunningBuildNewBuildClearsLock() throws Exception {
  assumeFalse(Functions.isWindows());

  LockableResourcesManager.get().createResource("resource1");

  WorkflowJob p1 = j.jenkins.createProject(WorkflowJob.class, "p");
  p1.setDefinition(
      new CpsFlowDefinition(
          "lock('resource1') { echo 'locked!'; semaphore 'wait-inside' }", true));
  WorkflowRun b1 = p1.scheduleBuild2(0).waitForStart();
  j.waitForMessage("locked!", b1);
  SemaphoreStep.waitForStart("wait-inside/1", b1);

  WorkflowJob p2 = j.jenkins.createProject(WorkflowJob.class, "p2");
  p2.setDefinition(
      new CpsFlowDefinition("lock('resource1') {\n" + "  semaphore 'wait-inside'\n" + "}", true));
  WorkflowRun b2 = p2.scheduleBuild2(0).waitForStart();
  // Make sure that b2 is blocked on b1's lock.
  j.waitForMessage("[resource1] is locked by " + b1.getFullDisplayName() + ", waiting...", b2);
  isPaused(b2, 1, 1);

  // Now b2 is still sitting waiting for a lock. Create b3 and launch it to verify order of
  // unlock.
  WorkflowJob p3 = j.jenkins.createProject(WorkflowJob.class, "p3");
  p3.setDefinition(
      new CpsFlowDefinition("lock('resource1') {\n" + "  semaphore 'wait-inside'\n" + "}", true));
  WorkflowRun b3 = p3.scheduleBuild2(0).waitForStart();
  j.waitForMessage("[resource1] is locked by " + b1.getFullDisplayName() + ", waiting...", b3);
  isPaused(b3, 1, 1);

  b1.delete();

  // Verify that b2 gets the lock.
  j.waitForMessage("Lock acquired on [resource1]", b2);
  SemaphoreStep.success("wait-inside/2", b2);
  // Verify that b2 releases the lock and finishes successfully.
  j.waitForMessage("Lock released on resource [resource1]", b2);
  j.assertBuildStatusSuccess(j.waitForCompletion(b2));
  isPaused(b2, 1, 0);

  // Now b3 should get the lock and do its thing.
  j.waitForMessage("Lock acquired on [resource1]", b3);
  SemaphoreStep.success("wait-inside/3", b3);
  j.assertBuildStatusSuccess(j.waitForCompletion(b3));
  isPaused(b3, 1, 0);
}
 
Example #24
Source File: PipelineNodeTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test
public void nodesWithPartialParallels() throws Exception {
    WorkflowJob job1 = j.jenkins.createProject(WorkflowJob.class, "pipeline1");
    job1.setDefinition(new CpsFlowDefinition("node {\n" +
                                                 "    stage (\"hey\") {\n" +
                                                 "        sh \"echo yeah\"\n" +
                                                 "    }\n" +
                                                 "    stage (\"par\") {\n" +
                                                 "    \n" +
                                                 "        parallel left : {\n" +
                                                 "            sh \"echo OMG BS\"\n" +
                                                 "            sh \"echo yeah\"\n" +
                                                 "        }, \n" +
                                                 "        \n" +
                                                 "        right : {\n" +
                                                 "            sh \"echo wozzle\"\n" +
                                                 "        }\n" +
                                                 "    }\n" +
                                                 "    stage (\"ho\") {\n" +
                                                 "        sh \"echo done\"\n" +
                                                 "    }\n" +
                                                 "}", false));

    j.buildAndAssertSuccess(job1);
    List<Map> resp = get("/organizations/jenkins/pipelines/pipeline1/runs/1/nodes/", List.class);
    Assert.assertEquals(5, resp.size());

    job1.setDefinition(new CpsFlowDefinition("node {\n" +
                                                 "    stage (\"hey\") {\n" +
                                                 "        sh \"echo yeah\"\n" +
                                                 "    }\n" +
                                                 "    stage (\"par\") {\n" +
                                                 "    \n" +
                                                 "        parallel left : {\n" +
                                                 "            sh \"echo OMG BS\"\n" +
                                                 "            echo \"running\"\n" +
                                                 "            semaphore('left')\n" +
                                                 "            echo \"BRANCH NAME left\"\n" +
                                                 "            sh \"echo yeah\"\n" +
                                                 "        }, \n" +
                                                 "        \n" +
                                                 "        right : {\n" +
                                                 "            sh \"echo wozzle\"\n" +
                                                 "            semaphore('right')\n" +
                                                 "            echo \"BRANCH NAME right\"\n" +
                                                 "        }\n" +
                                                 "    }\n" +
                                                 "    stage (\"ho\") {\n" +
                                                 "        sh \"echo done\"\n" +
                                                 "    }\n" +
                                                 "}", false));

    WorkflowRun b2 = job1.scheduleBuild2(0).waitForStart();
    SemaphoreStep.waitForStart("left/1", b2);
    SemaphoreStep.waitForStart("right/1", b2);

    resp = get("/organizations/jenkins/pipelines/pipeline1/runs/2/nodes/", List.class);

    Assert.assertEquals(5, resp.size());

    Map leftNode = resp.get(2);
    Assert.assertEquals("left", leftNode.get("displayName"));

    Map rightNode = resp.get(3);
    Assert.assertEquals("right", rightNode.get("displayName"));

    List<Map> leftSteps = get("/organizations/jenkins/pipelines/pipeline1/runs/2/nodes/" + leftNode.get("id") + "/steps/", List.class);

    Assert.assertEquals(3, leftSteps.size());

    List<Map> rightSteps = get("/organizations/jenkins/pipelines/pipeline1/runs/2/nodes/" + rightNode.get("id") + "/steps/", List.class);

    Assert.assertEquals(2, rightSteps.size());
}
 
Example #25
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 4 votes vote down vote up
@Test
public void lockOrderLabelQuantity() throws Exception {
  LockableResourcesManager.get().createResourceWithLabel("resource1", "label1");
  LockableResourcesManager.get().createResourceWithLabel("resource2", "label1");
  LockableResourcesManager.get().createResourceWithLabel("resource3", "label1");
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "lock(label: 'label1', quantity: 2) {\n"
              + "	semaphore 'wait-inside'\n"
              + "}\n"
              + "echo 'Finish'",
          true));
  WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
  SemaphoreStep.waitForStart("wait-inside/1", b1);

  WorkflowRun b2 = p.scheduleBuild2(0).waitForStart();
  // Ensure that b2 reaches the lock before b3
  j.waitForMessage("[Label: label1, Quantity: 2] is locked, waiting...", b2);
  j.waitForMessage("Found 1 available resource(s). Waiting for correct amount: 2.", b2);
  isPaused(b2, 1, 1);

  WorkflowJob p3 = j.jenkins.createProject(WorkflowJob.class, "p3");
  p3.setDefinition(
      new CpsFlowDefinition(
          "lock(label: 'label1', quantity: 1) {\n"
              + "	semaphore 'wait-inside-quantity1'\n"
              + "}\n"
              + "echo 'Finish'",
          true));
  WorkflowRun b3 = p3.scheduleBuild2(0).waitForStart();
  // While 2 continues waiting, 3 can continue directly
  SemaphoreStep.waitForStart("wait-inside-quantity1/1", b3);
  // Let 3 finish
  SemaphoreStep.success("wait-inside-quantity1/1", null);
  j.waitForMessage("Finish", b3);
  isPaused(b3, 1, 0);

  // Unlock Label: label1, Quantity: 2
  SemaphoreStep.success("wait-inside/1", null);
  j.waitForMessage("Lock released on resource [Label: label1, Quantity: 2]", b1);
  isPaused(b1, 1, 0);

  // #2 gets the lock before #3 (in the order as they requested the lock)
  j.waitForMessage("Lock acquired on [Label: label1, Quantity: 2]", b2);
  SemaphoreStep.success("wait-inside/2", null);
  j.waitForMessage("Finish", b2);
  isPaused(b2, 1, 0);

  assertNotNull(LockableResourcesManager.get().fromName("resource1"));
  assertNotNull(LockableResourcesManager.get().fromName("resource2"));
  assertNotNull(LockableResourcesManager.get().fromName("resource3"));
}
 
Example #26
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 4 votes vote down vote up
@Test
public void lockOrderLabel() throws Exception {
  LockableResourcesManager.get().createResourceWithLabel("resource1", "label1");
  LockableResourcesManager.get().createResourceWithLabel("resource2", "label1");
  LockableResourcesManager.get().createResourceWithLabel("resource3", "label1");
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "lock(label: 'label1', quantity: 2) {\n"
              + "	semaphore 'wait-inside'\n"
              + "}\n"
              + "echo 'Finish'",
          true));
  WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
  SemaphoreStep.waitForStart("wait-inside/1", b1);

  WorkflowRun b2 = p.scheduleBuild2(0).waitForStart();
  // Ensure that b2 reaches the lock before b3
  j.waitForMessage("[Label: label1, Quantity: 2] is locked, waiting...", b2);
  j.waitForMessage("Found 1 available resource(s). Waiting for correct amount: 2.", b2);
  isPaused(b2, 1, 1);
  WorkflowRun b3 = p.scheduleBuild2(0).waitForStart();
  // Both 2 and 3 are waiting for locking Label: label1, Quantity: 2
  j.waitForMessage("[Label: label1, Quantity: 2] is locked, waiting...", b3);
  j.waitForMessage("Found 1 available resource(s). Waiting for correct amount: 2.", b3);
  isPaused(b3, 1, 1);

  // Unlock Label: label1, Quantity: 2
  SemaphoreStep.success("wait-inside/1", null);
  j.waitForMessage("Lock released on resource [Label: label1, Quantity: 2]", b1);
  isPaused(b1, 1, 0);

  // #2 gets the lock before #3 (in the order as they requested the lock)
  j.waitForMessage("Lock acquired on [Label: label1, Quantity: 2]", b2);
  SemaphoreStep.success("wait-inside/2", null);
  j.waitForMessage("Finish", b2);
  isPaused(b2, 1, 0);
  j.waitForMessage("Lock acquired on [Label: label1, Quantity: 2]", b3);
  SemaphoreStep.success("wait-inside/3", null);
  j.waitForMessage("Finish", b3);
  isPaused(b3, 1, 0);

  assertNotNull(LockableResourcesManager.get().fromName("resource1"));
  assertNotNull(LockableResourcesManager.get().fromName("resource2"));
  assertNotNull(LockableResourcesManager.get().fromName("resource3"));
}
 
Example #27
Source File: LockStepHardKillTest.java    From lockable-resources-plugin with MIT License 4 votes vote down vote up
@Issue("JENKINS-40368")
@Test
public void hardKillWithWaitingRunsOnLabel() throws Exception {
  LockableResourcesManager.get().createResourceWithLabel("resource1", "label1");
  LockableResourcesManager.get().createResourceWithLabel("resource2", "label1");
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "retry(99) {\n"
              + "    lock(label: 'label1', quantity: 1) {\n"
              + "        semaphore('wait-inside')\n"
              + "     }\n"
              + "}",
          true));

  WorkflowRun firstPrev = null;
  WorkflowRun secondPrev = null;
  for (int i = 0; i < 3; i++) {
    WorkflowRun firstNext = p.scheduleBuild2(0).waitForStart();
    j.waitForMessage("Trying to acquire lock on", firstNext);
    WorkflowRun secondNext = p.scheduleBuild2(0).waitForStart();
    j.waitForMessage("Trying to acquire lock on", secondNext);

    if (firstPrev != null) {
      j.waitForMessage("is locked, waiting...", firstNext);
      isPaused(firstNext, 1, 1);
      j.waitForMessage("is locked, waiting...", secondNext);
      isPaused(secondNext, 1, 1);
    }

    interruptTermKill(firstPrev);
    j.waitForMessage("Lock acquired on ", firstNext);
    interruptTermKill(secondPrev);
    j.waitForMessage("Lock acquired on ", secondNext);

    SemaphoreStep.waitForStart("wait-inside/" + ((i * 2) + 1), firstNext);
    SemaphoreStep.waitForStart("wait-inside/" + ((i * 2) + 2), secondNext);
    isPaused(firstNext, 1, 0);
    isPaused(secondNext, 1, 0);
    firstPrev = firstNext;
    secondPrev = secondNext;
  }
  SemaphoreStep.success("wait-inside/5", null);
  SemaphoreStep.success("wait-inside/6", null);
  j.assertBuildStatus(Result.SUCCESS, j.waitForCompletion(firstPrev));
  j.assertBuildStatus(Result.SUCCESS, j.waitForCompletion(secondPrev));
}
 
Example #28
Source File: LockStepHardKillTest.java    From lockable-resources-plugin with MIT License 4 votes vote down vote up
@Issue("JENKINS-36479")
@Test
public void hardKillNewBuildClearsLock() throws Exception {
  LockableResourcesManager.get().createResource("resource1");

  WorkflowJob p1 = j.jenkins.createProject(WorkflowJob.class, "p");
  p1.setDefinition(
      new CpsFlowDefinition(
          "lock('resource1') { echo 'locked!'; semaphore 'wait-inside' }", true));
  WorkflowRun b1 = p1.scheduleBuild2(0).waitForStart();
  j.waitForMessage("locked!", b1);
  SemaphoreStep.waitForStart("wait-inside/1", b1);

  WorkflowJob p2 = j.jenkins.createProject(WorkflowJob.class, "p2");
  p2.setDefinition(
      new CpsFlowDefinition("lock('resource1') {\n" + "  semaphore 'wait-inside'\n" + "}", true));
  WorkflowRun b2 = p2.scheduleBuild2(0).waitForStart();

  // Make sure that b2 is blocked on b1's lock.
  j.waitForMessage("[resource1] is locked by " + b1.getFullDisplayName() + ", waiting...", b2);
  isPaused(b2, 1, 1);

  // Now b2 is still sitting waiting for a lock. Create b3 and launch it to clear the
  // lock.
  WorkflowJob p3 = j.jenkins.createProject(WorkflowJob.class, "p3");
  p3.setDefinition(
      new CpsFlowDefinition("lock('resource1') {\n" + "  semaphore 'wait-inside'\n" + "}", true));
  WorkflowRun b3 = p3.scheduleBuild2(0).waitForStart();
  j.waitForMessage("[resource1] is locked by " + b1.getFullDisplayName() + ", waiting...", b3);
  isPaused(b3, 1, 1);

  // Kill b1 hard.
  b1.doKill();
  j.waitForMessage("Hard kill!", b1);
  j.waitForCompletion(b1);
  j.assertBuildStatus(Result.ABORTED, b1);

  // Verify that b2 gets the lock.
  j.waitForMessage("Lock acquired on [resource1]", b2);
  SemaphoreStep.success("wait-inside/2", b2);
  // Verify that b2 releases the lock and finishes successfully.
  j.waitForMessage("Lock released on resource [resource1]", b2);
  j.assertBuildStatusSuccess(j.waitForCompletion(b2));
  isPaused(b2, 1, 0);

  // Now b3 should get the lock and do its thing.
  j.waitForMessage("Lock acquired on [resource1]", b3);
  SemaphoreStep.success("wait-inside/3", b3);
  j.assertBuildStatusSuccess(j.waitForCompletion(b3));
  isPaused(b3, 1, 0);
}
 
Example #29
Source File: PipelineApiTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test
public void getPipelineRunStopTest() throws Exception {
    WorkflowJob job1 = j.jenkins.createProject(WorkflowJob.class, "pipeline1");

    job1.setDefinition(new CpsFlowDefinition("" +
        "node {" +
        "   stage ('Build'); " +
        "   semaphore 's' " +
        "   stage ('Test'); " +
        "   echo ('Testing'); " +
        "}", false));

    WorkflowRun b1 = job1.scheduleBuild2(0).waitForStart();
    SemaphoreStep.waitForStart("s/1", b1);
    Map r = null;
    for (int i = 0; i < 10; i++) {
         r = request().put("/organizations/jenkins/pipelines/pipeline1/runs/1/stop")
            .build(Map.class);
         if(((String) r.get("state")).equals("FINISHED"))
            break;
        Thread.sleep(1000);
    }
    Assert.assertEquals(r.get("state"), "FINISHED");
    Assert.assertEquals(r.get("result"), "ABORTED");

    j.assertBuildStatus(Result.ABORTED, b1);

    FreeStyleProject p = j.createFreeStyleProject("pipeline5");
    p.getBuildersList().add(new Shell("echo hello!\nsleep 69"));
    FreeStyleBuild b2 = p.scheduleBuild2(0).waitForStart();

    for (int i = 0; i < 10; i++) {
        r = put("/organizations/jenkins/pipelines/pipeline5/runs/1/stop",null);
        if(((String) r.get("state")).equals("FINISHED"))
            break;
        Thread.sleep(1000);
    }
    Assert.assertEquals(r.get("state"), "FINISHED");
    Assert.assertEquals(r.get("result"), "ABORTED");
    j.assertBuildStatus(Result.ABORTED, b2);

}