Ejemplo n.º 1
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();
    }
  }
    /** Makes sure that the data fields are up to date. */
    private synchronized void upToDateCheck() {
      // up to date check
      if (lastUpdated > lastChanged) return;
      lastUpdated = lastChanged + 1;

      int failCount = 0;
      int totalCount = 0;
      List<AbstractTestResultAction> individuals = new ArrayList<AbstractTestResultAction>();
      List<AbstractProject> didntRun = new ArrayList<AbstractProject>();
      List<AbstractProject> noFingerprints = new ArrayList<AbstractProject>();
      for (AbstractProject job : getJobs()) {
        RangeSet rs = owner.getDownstreamRelationship(job);
        if (rs.isEmpty()) {
          // is this job expected to produce a test result?
          Run b;
          if (includeFailedBuilds) {
            b = job.getLastBuild();
          } else {
            b = job.getLastSuccessfulBuild();
          }
          if (b != null && b.getAction(AbstractTestResultAction.class) != null) {
            if (b.getAction(FingerprintAction.class) != null) {
              didntRun.add(job);
            } else {
              noFingerprints.add(job);
            }
          }
        } else {
          for (int n : rs.listNumbersReverse()) {
            Run b = job.getBuildByNumber(n);
            if (b == null) continue;
            Result targetResult;
            if (includeFailedBuilds) {
              targetResult = Result.FAILURE;
            } else {
              targetResult = Result.UNSTABLE;
            }

            if (b.isBuilding() || b.getResult().isWorseThan(targetResult))
              continue; // don't count them

            for (AbstractTestResultAction ta : b.getActions(AbstractTestResultAction.class)) {
              failCount += ta.getFailCount();
              totalCount += ta.getTotalCount();
              individuals.add(ta);
            }
            break;
          }
        }
      }

      this.failCount = failCount;
      this.totalCount = totalCount;
      this.individuals = individuals;
      this.didntRun = didntRun;
      this.noFingerprints = noFingerprints;
    }
Ejemplo n.º 3
0
  /** Invoked to actually tag the workspace. */
  public synchronized void doSubmit(StaplerRequest req, StaplerResponse rsp)
      throws IOException, ServletException {
    build.checkPermission(getPermission());

    Map<AbstractBuild, String> tagSet = new HashMap<AbstractBuild, String>();

    String name = fixNull(req.getParameter("name")).trim();
    String reason = isInvalidTag(name);
    if (reason != null) {
      sendError(reason, req, rsp);
      return;
    }

    tagSet.put(build, name);

    if (req.getParameter("upstream") != null) {
      // tag all upstream builds
      Enumeration e = req.getParameterNames();
      Map<AbstractProject, Integer> upstreams =
          build.getTransitiveUpstreamBuilds(); // TODO: define them at AbstractBuild level

      while (e.hasMoreElements()) {
        String upName = (String) e.nextElement();
        if (!upName.startsWith("upstream.")) {
          continue;
        }

        String tag = fixNull(req.getParameter(upName)).trim();
        reason = isInvalidTag(tag);
        if (reason != null) {
          sendError(
              hudson.scm.cvs.Messages.CVSSCM_NoValidTagNameGivenFor(upName, reason), req, rsp);
          return;
        }

        upName = upName.substring(9); // trim off 'upstream.'
        AbstractProject p = Hudson.getInstance().getItemByFullName(upName, AbstractProject.class);
        if (p == null) {
          sendError(hudson.scm.cvs.Messages.CVSSCM_NoSuchJobExists(upName), req, rsp);
          return;
        }

        Integer buildNum = upstreams.get(p);
        if (buildNum == null) {
          sendError(hudson.scm.cvs.Messages.CVSSCM_NoUpstreamBuildFound(upName), req, rsp);
          return;
        }

        Run build = p.getBuildByNumber(buildNum);
        tagSet.put((AbstractBuild) build, tag);
      }
    }

    new TagWorkerThread(this, tagSet).start();

    doIndex(req, rsp);
  }
  protected int run() throws Exception {
    Run run = job.getBuildByNumber(number);
    run.checkPermission(Run.UPDATE);

    if ("-".equals(displayName)) {
      displayName =
          channel.call(
              new Callable<String, IOException>() {
                public String call() throws IOException {
                  return IOUtils.toString(System.in);
                }
              });
    }

    run.setDisplayName(displayName);

    return 0;
  }
Ejemplo n.º 5
0
  /** Performs an installation. */
  private int install(ToolInstallation t, BuildIDs id, AbstractProject p)
      throws IOException, InterruptedException {

    Run b = p.getBuildByNumber(Integer.parseInt(id.number));
    if (b == null) throw new AbortException("No such build: " + id.number);

    Executor exec = b.getExecutor();
    if (exec == null) throw new AbortException(b.getFullDisplayName() + " is not building");

    Node node = exec.getOwner().getNode();
    if (node == null) {
      throw new AbortException(
          "The node " + exec.getOwner().getDisplayName() + " has been deleted");
    }

    t = t.translate(node, EnvVars.getRemote(checkChannel()), new StreamTaskListener(stderr));
    stdout.println(t.getHome());
    return 0;
  }
 public String getBuildParams(SubBuild subBuild) {
   AbstractProject project =
       (AbstractProject) Jenkins.getInstance().getItem(subBuild.getJobName());
   Run build = project.getBuildByNumber(subBuild.getBuildNumber());
   ParametersAction action = build.getAction(ParametersAction.class);
   List<ParameterValue> parameters = action.getParameters();
   StringBuffer buffer = new StringBuffer();
   for (ParameterValue parameterValue : parameters) {
     StringParameterValue stringParameter;
     try {
       stringParameter = ((StringParameterValue) parameterValue);
     } catch (Exception e) {
       continue;
     }
     String value = stringParameter.value;
     String name = stringParameter.getName();
     buffer
         .append("<input type='text' size='15' value='" + name + "' readonly/>")
         .append("&nbsp;")
         .append("<input type='text' size='35' value='" + value + "'/ readonly>")
         .append("</br>");
   }
   return buffer.toString();
 }
  private MimeMessage createMail(
      EmailType type, AbstractBuild<?, ?> build, BuildListener listener, EmailTrigger trigger)
      throws MessagingException, IOException, InterruptedException {
    boolean overrideGlobalSettings = ExtendedEmailPublisher.DESCRIPTOR.getOverrideGlobalSettings();

    MimeMessage msg;

    // If not overriding global settings, use the Mailer class to create a session and set the from
    // address
    // Else we'll do it ourselves
    if (!overrideGlobalSettings) {
      debug(
          listener.getLogger(),
          "NOT overriding default server settings, using Mailer to create session");
      msg = new MimeMessage(Mailer.descriptor().createSession());
      msg.setFrom(new InternetAddress(Mailer.descriptor().getAdminAddress()));
    } else {
      debug(listener.getLogger(), "Overriding default server settings, creating our own session");
      msg = new MimeMessage(ExtendedEmailPublisher.DESCRIPTOR.createSession());
      msg.setFrom(new InternetAddress(ExtendedEmailPublisher.DESCRIPTOR.getAdminAddress()));
    }

    String charset = Mailer.descriptor().getCharset();
    if (overrideGlobalSettings) {
      String overrideCharset = ExtendedEmailPublisher.DESCRIPTOR.getCharset();
      if (StringUtils.isNotBlank(overrideCharset)) {
        debug(listener.getLogger(), "Overriding charset %s", overrideCharset);
        charset = overrideCharset;
      }
    }

    // Set the contents of the email
    msg.addHeader("X-Jenkins-Job", build.getProject().getDisplayName());
    if (build.getResult() != null) {
      msg.addHeader("X-Jenkins-Result", build.getResult().toString());
    }
    msg.setSentDate(new Date());
    setSubject(type, build, msg, listener, charset);

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(getContent(type, build, listener, charset, trigger));

    AttachmentUtils attachments = new AttachmentUtils(attachmentsPattern);
    attachments.attach(multipart, this, build, listener);

    // add attachments from the email type if they are setup
    if (StringUtils.isNotBlank(type.getAttachmentsPattern())) {
      AttachmentUtils typeAttachments = new AttachmentUtils(type.getAttachmentsPattern());
      typeAttachments.attach(multipart, this, build, listener);
    }

    if (attachBuildLog || type.getAttachBuildLog()) {
      debug(listener.getLogger(), "Request made to attach build log");
      AttachmentUtils.attachBuildLog(
          multipart, build, listener, compressBuildLog || type.getCompressBuildLog());
    }

    msg.setContent(multipart);

    EnvVars env = null;
    try {
      env = build.getEnvironment(listener);
    } catch (Exception e) {
      listener.getLogger().println("Error retrieving environment vars: " + e.getMessage());
      // create an empty set of env vars
      env = new EnvVars();
    }

    // Get the recipients from the global list of addresses
    Set<InternetAddress> recipientAddresses = new LinkedHashSet<InternetAddress>();
    Set<InternetAddress> ccAddresses = new LinkedHashSet<InternetAddress>();
    if (type.getSendToRecipientList()) {
      debug(listener.getLogger(), "Adding recipients from recipient list");
      addAddressesFromRecipientList(
          recipientAddresses,
          ccAddresses,
          getRecipientList(type, build, recipientList, listener, charset),
          env,
          listener);
    }
    // Get the list of developers who made changes between this build and the last
    // if this mail type is configured that way
    if (type.getSendToDevelopers()) {
      debug(listener.getLogger(), "Adding developers");
      Set<User> users;
      if (type.getIncludeCulprits()) {
        users = build.getCulprits();
      } else {
        users = new HashSet<User>();
        for (Entry change : build.getChangeSet()) {
          users.add(change.getAuthor());
        }
      }

      for (User user : users) {
        if (!isExcludedCommitter(user.getFullName())) {
          String userAddress = EmailRecipientUtils.getUserConfiguredEmail(user);
          if (userAddress != null) {
            addAddressesFromRecipientList(
                recipientAddresses, ccAddresses, userAddress, env, listener);
          } else {
            listener
                .getLogger()
                .println(
                    "Failed to send e-mail to "
                        + user.getFullName()
                        + " because no e-mail address is known, and no default e-mail domain is configured");
          }
        }
      }
    }

    if (type.isSendToRequester()) {
      debug(listener.getLogger(), "Sending to requester");
      // looking for Upstream build.
      AbstractBuild<?, ?> cur = build;
      Cause.UpstreamCause upc = build.getCause(Cause.UpstreamCause.class);
      while (upc != null) {
        // UpstreamCause.getUpStreamProject() returns the full name, so use getItemByFullName
        AbstractProject<?, ?> p =
            (AbstractProject<?, ?>)
                Hudson.getInstance().getItemByFullName(upc.getUpstreamProject());
        cur = p.getBuildByNumber(upc.getUpstreamBuild());
        upc = cur.getCause(Cause.UpstreamCause.class);
      }
      addUserTriggeringTheBuild(cur, recipientAddresses, ccAddresses, env, listener);
    }

    // Get the list of recipients that are uniquely specified for this type of email
    if (StringUtils.isNotBlank(type.getRecipientList())) {
      addAddressesFromRecipientList(
          recipientAddresses,
          ccAddresses,
          getRecipientList(type, build, type.getRecipientList(), listener, charset),
          env,
          listener);
    }

    String emergencyReroute = ExtendedEmailPublisher.DESCRIPTOR.getEmergencyReroute();
    boolean isEmergencyReroute = StringUtils.isNotBlank(emergencyReroute);

    if (isEmergencyReroute) {
      debug(listener.getLogger(), "Emergency reroute turned on");
      recipientAddresses.clear();
      addAddressesFromRecipientList(
          recipientAddresses, ccAddresses, emergencyReroute, env, listener);
      listener.getLogger().println("Emergency reroute is set to: " + emergencyReroute);
    }

    msg.setRecipients(
        Message.RecipientType.TO,
        recipientAddresses.toArray(new InternetAddress[recipientAddresses.size()]));
    if (ccAddresses.size() > 0) {
      msg.setRecipients(
          Message.RecipientType.CC, ccAddresses.toArray(new InternetAddress[ccAddresses.size()]));
    }

    Set<InternetAddress> replyToAddresses = new LinkedHashSet<InternetAddress>();
    if (StringUtils.isNotBlank(replyTo)) {
      addAddressesFromRecipientList(
          replyToAddresses,
          null,
          getRecipientList(type, build, replyTo, listener, charset),
          env,
          listener);
    }

    if (StringUtils.isNotBlank(type.getReplyTo())) {
      addAddressesFromRecipientList(
          replyToAddresses,
          null,
          getRecipientList(type, build, type.getReplyTo(), listener, charset),
          env,
          listener);
    }

    if (replyToAddresses.size() > 0) {
      msg.setReplyTo(replyToAddresses.toArray(new InternetAddress[replyToAddresses.size()]));
    }

    AbstractBuild<?, ?> pb = build.getPreviousBuild();
    if (pb != null) {
      // Send mails as replies until next successful build
      MailMessageIdAction b = pb.getAction(MailMessageIdAction.class);
      if (b != null && pb.getResult() != Result.SUCCESS) {
        debug(listener.getLogger(), "Setting In-Reply-To since last build was not successful");
        msg.setHeader("In-Reply-To", b.messageId);
        msg.setHeader("References", b.messageId);
      }
    }

    if (CONTENT_TRANSFER_ENCODING != null) {
      msg.setHeader("Content-Transfer-Encoding", CONTENT_TRANSFER_ENCODING);
    }

    String listId = ExtendedEmailPublisher.DESCRIPTOR.getListId();
    if (listId != null) {
      msg.setHeader("List-ID", listId);
    }

    if (ExtendedEmailPublisher.DESCRIPTOR.getPrecedenceBulk()) {
      msg.setHeader("Precedence", "bulk");
    }

    return msg;
  }