public void testNativeMaven() throws Exception {
    MavenInstallation maven = configureDefaultMaven();
    String mavenPath = maven.getHome();
    Jenkins.getInstance()
        .getDescriptorByType(Maven.DescriptorImpl.class)
        .setInstallations(new MavenInstallation("maven", "THIS IS WRONG", NO_PROPERTIES));

    MavenModuleSet project = createMavenProject();
    project.setScm(new ExtractResourceSCM(getClass().getResource("/simple-projects.zip")));
    project.setAssignedLabel(slave.getSelfLabel());
    project.setJDK(jenkins.getJDK("default"));

    project.setMaven("maven");
    project.setGoals("clean");

    Run build = project.scheduleBuild2(0).get();
    assertBuildStatus(Result.FAILURE, build);

    ToolLocationNodeProperty property =
        new ToolLocationNodeProperty(
            new ToolLocationNodeProperty.ToolLocation(
                jenkins.getDescriptorByType(MavenInstallation.DescriptorImpl.class),
                "maven",
                mavenPath));
    slave.getNodeProperties().add(property);

    build = project.scheduleBuild2(0).get();
    System.out.println(build.getLog());
    assertBuildStatus(Result.SUCCESS, build);
  }
Пример #2
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;
  }
Пример #3
0
 public int compare(Run record, String key) {
   try {
     int k = Integer.parseInt(key);
     return record.getNumber() - k;
   } catch (NumberFormatException nfe) {
     return String.valueOf(record.getNumber()).compareTo(key);
   }
 }
Пример #4
0
 /**
  * Returns a Run object configured for the current row, or null if the current row is invalid.
  */
 public Run getRun() {
   if (isBeforeFirst() || isAfterLast()) return null;
   Run run = new Run();
   long runId = getLong(getColumnIndex(COLUMN_RUN_ID));
   run.setId(runId);
   long startDate = getLong(getColumnIndex(COLUMN_RUN_START_DATE));
   run.setStartDate(new Date(startDate));
   return run;
 }
Пример #5
0
 @Issue("JENKINS-15816")
 @SuppressWarnings({"unchecked", "rawtypes"})
 @Test
 public void timezoneOfID() throws Exception {
   TimeZone origTZ = TimeZone.getDefault();
   try {
     final Run r;
     String id;
     TimeZone.setDefault(TimeZone.getTimeZone("America/Chicago"));
     ExecutorService svc = Executors.newSingleThreadExecutor();
     try {
       r =
           svc.submit(
                   new Callable<Run>() {
                     @Override
                     public Run call() throws Exception {
                       return new Run(new StubJob(), 1234567890) {};
                     }
                   })
               .get();
       TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
       id = r.getId();
       assertEquals(
           id,
           svc.submit(
                   new Callable<String>() {
                     @Override
                     public String call() throws Exception {
                       return r.getId();
                     }
                   })
               .get());
     } finally {
       svc.shutdown();
     }
     TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
     svc = Executors.newSingleThreadExecutor();
     try {
       assertEquals(id, r.getId());
       assertEquals(
           id,
           svc.submit(
                   new Callable<String>() {
                     @Override
                     public String call() throws Exception {
                       return r.getId();
                     }
                   })
               .get());
     } finally {
       svc.shutdown();
     }
   } finally {
     TimeZone.setDefault(origTZ);
   }
 }
Пример #6
0
  public static void main(String[] args) {
    // boolean notRan = true;
    Run go = new Run();
    go.go();
    // SoundEffect.init();
    // SoundEffect.GONG.play();
    // System.out.println("WAIT FOR IT!");

    // SoundEffect.EXPLODE.play();

  }
Пример #7
0
  public void generateMergeRequestBuild(
      String json, Job project, StaplerRequest req, StaplerResponse rsp) {
    GitLabMergeRequest request = GitLabMergeRequest.create(json);
    if ("closed".equals(request.getObjectAttribute().getState())) {
      LOGGER.log(Level.INFO, "Closed Merge Request, no build started");
      return;
    }
    if ("merged".equals(request.getObjectAttribute().getState())) {
      LOGGER.log(Level.INFO, "Accepted Merge Request, no build started");
      return;
    }
    if ("update".equals(request.getObjectAttribute().getAction())) {
      LOGGER.log(
          Level.INFO,
          "Existing Merge Request, build will be trigged by buildOpenMergeRequests instead");
      return;
    }
    if (request.getObjectAttribute().getLastCommit() != null) {
      Run mergeBuild =
          getBuildBySHA1(project, request.getObjectAttribute().getLastCommit().getId(), true);
      if (mergeBuild != null) {
        LOGGER.log(
            Level.INFO,
            "Last commit in Merge Request has already been built in build #" + mergeBuild.getId());
        return;
      }
    }
    if (request.getObjectAttribute().getDescription().contains("[ci-skip]")) {
      LOGGER.log(
          Level.INFO,
          "Skipping MR " + request.getObjectAttribute().getTitle() + " due to ci-skip.");
      return;
    }

    Authentication old = SecurityContextHolder.getContext().getAuthentication();
    SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
    try {
      GitLabPushTrigger trigger = null;
      if (project instanceof ParameterizedJobMixIn.ParameterizedJob) {
        ParameterizedJobMixIn.ParameterizedJob p = (ParameterizedJobMixIn.ParameterizedJob) project;
        for (Trigger t : p.getTriggers().values()) {
          if (t instanceof GitLabPushTrigger) {
            trigger = (GitLabPushTrigger) t;
          }
        }
      }
      if (trigger == null) {
        return;
      }
      trigger.onPost(request);
    } finally {
      SecurityContextHolder.getContext().setAuthentication(old);
    }
  }
Пример #8
0
 @Override
 public String toString() {
   StringBuilder sb = new StringBuilder();
   PriorityQueue<Run> temp = new PriorityQueue<Run>();
   while (!runs.isEmpty()) {
     Run r = runs.poll();
     sb.append(r.toString()).append("\n\n");
     temp.offer(r);
   }
   runs = temp;
   return sb.toString();
 }
  /**
   * Consumes a run of characters at the limits of which we introduce a break.
   *
   * @param offset the offset to start at
   * @return the run that was consumed
   */
  private Run consumeRun(int offset) {
    // assert offset < length

    char ch = fText.charAt(offset);
    int length = fText.length();
    Run run = getRun(ch);
    while (run.consume(ch) && offset < length - 1) {
      offset++;
      ch = fText.charAt(offset);
    }

    return run;
  }
Пример #10
0
 private void redirectToBuildPage(StaplerResponse res, Run build) {
   if (build != null) {
     try {
       res.sendRedirect2(Jenkins.getInstance().getRootUrl() + build.getUrl());
     } catch (IOException e) {
       try {
         res.sendRedirect2(Jenkins.getInstance().getRootUrl() + build.getBuildStatusUrl());
       } catch (IOException e1) {
         e1.printStackTrace();
       }
     }
   }
 }
Пример #11
0
    public int compare(Run o1, Run o2) {
      if (o1 == null) {
        if (o2 == null) {
          return 0;
        } else {
          return -1;
        }
      }
      if (o2 == null) {
        return 1;
      }

      return ((Integer) o2.getNumber()).compareTo(o1.getNumber());
    }
Пример #12
0
 static String getStatusMessage(AbstractBuild r) {
   if (r.isBuilding()) {
     return "Starting...";
   }
   Result result = r.getResult();
   Run previousBuild = r.getProject().getLastBuild().getPreviousBuild();
   Result previousResult = (previousBuild != null) ? previousBuild.getResult() : Result.SUCCESS;
   if (result == Result.SUCCESS && previousResult == Result.FAILURE) return "Back to normal";
   if (result == Result.SUCCESS) return "Success";
   if (result == Result.FAILURE) return "Failure";
   if (result == Result.ABORTED) return "Aborted";
   if (result == Result.NOT_BUILT) return "Not built";
   if (result == Result.UNSTABLE) return "Unstable";
   return "Unknown";
 }
Пример #13
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;
  }
Пример #14
0
 @Test
 public void testGetFilesToCompileStarAfter() {
   mockGetInputPath();
   filesToCompile = Run.getFilesToCompile("input*");
   assertEquals(1, filesToCompile.size());
   assertEquals("InputFile.flow", filesToCompile.get(0));
 }
  /**
   * visit project chain, from current through parents.
   *
   * @param visitor
   * @param run
   */
  public static void traverseChain(HudsonVisitor visitor, Run run) {
    if (run == null) return;

    traverse(visitor, run);

    RepositoryAction repositoryAction = run.getAction(RepositoryAction.class);

    if (repositoryAction != null) {
      if (repositoryAction instanceof ProjectRepositoryAction) {
        final ProjectRepositoryAction projectRepositoryAction =
            (ProjectRepositoryAction) repositoryAction;

        AbstractProject item =
            (AbstractProject)
                Hudson.getInstance().getItem(projectRepositoryAction.getProjectName());

        Optional<Run> r =
            Iterables.tryFind(
                item.getBuilds(),
                new Predicate<Run>() {
                  public boolean apply(Run run) {
                    return run.getNumber() == projectRepositoryAction.getBuildNumber();
                  }
                });

        if (r.isPresent()) traverseChain(visitor, r.get());
      }
    }
  }
  /**
   * visit a run
   *
   * @param visitor
   * @param run
   */
  public static void traverse(HudsonVisitor visitor, Run run) {
    if (run instanceof MavenModuleSetBuild) {
      MavenModuleSetBuild item = (MavenModuleSetBuild) run;

      visitor.visitModuleSet(item);

      Map<MavenModule, List<MavenBuild>> modulesMap = item.getModuleBuilds();

      for (List<MavenBuild> builds : modulesMap.values()) {
        for (MavenBuild build : builds) {

          log.trace("Visit mavenBuild {}", build);

          visitor.visitBuild(build);

          MavenArtifactRecord artifacts = build.getAction(MavenArtifactRecord.class);
          if (artifacts != null) {
            visitMavenArtifactRecord(visitor, build, artifacts);
          }
        }
      }
    } else {

      RepositoryArtifactRecords records = run.getAction(RepositoryArtifactRecords.class);
      if (records != null) {
        for (RepositoryArtifactRecord record : records.recordList) {
          visitRepositoryRecord(visitor, run, record);
        }
      }
    }
  }
Пример #17
0
 @Test
 public void testGetFilesToCompileStarBefore() {
   mockGetInputPath();
   filesToCompile = Run.getFilesToCompile("*input");
   assertEquals(1, filesToCompile.size());
   assertEquals("myInputFileInput", filesToCompile.get(0));
 }
Пример #18
0
 public void doRssLatest(StaplerRequest req, StaplerResponse rsp)
     throws IOException, ServletException {
   final List<Run> lastBuilds = new ArrayList<Run>();
   for (final TopLevelItem item : Hudson.getInstance().getItems()) {
     if (!(item instanceof Job)) continue;
     for (Run r = ((Job) item).getLastBuild(); r != null; r = r.getPreviousBuild()) {
       if (!(r instanceof AbstractBuild)) continue;
       final AbstractBuild b = (AbstractBuild) r;
       if (b.hasParticipant(this)) {
         lastBuilds.add(b);
         break;
       }
     }
   }
   rss(req, rsp, " latest build", RunList.fromRuns(lastBuilds), Run.FEED_ADAPTER_LATEST);
 }
Пример #19
0
 @Test
 public void testGetOutput() {
   assertEquals("src/test/java/generatedtest/HTMLUnitGeneratedTest1.java", Run.getOutput(string1));
   assertEquals(
       "/src/test/java/generatedtest/HTMLUnitGeneratedTest2.java", Run.getOutput(string2));
   assertEquals("src/test/java/generatedtest/HTMLUnitGeneratedTest3.java", Run.getOutput(string3));
   assertEquals("HTMLUnitGeneratedTest4.java", Run.getOutput(string4));
   assertEquals("HTMLUnitGeneratedTest5.java", Run.getOutput(string5));
   assertEquals("/HTMLUnitGeneratedTest5.java", Run.getOutput(string6));
   assertEquals("one/HTMLUnitGeneratedTest5.java", Run.getOutput(string7));
   assertEquals("/one/HTMLUnitGeneratedTest5.java", Run.getOutput(string8));
   assertEquals("testspec/data/test_bbb.java", Run.getOutput(string9));
 }
Пример #20
0
  private void updateUI() {
    boolean started = mRunManager.isTrackingRun();

    if (mRun != null) mStartedTextView.setText(mRun.getStartDate().toString());

    int durationSeconds = 0;
    if (mLastLocation != null) {
      durationSeconds = mRun.getDurationSeconds(mLastLocation.getTime());
      mLatitudeTextView.setText(Double.toString(mLastLocation.getLatitude()));
      mLongitudeTextView.setText(Double.toString(mLastLocation.getLongitude()));
      mAltitudeTextView.setText(Double.toString(mLastLocation.getAltitude()));
    }
    mDurationTextView.setText(Run.formatDuration(durationSeconds));

    mStartButton.setEnabled(!started);
    mStopButton.setEnabled(started);
  }
Пример #21
0
  final void start() {
    workspace().register(this, _run);
    init(true, false);

    if (Debug.THREADS) ThreadAssert.exchangeGive(_run, this);

    _run.onStarted();
  }
Пример #22
0
 @Test
 public void testGetFilesToCompileStarMiddle() {
   mockGetInputPath();
   filesToCompile = Run.getFilesToCompile("my*.flow");
   assertEquals(2, filesToCompile.size());
   assertEquals("myInputFile.flow", filesToCompile.get(0));
   assertEquals("myOtherInputFileInput.flow", filesToCompile.get(1));
 }
  @Override
  public void queueJob(String jobName) throws JobNameNotProvidedException {
    validateJobNameArg(jobName);

    AbstractProject<?, ?> project =
        (AbstractProject<?, ?>) Jenkins.getInstance().getItemByFullName(jobName);

    if (build != null && build instanceof Run) {
      Run run = (Run) build;
      LOGGER.log(
          Level.INFO,
          String.format("Scheduling build of %s from %s", jobName, run.getParent().getName()));
      project.scheduleBuild(new Cause.UpstreamCause(run));
    } else {
      LOGGER.log(Level.INFO, String.format("Scheduling build of %s", jobName));
      project.scheduleBuild(new Cause.UserCause());
    }
  }
Пример #24
0
 /**
  * @param project
  * @param branch
  * @return latest build of the branch specified that is not part of a merge request
  */
 @SuppressWarnings("rawtypes")
 private Run getBuildByBranch(Job project, String branch) {
   RunList<?> builds = project.getBuilds();
   for (Run build : builds) {
     BuildData data = build.getAction(BuildData.class);
     if (data != null && data.lastBuild != null) {
       MergeRecord merge = build.getAction(MergeRecord.class);
       boolean isMergeBuild =
           merge != null && !merge.getSha1().equals(data.lastBuild.getMarked().getSha1String());
       if (data.lastBuild.getRevision() != null && !isMergeBuild) {
         for (Branch b : data.lastBuild.getRevision().getBranches()) {
           if (b.getName().endsWith("/" + branch)) return build;
         }
       }
     }
   }
   return null;
 }
Пример #25
0
  private void generateStatusJSON(
      String commitSHA1, Job project, StaplerRequest req, StaplerResponse rsp) {
    SCMTriggerItem item = SCMTriggerItems.asSCMTriggerItem(project);
    GitSCM gitSCM = getGitSCM(item);

    if (gitSCM == null) {
      throw new IllegalArgumentException("This repo does not use git.");
    }

    Run mainBuild = this.getBuildBySHA1(project, commitSHA1, true);

    JSONObject object = new JSONObject();
    object.put("sha", commitSHA1);

    if (mainBuild == null) {
      try {
        object.put("status", "pending");
        this.writeJSON(rsp, object);
        return;
      } catch (IOException e) {
        throw HttpResponses.error(500, "Could not generate response.");
      }
    }

    object.put("id", mainBuild.getNumber());

    Result res = mainBuild.getResult();

    // TODO: add status of pending when we figure it out.
    if (mainBuild.isBuilding()) {
      object.put("status", "running");
    } else if (res == Result.SUCCESS) {
      object.put("status", "success");
    } else {
      object.put("status", "failed");
    }

    try {
      this.writeJSON(rsp, object);
    } catch (IOException e) {
      throw HttpResponses.error(500, "Could not generate response.");
    }
  }
  public File getRunDir(Run run) {
    String runName = run.getName();
    if (runName == null) throw new IllegalArgumentException("Run doesn't have a name.");

    File runDir = new File(root, runName);

    if (!runDir.exists()) runDir.mkdir();

    return runDir;
  }
Пример #27
0
 private static ClaimBuildAction getClaimForRun(Run<?, ?> run) {
   ClaimBuildAction claimAction = null;
   List<ClaimBuildAction> claimActionList = run.getActions(ClaimBuildAction.class);
   if (claimActionList.size() == 1) {
     claimAction = claimActionList.get(0);
   } else if (claimActionList.size() > 1) {
     Log.warn("Multiple ClaimBuildActions found for job ");
   }
   return claimAction;
 }
Пример #28
0
  /*
   * Launches against the agent& main
   */
  public void testAgentAndMain() throws Exception {
    Project project = workspace.getProject("p1");
    Run bndrun = new Run(workspace, project.getBase(), project.getFile("one.bndrun"));
    bndrun.setProperty("-runpath", "biz.aQute.remote.launcher");
    bndrun.setProperty("-runbundles", "bsn-1,bsn-2");
    bndrun.setProperty("-runremote", "agent,main;agent=1090");

    final RemoteProjectLauncherPlugin pl =
        (RemoteProjectLauncherPlugin) bndrun.getProjectLauncher();
    pl.prepare();

    List<? extends RunSession> sessions = pl.getRunSessions();
    assertEquals(2, sessions.size());

    RunSession agent = sessions.get(0);
    RunSession main = sessions.get(1);

    CountDownLatch agentLatch = launch(agent);
    CountDownLatch mainLatch = launch(main);

    agent.waitTillStarted(1000);
    main.waitTillStarted(1000);
    Thread.sleep(500);

    agent.cancel();
    main.cancel();

    agentLatch.await();
    mainLatch.await();
    assertEquals(-3, agent.getExitCode());
    assertEquals(-3, main.getExitCode());

    bndrun.close();
  }
Пример #29
0
  public void populate(@NotNull AbstractProject project) {
    synchronized (populateLock) {
      Run lastBuild = project.getLastBuild();
      if (lastBuild == null) {
        return;
      }

      if (lastBuild.getNumber() <= oldest) {
        return;
      }

      for (int number = lastBuild.getNumber(); number > oldest; number--) {
        Run build = project.getBuildByNumber(number);
        if (build == null) {
          continue;
        }
        String externalizableId = build.getExternalizableId();

        size++;
        put("projectName", project.getName(), externalizableId);
        populateWithChangeInformation(build, externalizableId);
        populateWithCauseInformation(build, externalizableId);
        populateWithParameters(build, externalizableId);
      }

      oldest = lastBuild.getNumber();
    }
  }
Пример #30
0
  @Issue("JENKINS-26777")
  @SuppressWarnings({"unchecked", "rawtypes"})
  @Test
  public void getDurationString() throws IOException {
    LocaleProvider providerToRestore = LocaleProvider.getProvider();
    try {
      // This test expects English texts.
      LocaleProvider.setProvider(
          new LocaleProvider() {
            @Override
            public Locale get() {
              return Locale.ENGLISH;
            }
          });

      Run r = new Run(new StubJob(), 0) {};
      assertEquals("Not started yet", r.getDurationString());
      r.onStartBuilding();
      String msg;
      msg = r.getDurationString();
      assertTrue(msg, msg.endsWith(" and counting"));
      r.onEndBuilding();
      msg = r.getDurationString();
      assertFalse(msg, msg.endsWith(" and counting"));
    } finally {
      LocaleProvider.setProvider(providerToRestore);
    }
  }