/**
   * Actually build a project, passing in parameters where appropriate
   *
   * @param project
   * @return
   */
  protected final boolean performBuildProject(AbstractProject<?, ?> project) {
    if (!project.hasPermission(AbstractProject.BUILD)) {
      LOGGER.log(Level.WARNING, "Insufficient permission to build job '" + project.getName() + "'");
      return false;
    }

    if (action.equals(BuildAction.POLL_SCM)) {
      project.schedulePolling();
      return true;
    }

    // no user parameters provided, just build it
    if (param == null) {
      project.scheduleBuild(new Cause.UserIdCause());
      return true;
    }

    ParametersDefinitionProperty pp =
        (ParametersDefinitionProperty) project.getProperty(ParametersDefinitionProperty.class);

    // project does not except any parameters, just build it
    if (pp == null) {
      project.scheduleBuild(new Cause.UserIdCause());
      return true;
    }

    List<ParameterDefinition> parameterDefinitions = pp.getParameterDefinitions();
    List<ParameterValue> values = new ArrayList<ParameterValue>();

    for (ParameterDefinition paramDef : parameterDefinitions) {

      if (!(paramDef instanceof StringParameterDefinition)) {
        // TODO add support for other parameter types
        values.add(paramDef.getDefaultParameterValue());
        continue;
      }

      StringParameterDefinition stringParamDef = (StringParameterDefinition) paramDef;
      ParameterValue value;

      // Did user supply this parameter?
      if (param.containsKey(paramDef.getName())) {
        value = stringParamDef.createValue(param.get(stringParamDef.getName()));
      } else {
        // No, then use the default value
        value = stringParamDef.createValue(stringParamDef.getDefaultValue());
      }

      values.add(value);
    }

    Jenkins.getInstance().getQueue().schedule(pp.getOwner(), 1, new ParametersAction(values));
    return true;
  }
Beispiel #2
0
 public void run() {
   String threadName = Thread.currentThread().getName();
   Thread.currentThread().setName("SCM polling for " + job);
   try {
     startTime = System.currentTimeMillis();
     if (runPolling()) {
       AbstractProject p = job.asProject();
       String name = " #" + p.getNextBuildNumber();
       SCMTriggerCause cause;
       try {
         cause = new SCMTriggerCause(getLogFile());
       } catch (IOException e) {
         LOGGER.log(WARNING, "Failed to parse the polling log", e);
         cause = new SCMTriggerCause();
       }
       if (p.scheduleBuild(p.getQuietPeriod(), cause, additionalActions)) {
         LOGGER.info("SCM changes detected in " + job.getName() + ". Triggering " + name);
       } else {
         LOGGER.info(
             "SCM changes detected in " + job.getName() + ". Job is already in the queue");
       }
     }
   } finally {
     Thread.currentThread().setName(threadName);
   }
 }
  @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());
    }
  }
Beispiel #4
0
  public void doIndex(StaplerRequest req) throws IOException {
    String payload = IOUtils.toString(req.getReader());
    LOGGER.fine("Full details of the POST was " + payload);

    JSONObject o = JSONObject.fromObject(payload);
    String repoUrl = o.getString("repository_ssl_path");
    LOGGER.info("Received POST for " + repoUrl);

    // run in high privilege to see all the projects anonymous users don't see.
    // this is safe because when we actually schedule a build, it's a build that can
    // happen at some random time anyway.

    // TODO replace with ACL.impersonate as LTS is > 1.461
    Authentication old = SecurityContextHolder.getContext().getAuthentication();
    SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
    try {
      for (AbstractProject<?, ?> job : Jenkins.getInstance().getAllItems(AbstractProject.class)) {
        boolean found = false;
        SCM scm = job.getScm();
        if (scm instanceof SubversionSCM) {
          found = hasRepository(repoUrl, (SubversionSCM) scm);
        } else if (scm instanceof GitSCM) {
          found = hasRepository(repoUrl, (GitSCM) scm);
        } else if (scm instanceof MercurialSCM) {
          found = hasRepository(repoUrl, (MercurialSCM) scm);
        }

        if (found) {
          LOGGER.info(job.getFullDisplayName() + " triggered by web hook.");
          job.scheduleBuild(new WebHookCause());
        }

        LOGGER.fine(
            "Skipped "
                + job.getFullDisplayName()
                + " because it doesn't have a matching repository.");
      }
    } finally {
      SecurityContextHolder.getContext().setAuthentication(old);
    }
  }
Beispiel #5
0
  public synchronized void checkPendingDownstream(
      AbstractBuild<?, ?> owner, TaskListener listener) {
    if (pendingDownstreamProjects.isEmpty()) {
      listener.getLogger().println("All downstream projects complete!");
      Result threshold = this.evenIfDownstreamUnstable ? Result.UNSTABLE : Result.SUCCESS;
      if (this.overallResult.isWorseThan(threshold)) {
        listener.getLogger().println("Minimum result threshold not met for join project");
      } else {
        // Construct a launcher since CopyArchiver wants to get the
        // channel from it. We use the channel of the node where the
        // splitProject was built on.
        final Launcher launcher = new NoopLauncher(listener, owner);

        for (Publisher pub : this.joinPublishers) {
          try {
            pub.perform(owner, launcher, (BuildListener) listener);
          } catch (InterruptedException e) {
            e.printStackTrace();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        if (!JoinTrigger.canDeclare(owner.getProject())) {
          List<AbstractProject> projects = Items.fromNameList(joinProjects, AbstractProject.class);
          for (AbstractProject project : projects) {
            listener.getLogger().println("Scheduling join project: " + project.getName());
            project.scheduleBuild(new JoinCause(owner));
          }
        }
      }
    } else {
      listener
          .getLogger()
          .println(
              "Project "
                  + owner.getProject().getName()
                  + " still waiting for "
                  + pendingDownstreamProjects.size()
                  + " builds to complete");
    }
  }
  /**
   * @deprecated since 2.3 with Hudson 1.341+ (see {@link
   *     BuildTrigger#buildDependencyGraph(AbstractProject, hudson.model.DependencyGraph)})
   */
  @Deprecated
  public void perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
      throws InterruptedException, IOException {

    try {
      if (condition.isMet(build.getResult())) {
        List<Action> actions = getBaseActions(build, listener);
        if (!actions.isEmpty()) {
          for (AbstractProject project : getProjectList()) {
            List<Action> list = getBuildActions(actions, project);

            project.scheduleBuild(
                project.getQuietPeriod(),
                new Cause.UpstreamCause((Run) build),
                list.toArray(new Action[list.size()]));
          }
        }
      }
    } catch (DontTriggerException e) {
      // don't trigger on this configuration
      return;
    }
  }
  /*
   * Path: /auto/scheduleBuild
   *
   * POST to create automation requests to schedule builds.
   */
  public void doScheduleBuild(StaplerRequest request, StaplerResponse response) throws Exception {
    requirePOST();

    OSLC4JUnmarshaller unmarshaller = OSLC4JContext.newInstance().createUnmarshaller();

    String contentType = request.getContentType();
    if (contentType == null) {
      throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
    }
    unmarshaller.setMediaType(MediaType.valueOf(contentType));

    final AutomationRequest autoRequest =
        unmarshaller.unmarshal(request.getInputStream(), AutomationRequest.class);
    if (autoRequest == null) {
      throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
    }

    Link planLink = autoRequest.getExecutesAutomationPlan();
    if (planLink == null) {
      throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
    }

    URI planURI = planLink.getValue();
    String jobName = getJobNameFromURI(planURI);
    if (jobName == null) {
      throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
    }

    Job<?, ?> job = getJob(jobName);
    if (job == null) {
      throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
    }

    if (!job.isBuildable()) {
      throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
    }

    if (!(job instanceof AbstractProject)) {
      LOG.log(
          Level.WARNING,
          "Cannot schedule builds for jobs that don't extend AbstractProject: " + jobName);
      throw HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
    }

    AbstractProject<?, ?> project = (AbstractProject<?, ?>) job;
    int nextBuildNumber = project.getNextBuildNumber();
    Cause cause =
        new Cause() {
          @Override
          public String getShortDescription() {
            String description = autoRequest.getDescription();
            return description != null ? description : "OSLC Automation Request";
          }
        };

    ParameterInstance[] parameters = autoRequest.getInputParameters();
    boolean suceeded;
    if (parameters.length == 0) {
      suceeded = project.scheduleBuild(cause);
    } else {
      List<ParameterValue> values = getParameterValues(project, parameters);
      suceeded =
          project.scheduleBuild2(project.getQuietPeriod(), cause, new ParametersAction(values))
              != null;
    }

    if (!suceeded) {
      // Build already queued.
      LOG.log(
          Level.WARNING,
          "Automation request rejected (409 conflict) since build is already queued: " + jobName);
      throw HttpResponses.status(HttpServletResponse.SC_CONFLICT);
    }

    URI requestURI = getAutoRequestURI(job, nextBuildNumber);
    response.setStatus(HttpServletResponse.SC_CREATED);
    response.setHeader("Location", requestURI.toString());
  }