public static BuildInfo getLastUnstableBuild(
      Job<?, ?> job,
      Locale locale,
      boolean isUnstableShownOnlyIfLast,
      boolean isShowColorblindUnderlineHint,
      boolean isFirst,
      TimeAgoType timeAgoType) {
    Run<?, ?> lastUnstable = job.getLastUnstableBuild();
    if (lastUnstable == null) {
      return null;
    }

    Run<?, ?> lastCompleted = job.getLastCompletedBuild();
    boolean isLastCompleted =
        (lastCompleted != null && lastCompleted.number == lastUnstable.number);
    if (isUnstableShownOnlyIfLast && !isLastCompleted) {
      return null;
    }

    return createBuildInfo(
        lastUnstable,
        BuildInfo.UNSTABLE_COLOR,
        UNSTABLE_UNDERLINE_STYLE,
        getUnstableMessage(),
        String.valueOf(lastUnstable.number),
        job,
        locale,
        isShowColorblindUnderlineHint,
        isFirst,
        timeAgoType);
  }
 private static BuildInfo createBuildInfo(
     Run<?, ?> run,
     String color,
     String underlineStyle,
     String status,
     String urlPart,
     Job<?, ?> job,
     Locale locale,
     boolean isShowColorblindUnderlineHint,
     boolean isFirst,
     TimeAgoType timeAgoType) {
   if (run != null) {
     long buildTime = run.getTime().getTime();
     if (urlPart == null) {
       urlPart = String.valueOf(run.number);
     }
     Run<?, ?> latest = job.getLastCompletedBuild();
     if (latest == null) {
       latest = job.getLastBuild();
     }
     if (!isShowColorblindUnderlineHint) {
       underlineStyle = null;
     }
     BuildInfo build =
         new BuildInfo(
             run, color, underlineStyle, buildTime, status, urlPart, run.number == latest.number);
     return build;
   }
   return null;
 }
  @SuppressWarnings("rawtypes")
  public void doQueryRuns(
      StaplerRequest request,
      StaplerResponse response,
      @QueryParameter("oslc.where") String where,
      @QueryParameter("oslc.prefix") String prefixes)
      throws IOException, URISyntaxException {
    requireGET();
    WhereClause whereClause = null;
    if (where != null) {
      whereClause = parseWhere(where, prefixes);
    }

    Collection<Job> jobs = Hudson.getInstance().getItems(Job.class);
    ArrayList<AutomationResult> results = new ArrayList<AutomationResult>();

    for (Job<?, ?> job : jobs) {
      if (jobMatchesRunWhereClause(request, job, whereClause)) {
        Iterator<?> i = job.getBuilds().iterator();
        while (i.hasNext()) {
          Run<?, ?> run = (Run<?, ?>) i.next();
          results.add(toAutomationResult(request, job, run));
        }
      }
    }

    marshalQueryResult(request, response, results);
  }
Пример #4
0
  /** If the command is currently running inside a build, return it. Otherwise null. */
  protected Run optCurrentlyBuilding() throws CmdLineException {
    try {
      CLICommand c = CLICommand.getCurrent();
      if (c == null) throw new IllegalStateException("Not executing a CLI command");
      String[] envs = c.checkChannel().call(new GetCharacteristicEnvironmentVariables());

      if (envs[0] == null || envs[1] == null) return null;

      Job j = Jenkins.getInstance().getItemByFullName(envs[0], Job.class);
      if (j == null) throw new CmdLineException("No such job: " + envs[0]);

      try {
        Run r = j.getBuildByNumber(Integer.parseInt(envs[1]));
        if (r == null) throw new CmdLineException("No such build #" + envs[1] + " in " + envs[0]);
        if (!r.isBuilding()) {
          throw new CmdLineException(r + " is not currently being built");
        }
        return r;
      } catch (NumberFormatException e) {
        throw new CmdLineException("Invalid build number: " + envs[1]);
      }
    } catch (IOException e) {
      throw new CmdLineException("Failed to identify the build being executed", e);
    } catch (InterruptedException e) {
      throw new CmdLineException("Failed to identify the build being executed", e);
    }
  }
Пример #5
0
  /**
   * Summarize the last test results from the passed set of jobs, including the packages of the job.
   * If a job doesn't include any tests, add a 0 summary.
   *
   * @param jobs
   * @return
   */
  public static TestResultSummary getDetailedTestResultSummary(Collection<TopLevelItem> jobs) {
    TestResultSummary summary = new TestResultSummary();

    for (TopLevelItem item : jobs) {
      if (item instanceof Job) {
        Job job = (Job) item;

        // create summary for the last run
        Run run = job.getLastBuild();
        if (run != null) {
          TestResult testResult = TestUtil.getTestResult(job.getLastBuild());
          summary.addTestResult(testResult);

          AbstractTestResultAction tra = run.getAction(AbstractTestResultAction.class);

          if (tra != null) {
            if (tra.getResult() instanceof MetaTabulatedResult) {
              MetaTabulatedResult result = (MetaTabulatedResult) tra.getResult();

              // add test results for the packages
              for (hudson.tasks.test.TestResult child : result.getChildren()) {
                PackageResult sub =
                    new PackageResult(
                        child, child.getTotalCount(), child.getFailCount(), child.getSkipCount());
                testResult.getPackageResults().add(sub);
              }
            }
          }
        }
      }
    }

    return summary;
  }
 /**
  * @param onlyIfLastCompleted When the statuses aren't sorted, we only show the last failed when
  *     it is also the latest completed build.
  */
 public static BuildInfo getLastFailedBuild(
     Job<?, ?> job,
     Locale locale,
     boolean onlyIfLastCompleted,
     boolean isShowColorblindUnderlineHint,
     boolean isFirst,
     TimeAgoType timeAgoType) {
   Run<?, ?> lastFailedBuild = job.getLastFailedBuild();
   Run<?, ?> lastCompletedBuild = job.getLastCompletedBuild();
   if (lastFailedBuild == null) {
     return null;
   } else if (!onlyIfLastCompleted || (lastCompletedBuild.number == lastFailedBuild.number)) {
     return createBuildInfo(
         job.getLastFailedBuild(),
         BuildInfo.FAILED_COLOR,
         FAILED_UNDERLINE_STYLE,
         getFailedMessage(),
         "lastFailedBuild",
         job,
         locale,
         isShowColorblindUnderlineHint,
         isFirst,
         timeAgoType);
   } else {
     return null;
   }
 }
  public Object revert(Object o) {
    String id = (String) o;
    int hash = id.lastIndexOf('#');
    String jobName = id.substring(0, hash);
    String runNumber = id.substring(hash + 1);
    Job<?, ?> job = (Job<?, ?>) Hudson.getInstance().getItem(jobName);
    Run<?, ?> run = job.getBuildByNumber(Integer.parseInt(runNumber));

    return run;
  }
  /**
   * Get JaCoCo coverage results of all jobs and store into a sorted HashMap by date.
   *
   * @param jobs jobs of Dashboard view
   * @param daysNumber number of days
   * @return Map The sorted summaries
   */
  public static Map<LocalDate, JacocoCoverageResultSummary> loadChartDataWithinRange(
      List<Job> jobs, int daysNumber) {

    Map<LocalDate, JacocoCoverageResultSummary> summaries =
        new HashMap<LocalDate, JacocoCoverageResultSummary>();

    // Get the last build (last date) of the all jobs
    LocalDate lastDate = Utils.getLastDate(jobs);

    // No builds
    if (lastDate == null) {
      return null;
    }

    // Get the first date from last build date minus number of days
    LocalDate firstDate = lastDate.minusDays(daysNumber);

    // For each job, get JaCoCo coverage results according with
    // date range (last build date minus number of days)
    for (Job<?, ?> job : jobs) {

      Run<?, ?> run = job.getLastCompletedBuild();

      if (null != run) {
        LocalDate runDate = new LocalDate(run.getTimestamp());

        while (runDate.isAfter(firstDate)) {

          summarize(summaries, run, runDate, job);

          run = run.getPreviousBuild();
          while (run != null && run.isBuilding()) {
            run = run.getPreviousBuild();
          }

          if (null == run) {
            break;
          }

          runDate = new LocalDate(run.getTimestamp());
        }
      }
    }

    // Sorting by date, ascending order
    Map<LocalDate, JacocoCoverageResultSummary> sortedSummaries =
        new TreeMap<LocalDate, JacocoCoverageResultSummary>(summaries);

    return sortedSummaries;
  }
Пример #9
0
  /**
   * Summarize the last test results from the passed set of jobs. If a job doesn't include any
   * tests, add a 0 summary.
   *
   * @param jobs
   * @return
   */
  public static TestResultSummary getTestResultSummary(Collection<TopLevelItem> jobs) {
    TestResultSummary summary = new TestResultSummary();

    for (TopLevelItem item : jobs) {
      if (item instanceof Job) {
        Job job = (Job) item;
        boolean addBlank = true;
        TestResultProjectAction testResults = job.getAction(TestResultProjectAction.class);

        if (testResults != null) {
          AbstractTestResultAction tra = testResults.getLastTestResultAction();

          if (tra != null) {
            addBlank = false;
            summary.addTestResult(
                new TestResult(job, tra.getTotalCount(), tra.getFailCount(), tra.getSkipCount()));
          }
        } else {
          SurefireAggregatedReport surefireTestResults =
              job.getAction(SurefireAggregatedReport.class);
          if (surefireTestResults != null) {
            addBlank = false;
            summary.addTestResult(
                new TestResult(
                    job,
                    surefireTestResults.getTotalCount(),
                    surefireTestResults.getFailCount(),
                    surefireTestResults.getSkipCount()));
          }
        }

        if (addBlank) {
          Run run = job.getLastBuild();
          if (run != null) {
            TestResult testResult = getTestResult(run);
            if (testResult != null) {
              addBlank = false;
              summary.addTestResult(testResult);
            }
          }
        }

        if (addBlank) {
          summary.addTestResult(new TestResult(job, 0, 0, 0));
        }
      }
    }

    return summary;
  }
    /** Erase aliases from newly created projects by copying. */
    @Override
    public void onCopied(Item src, Item item) {
      if (!(item instanceof Job)) return;

      Job<?, ?> job = (Job<?, ?>) item;
      PermalinkStorage storage = job.getProperty(PermalinkStorage.class);
      if (storage == null) return;

      try {
        job.removeProperty(storage);
      } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, "Unable to erase aliases when coppying " + item.getFullName(), ex);
      }
    }
Пример #11
0
 @Issue("JENKINS-27441")
 @Test
 public void getLogReturnsAnEmptyListWhenCalledWith0() throws Exception {
   Job j = Mockito.mock(Job.class);
   File tempBuildDir = tmp.newFolder();
   Mockito.when(j.getBuildDir()).thenReturn(tempBuildDir);
   Run<? extends Job<?, ?>, ? extends Run<?, ?>> r = new Run(j, 0) {};
   File f = r.getLogFile();
   f.getParentFile().mkdirs();
   PrintWriter w = new PrintWriter(f, "utf-8");
   w.println("dummy");
   w.close();
   List<String> logLines = r.getLog(0);
   assertTrue(logLines.isEmpty());
 }
Пример #12
0
  /**
   * Returns true if any of the builds recorded in this fingerprint is still retained.
   *
   * <p>This is used to find out old fingerprint records that can be removed without losing too much
   * information.
   */
  public synchronized boolean isAlive() {
    if (original != null && original.isAlive()) return true;

    for (Entry<String, RangeSet> e : usages.entrySet()) {
      Job j = Jenkins.getInstance().getItemByFullName(e.getKey(), Job.class);
      if (j == null) continue;

      Run firstBuild = j.getFirstBuild();
      if (firstBuild == null) continue;

      int oldest = firstBuild.getNumber();
      if (!e.getValue().isSmallerThan(oldest)) return true;
    }
    return false;
  }
Пример #13
0
  /*
   * Convert a Hudson Job to an OSLC AutomationPlan
   */
  public AutomationPlan toAutomationPlan(Job<?, ?> job) throws URISyntaxException {
    StaplerRequest request = Stapler.getCurrentRequest();
    AutomationPlan plan = new AutomationPlan();
    plan.setAbout(getJobURI(job));
    plan.setTitle(job.getDisplayName());
    plan.setDescription(job.getDescription());
    plan.setServiceProvider(getProviderURI());

    if (job instanceof AbstractProject) {
      AbstractProject<?, ?> project = (AbstractProject<?, ?>) job;
      fillInParameters(request, plan, project);
    }

    return plan;
  }
Пример #14
0
  private AutomationResult toAutomationResult(StaplerRequest request, Job<?, ?> job, Run<?, ?> run)
      throws URISyntaxException {
    AutomationResult result = new AutomationResult();
    result.setAbout(getRunURI(job, run));
    result.setIdentifier(run.getId());
    result.setServiceProvider(getProviderURI());
    result.setTitle(run.getFullDisplayName());

    Result hudsonResult = run.getResult();
    if (hudsonResult == Result.SUCCESS) {
      result.addState(new URI(AutomationConstants.STATE_COMPLETE));
      result.addVerdict(new URI(AutomationConstants.VERDICT_PASSED));
    } else if (hudsonResult == Result.FAILURE) {
      result.addState(new URI(AutomationConstants.STATE_COMPLETE));
      result.addVerdict(new URI(AutomationConstants.VERDICT_FAILED));
    } else if (hudsonResult == Result.NOT_BUILT) {
      result.addState(new URI(AutomationConstants.STATE_CANCELED));
    } else if (hudsonResult == Result.ABORTED) {
      result.addState(new URI(AutomationConstants.STATE_CANCELED));
    } else if (hudsonResult == Result.UNSTABLE) {
      result.addState(new URI(AutomationConstants.STATE_COMPLETE));
      result.addVerdict(new URI(AutomationConstants.VERDICT_WARNING));
    }

    URI jobURI = getJobURI(job);
    Link jobLink = new Link(jobURI, job.getDisplayName());
    result.setReportsOnAutomationPlan(jobLink);

    return result;
  }
Пример #15
0
 public static EVMViewBean getCurrentPVACEV(Job<?, ?> project) {
   final Run<?, ?> tb = project.getLastSuccessfulBuild();
   Run<?, ?> b = project.getLastBuild();
   while (b != null) {
     ProjectSummaryAction a =
         PMUtils.findActionByUrlEndsWith(b, ProjectSummaryAction.class, PMConstants.BASE);
     if (a != null) return a.getCurrentPVACEV();
     if (b == tb)
       // if even the last successful build didn't produce the test
       // result,
       // that means we just don't have any tests configured.
       return null;
     b = b.getPreviousBuild();
   }
   return null;
 }
Пример #16
0
  /**
   * @param project
   * @param commitSHA1
   * @return
   */
  private Run getBuildBySHA1(Job project, String commitSHA1, boolean triggeredByMergeRequest) {
    List<Run> builds = project.getBuilds();
    for (Run build : builds) {
      BuildData data = build.getAction(BuildData.class);
      MergeRecord mergeRecord = build.getAction(MergeRecord.class);
      if (mergeRecord == null) {
        // Determine if build was triggered by a Merge Request event
        ParametersAction params = build.getAction(ParametersAction.class);

        if (params == null) continue;

        StringParameterValue sourceBranch =
            (StringParameterValue) params.getParameter("gitlabSourceBranch");
        StringParameterValue targetBranch =
            (StringParameterValue) params.getParameter("gitlabTargetBranch");
        boolean isMergeRequestBuild =
            (sourceBranch != null && !sourceBranch.value.equals(targetBranch.value));

        if (!triggeredByMergeRequest) {
          if (isMergeRequestBuild)
            // skip Merge Request builds
            continue;

          if (data.getLastBuiltRevision().getSha1String().contains(commitSHA1)) {
            return build;
          }
        } else {
          if (!isMergeRequestBuild)
            // skip Push builds
            continue;

          if (hasBeenBuilt(data, ObjectId.fromString(commitSHA1), build)) {
            return build;
          }
        }

      } else {
        Build b = data.lastBuild;
        boolean isMergeBuild =
            mergeRecord != null && !mergeRecord.getSha1().equals(b.getMarked().getSha1String());
        if (b != null
            && b.getMarked() != null
            && b.getMarked().getSha1String().equals(commitSHA1)) {
          if (triggeredByMergeRequest == isMergeBuild) {
            LOGGER.log(
                Level.FINE,
                build.getNumber()
                    + " Build found matching "
                    + commitSHA1
                    + " "
                    + (isMergeBuild ? "merge" : "normal")
                    + " build");
            return build;
          }
        }
      }
    }
    return null;
  }
Пример #17
0
 private URI getRunURI(Job<?, ?> job, Run<?, ?> run) {
   return getBaseUriBuilder()
       .path(PATH_JOB)
       .path(job.getName())
       .path(PATH_RUN)
       .path("" + run.getNumber())
       .build();
 }
Пример #18
0
 /**
  * Converts the Hudson build status to CruiseControl build status, which is either Success,
  * Failure, Exception, or Unknown.
  */
 public static String toCCStatus(Item i) {
   if (i instanceof Job) {
     Job j = (Job) i;
     switch (j.getIconColor().noAnime()) {
       case ABORTED:
       case RED:
       case YELLOW:
         return "Failure";
       case BLUE:
         return "Success";
       case DISABLED:
       case GREY:
         return "Unknown";
     }
   }
   return "Unknown";
 }
Пример #19
0
 private URI getAutoRequestURI(Job<?, ?> job, int buildNumber) {
   return getBaseUriBuilder()
       .path(PATH_JOB)
       .path(job.getName())
       .path(PATH_RUN)
       .path("" + buildNumber)
       .path(PATH_REQUEST)
       .build();
 }
Пример #20
0
  /*
   * Handle the Compact representation of a job.
   */
  private void handleCompact(Job<?, ?> job) throws IOException, URISyntaxException {
    Compact c = new Compact();

    c.setAbout(getJobURI(job));
    c.setTitle(job.getFullDisplayName());

    String icon =
        Stapler.getCurrentRequest().getRootPath() + job.getBuildHealth().getIconUrl("16x16");
    c.setIcon(new URI(icon));

    Preview p = new Preview();
    p.setHintHeight("200px");
    p.setHintWidth("400px");
    p.setDocument(getJobPreviewURI(job));
    c.setSmallPreview(p);

    marshal(c);
  }
Пример #21
0
 public void doRssLatest(StaplerRequest req, StaplerResponse rsp)
     throws IOException, ServletException {
   List<Run> lastBuilds = new ArrayList<Run>();
   for (TopLevelItem item : getItems()) {
     if (item instanceof Job) {
       Job job = (Job) item;
       Run lb = job.getLastBuild();
       if (lb != null) lastBuilds.add(lb);
     }
   }
   RSS.forwardToRss(
       getDisplayName() + " last builds only",
       getUrl(),
       lastBuilds,
       Run.FEED_ADAPTER_LATEST,
       req,
       rsp);
 }
 public List<String> getValues(Job<?, ?> job) {
   List<String> values = new ArrayList<String>();
   PrioritySorterJobProperty prop = job.getProperty(PrioritySorterJobProperty.class);
   if (prop != null) {
     values.add(String.valueOf(prop.priority));
   } else {
     values.add(DEFAULT_PRIORITY);
   }
   return values;
 }
 public XmlFile getXmlFile(Job prj) {
   // default behaviour
   File rootDir = prj.getRootDir();
   File credentialFile = new File(rootDir, credentialsFileName);
   if (credentialFile.exists()) {
     return new XmlFile(credentialFile);
   }
   // matrix configuration project
   if (prj instanceof MatrixConfiguration && prj.getParent() != null) {
     ItemGroup parent = prj.getParent();
     if (parent instanceof Job) {
       return getXmlFile((Job) parent);
     }
   }
   if (prj.hasCascadingProject()) {
     return getXmlFile(prj.getCascadingProject());
   }
   return new XmlFile(new File(rootDir, credentialsFileName));
 }
Пример #24
0
  public void fireEvent(Run<?, ?> run, ReactorEvent event) {
    for (Job j : Jenkins.getInstance().getAllItems(Job.class)) {
      ReactorJobProperty rjp = (ReactorJobProperty) j.getProperty(ReactorJobProperty.class);
      if (rjp != null && !run.getParent().equals(j)) {
        StringScriptSource scriptSource = new StringScriptSource(rjp.reactorScript);

        ReactorGroovy rg = new ReactorGroovy(scriptSource);

        try {
          if (rg.perform(event)) {

            ((BuildableItem) j).scheduleBuild(new ReactorCause(event));
          }
        } catch (Exception ex) {
          ex.printStackTrace();
        }
      }
    }
  }
Пример #25
0
  private AutomationRequest toAutomationRequest(
      StaplerRequest request, Job<?, ?> job, Run<?, ?> run) {
    AutomationRequest autoRequest = new AutomationRequest(getAutoRequestURI(job, run));

    URI jobURI = getJobURI(job);
    Link jobLink = new Link(jobURI, job.getDisplayName());
    autoRequest.setExecutesAutomationPlan(jobLink);

    return autoRequest;
  }
Пример #26
0
  @Test
  public void getLogReturnsAllLines() throws Exception {
    Job j = Mockito.mock(Job.class);
    File tempBuildDir = tmp.newFolder();
    Mockito.when(j.getBuildDir()).thenReturn(tempBuildDir);
    Run<? extends Job<?, ?>, ? extends Run<?, ?>> r = new Run(j, 0) {};
    File f = r.getLogFile();
    f.getParentFile().mkdirs();
    PrintWriter w = new PrintWriter(f, "utf-8");
    w.print("a1\nb2\n\nc3");
    w.close();
    List<String> logLines = r.getLog(10);
    assertFalse(logLines.isEmpty());

    assertEquals("a1", logLines.get(0));
    assertEquals("b2", logLines.get(1));
    assertEquals("", logLines.get(2));
    assertEquals("c3", logLines.get(3));
  }
 public void compute(Job job) {
   List<Run> builds = job.getBuilds();
   for (Run build : builds) {
     // a build result can be null if the build is currently building (HUDSON-15067)
     if (build.getResult() != null) {
       if (build.getResult().isBetterOrEqualTo(Result.SUCCESS)) addSuccess();
       else if (build.getResult().isBetterOrEqualTo(Result.UNSTABLE)) addUnstable();
       else if (build.getResult().isBetterOrEqualTo(Result.FAILURE)) addFail();
     }
   }
 }
 private static Run<?, ?> getLastAbortedBuild(Job<?, ?> job) {
   Run<?, ?> latest = job.getLastBuild();
   int i = 0;
   while (latest != null && i++ < 20) {
     if (latest.getResult() == Result.ABORTED) {
       return latest;
     }
     latest = latest.getPreviousBuild();
   }
   return null;
 }
  private void renameJob(Job from, String to) throws IOException {
    LOGGER.info(format("Renaming job %s to %s", from.getFullName(), to));

    ItemGroup fromParent = from.getParent();
    ItemGroup toParent = lookupStrategy.getParent(build.getProject(), to);
    if (fromParent != toParent) {
      LOGGER.info(
          format("Moving Job %s to folder %s", fromParent.getFullName(), toParent.getFullName()));
      if (toParent instanceof DirectlyModifiableTopLevelItemGroup) {
        DirectlyModifiableTopLevelItemGroup itemGroup =
            (DirectlyModifiableTopLevelItemGroup) toParent;
        move(from, itemGroup);
      } else {
        throw new DslException(
            format(
                Messages.RenameJobMatching_DestinationNotFolder(),
                from.getFullName(),
                toParent.getFullName()));
      }
    }
    from.renameTo(FilenameUtils.getName(to));
  }
Пример #30
0
  @Test
  public void getLogReturnsAnRightOrder() throws Exception {
    Job j = Mockito.mock(Job.class);
    File tempBuildDir = tmp.newFolder();
    Mockito.when(j.getBuildDir()).thenReturn(tempBuildDir);
    Run<? extends Job<?, ?>, ? extends Run<?, ?>> r = new Run(j, 0) {};
    File f = r.getLogFile();
    f.getParentFile().mkdirs();
    PrintWriter w = new PrintWriter(f, "utf-8");
    for (int i = 0; i < 20; i++) {
      w.println("dummy" + i);
    }

    w.close();
    List<String> logLines = r.getLog(10);
    assertFalse(logLines.isEmpty());

    for (int i = 1; i < 10; i++) {
      assertEquals("dummy" + (10 + i), logLines.get(i));
    }
    assertEquals("[...truncated 68 B...]", logLines.get(0));
  }