示例#1
0
  @Test
  public void shouldFindTheLatestJobWhenJobStatusIsRequested() throws Exception {
    JobInstance job =
        JobInstanceMother.buildEndingWithState(JobState.Rescheduled, JobResult.Unknown, "config");
    job.assign("agent", new Date());

    JobInstance newJob =
        JobInstanceMother.buildEndingWithState(
            JobState.Building, JobResult.Unknown, "another_config");
    newJob.setId(2);
    newJob.assign("another_agent", new Date());

    String pipelineName = job.getPipelineName();
    String stageName = job.getStageName();

    when(jobInstanceService.buildByIdWithTransitions(job.getId())).thenReturn(job);
    when(jobDetailService.findMostRecentBuild(job.getIdentifier())).thenReturn(newJob);
    when(stageService.getBuildDuration(pipelineName, stageName, newJob))
        .thenReturn(new DurationBean(newJob.getId(), 5l));

    ModelAndView modelAndView =
        jobController.handleRequest(pipelineName, stageName, job.getId(), response);

    verify(jobInstanceService).buildByIdWithTransitions(job.getId());
    verify(jobDetailService).findMostRecentBuild(job.getIdentifier());
    verify(stageService).getBuildDuration(pipelineName, stageName, newJob);

    JsonValue json = from(((JsonList) modelAndView.getModel().get("json")).getJsonMap(0));

    JsonValue buildingInfo = json.getObject("building_info");

    assertThat(buildingInfo.getString("id"), is("2"));
    assertThat(buildingInfo.getString("last_build_duration"), is("5"));
  }
  @Test
  public void shouldNotReloadScheduledJobPlansWhenAgentWorkAssignmentIsInProgress()
      throws Exception {
    fixture.createPipelineWithFirstStageScheduled();
    Pipeline pipeline = pipelineDao.mostRecentPipeline(fixture.pipelineName);
    JobInstance job = pipeline.getFirstStage().getJobInstances().first();

    final JobInstanceService mockJobInstanceService = mock(JobInstanceService.class);

    final Pipeline pipeline1 = pipeline;
    final Semaphore sem = new Semaphore(1);
    sem.acquire();
    when(mockJobInstanceService.orderedScheduledBuilds())
        .thenReturn(jobInstanceService.orderedScheduledBuilds());
    when(mockJobInstanceService.buildByIdWithTransitions(job.getId()))
        .thenReturn(jobInstanceService.buildByIdWithTransitions(job.getId()));

    ScheduledPipelineLoader scheduledPipelineLoader =
        new ScheduledPipelineLoader(null, null, null, null, null, null, null, null) {
          @Override
          public Pipeline pipelineWithPasswordAwareBuildCauseByBuildId(long buildId) {
            sem.release();
            sleepQuietly(1000);
            verify(mockJobInstanceService, times(1)).orderedScheduledBuilds();
            return pipeline1;
          }
        };

    final BuildAssignmentService buildAssignmentServiceUnderTest =
        new BuildAssignmentService(
            goConfigService,
            mockJobInstanceService,
            scheduleService,
            agentService,
            environmentConfigService,
            timeProvider,
            transactionTemplate,
            scheduledPipelineLoader,
            pipelineService,
            builderFactory,
            agentRemoteHandler);

    final Throwable[] fromThread = new Throwable[1];
    buildAssignmentServiceUnderTest.onTimer();

    Thread assigner =
        new Thread(
            new Runnable() {
              public void run() {
                try {
                  final AgentConfig agentConfig =
                      AgentMother.localAgentWithResources("some-other-resource");

                  buildAssignmentServiceUnderTest.assignWorkToAgent(agent(agentConfig));
                } catch (Throwable e) {
                  e.printStackTrace();
                  fromThread[0] = e;
                } finally {

                }
              }
            },
            "assignmentThread");
    assigner.start();

    sem.acquire();
    buildAssignmentServiceUnderTest.onTimer();

    assigner.join();
    assertThat(fromThread[0], is(nullValue()));
  }
  @Test
  public void shouldSetAServerHealthMessageWhenMaterialForPipelineWithBuildCauseIsNotFound()
      throws IllegalArtifactLocationException, IOException {
    PipelineConfig pipelineConfig =
        PipelineConfigMother.pipelineConfig(
            "last",
            new StageConfig(
                new CaseInsensitiveString("stage"), new JobConfigs(new JobConfig("job-one"))));
    pipelineConfig.materialConfigs().clear();
    SvnMaterialConfig onDirOne =
        MaterialConfigsMother.svnMaterialConfig(
            "google.com", "dirOne", "loser", "boozer", false, "**/*.html");
    final P4MaterialConfig onDirTwo =
        MaterialConfigsMother.p4MaterialConfig(
            "host:987654321", "zoozer", "secret", "through-the-window", true);
    onDirTwo.setConfigAttributes(Collections.singletonMap(ScmMaterialConfig.FOLDER, "dirTwo"));
    pipelineConfig.addMaterialConfig(onDirOne);
    pipelineConfig.addMaterialConfig(onDirTwo);

    configHelper.addPipeline(pipelineConfig);

    Pipeline building = PipelineMother.building(pipelineConfig);
    final Pipeline pipeline = dbHelper.savePipelineWithMaterials(building);

    CruiseConfig cruiseConfig = configHelper.currentConfig();
    PipelineConfig cfg = cruiseConfig.pipelineConfigByName(new CaseInsensitiveString("last"));
    cfg.removeMaterialConfig(cfg.materialConfigs().get(1));
    configHelper.writeConfigFile(cruiseConfig);

    assertThat(
        serverHealthService.filterByScope(HealthStateScope.forPipeline("last")).size(), is(0));

    final long jobId = pipeline.getStages().get(0).getJobInstances().get(0).getId();

    Date currentTime = new Date(System.currentTimeMillis() - 1);
    Pipeline loadedPipeline =
        (Pipeline)
            transactionTemplate.execute(
                new TransactionCallback() {
                  public Object doInTransaction(TransactionStatus status) {
                    Pipeline loadedPipeline = null;
                    try {
                      loadedPipeline = loader.pipelineWithPasswordAwareBuildCauseByBuildId(jobId);
                      fail(
                          "should not have loaded pipeline with build-cause as one of the necessary materials was not found");
                    } catch (Exception e) {
                      assertThat(e, is(instanceOf(StaleMaterialsOnBuildCause.class)));
                      assertThat(
                          e.getMessage(),
                          is(
                              "Cannot load job 'last/"
                                  + pipeline.getCounter()
                                  + "/stage/1/job-one' because material "
                                  + onDirTwo
                                  + " was not found in config."));
                    }
                    return loadedPipeline;
                  }
                });

    assertThat(loadedPipeline, is(nullValue()));

    JobInstance reloadedJobInstance = jobInstanceService.buildById(jobId);
    assertThat(reloadedJobInstance.getState(), is(JobState.Completed));
    assertThat(reloadedJobInstance.getResult(), is(JobResult.Failed));

    assertThat(
        serverHealthService
            .filterByScope(HealthStateScope.forJob("last", "stage", "job-one"))
            .size(),
        is(1));
    ServerHealthState error =
        serverHealthService
            .filterByScope(HealthStateScope.forJob("last", "stage", "job-one"))
            .get(0);
    assertThat(
        error,
        is(
            ServerHealthState.error(
                "Cannot load job 'last/"
                    + pipeline.getCounter()
                    + "/stage/1/job-one' because material "
                    + onDirTwo
                    + " was not found in config.",
                "Job for pipeline 'last/"
                    + pipeline.getCounter()
                    + "/stage/1/job-one' has been failed as one or more material configurations were either changed or removed.",
                HealthStateType.general(HealthStateScope.forJob("last", "stage", "job-one")))));
    DateTime expiryTime = (DateTime) ReflectionUtil.getField(error, "expiryTime");
    assertThat(expiryTime.toDate().after(currentTime), is(true));
    assertThat(
        expiryTime.toDate().before(new Date(System.currentTimeMillis() + 5 * 60 * 1000 + 1)),
        is(true));

    String logText =
        FileUtil.readToEnd(consoleService.findConsoleArtifact(reloadedJobInstance.getIdentifier()));
    assertThat(
        logText,
        containsString(
            "Cannot load job 'last/"
                + pipeline.getCounter()
                + "/stage/1/job-one' because material "
                + onDirTwo
                + " was not found in config."));
    assertThat(
        logText,
        containsString(
            "Job for pipeline 'last/"
                + pipeline.getCounter()
                + "/stage/1/job-one' has been failed as one or more material configurations were either changed or removed."));
  }