/** {@inheritDoc} */
 @Override
 public boolean isSelectable(Run<?, ?> run, EnvVars env) {
   EnvVars otherEnv;
   try {
     otherEnv = run.getEnvironment(TaskListener.NULL);
   } catch (Exception ex) {
     return false;
   }
   if (!(run instanceof AbstractBuild)) {
     // Abstract#getEnvironment(TaskListener) put build parameters to
     // environments, but Run#getEnvironment(TaskListener) doesn't.
     // That means we can't retrieve build parameters from WorkflowRun
     // as it is a subclass of Run, not of AbstractBuild.
     // We need expand build parameters manually.
     // See JENKINS-26694 for details.
     for (ParametersAction pa : run.getActions(ParametersAction.class)) {
       // We have to extract parameters manually as ParametersAction#buildEnvVars
       // (overrides EnvironmentContributingAction#buildEnvVars)
       // is applicable only for AbstractBuild.
       for (ParameterValue pv : pa.getParameters()) {
         pv.buildEnvironment(run, otherEnv);
       }
     }
   }
   for (StringParameterValue spv : filters) {
     if (!spv.value.equals(otherEnv.get(spv.getName()))) {
       return false;
     }
   }
   return true;
 }
  private void triggerAllBuildsConcurrent(AbstractBuild build, BuildListener listener) {

    final List<String> newBuildNodes = new ArrayList<String>();

    final ParametersAction origParamsAction = build.getAction(ParametersAction.class);
    final List<ParameterValue> origParams = origParamsAction.getParameters();
    final List<ParameterValue> newPrams = new ArrayList<ParameterValue>();
    for (ParameterValue parameterValue : origParams) {
      if (parameterValue instanceof LabelParameterValue) {
        if (parameterValue instanceof NodeParameterValue) {
          NodeParameterValue origNodePram = (NodeParameterValue) parameterValue;
          List<String> nextNodes = origNodePram.getNextLabels();
          if (nextNodes != null) {
            listener.getLogger().print("next nodes: " + nextNodes);
            newBuildNodes.addAll(nextNodes);
          }
        }
      } else {
        newPrams.add(parameterValue);
      }
    }
    for (String nodeName : newBuildNodes) {
      final List<String> singleNodeList = new ArrayList<String>();
      singleNodeList.add(nodeName);
      final NodeParameterValue nodeParameterValue =
          new NodeParameterValue(nodeName, singleNodeList);
      List<ParameterValue> copies = new ArrayList<ParameterValue>(newPrams);
      copies.add(nodeParameterValue); // where to do the next build
      listener.getLogger().print("schedule build on node " + nodeName);
      build
          .getProject()
          .scheduleBuild(0, new NextLabelCause(nodeName), new ParametersAction(copies));
    }
  }
Esempio n. 3
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;
  }
 private BuildData getBuildData(StringParameterValue pullRequestUrlParam) {
   for (Run<?, ?> build : project.getBuilds()) {
     ParametersAction paramsAction = build.getAction(ParametersAction.class);
     if (paramsAction != null) {
       for (ParameterValue param : paramsAction.getParameters()) {
         if (param.equals(pullRequestUrlParam)) {
           List<BuildData> buildDataList = build.getActions(BuildData.class);
           if (!buildDataList.isEmpty()) {
             return buildDataList.get(0);
           }
         }
       }
     }
   }
   return null;
 }
Esempio n. 5
0
 private void populateWithParameters(Run build, String externalizableId) {
   ParametersAction action = build.getAction(ParametersAction.class);
   if (action != null) {
     List<ParameterValue> parameters = action.getParameters();
     if (parameters != null) {
       for (ParameterValue parameter : parameters) {
         if (parameter instanceof StringParameterValue) {
           put(
               "parameter-" + parameter.getName(),
               ((StringParameterValue) parameter).value,
               externalizableId);
         }
       }
     }
   }
 }
 @SuppressWarnings("unchecked")
 public boolean matchesRun(Run run) {
   ParametersAction action = run.getAction(ParametersAction.class);
   if (action == null) {
     return false;
   }
   // look for one parameter value that matches our criteria
   for (ParameterValue value : action.getParameters()) {
     String sval = getStringValue(value);
     if (matchesParameter(value.getName(), sval, false, null)) {
       return true;
     }
   }
   // no parameters matched the criteria
   return false;
 }
Esempio n. 7
0
  private String getSingleBranch(AbstractBuild<?, ?> build) {
    // if we have multiple branches skip to advanced usecase
    if (getBranches().size() != 1 || getRepositories().size() != 1) return null;

    String branch = getBranches().get(0).getName();
    String repository = getRepositories().get(0).getName();

    // replace repository wildcard with repository name
    if (branch.startsWith("*/")) branch = repository + branch.substring(1);

    // if the branch name contains more wildcards then the simple usecase
    // does not apply and we need to skip to the advanced usecase
    if (branch.contains("*")) return null;

    // substitute build parameters if available
    ParametersAction parameters = build.getAction(ParametersAction.class);
    if (parameters != null) branch = parameters.substitute(build, branch);
    return branch;
  }
Esempio n. 8
0
 /**
  * Method for getting the ParameterValue instance from ParameterDefinition or ParamterAction.
  *
  * @param paramDefProp ParametersDefinitionProperty
  * @param parameterName Name of the Parameter.
  * @param paramAction ParametersAction
  * @param req StaplerRequest
  * @param jo JSONObject
  * @return ParameterValue instance of subclass of ParameterValue
  */
 public ParameterValue getParameterValue(
     ParametersDefinitionProperty paramDefProp,
     String parameterName,
     ParametersAction paramAction,
     StaplerRequest req,
     JSONObject jo) {
   ParameterDefinition paramDef;
   // this is normal case when user try to rebuild a parameterized job.
   if (paramDefProp != null) {
     paramDef = paramDefProp.getParameterDefinition(parameterName);
     if (paramDef != null) {
       // The copy artifact plugin throws an exception when using createValue(req, jo)
       // If the parameter comes from the copy artifact plugin, then use the single argument
       // createValue
       if (jo.toString().contains("BuildSelector")
           || jo.toString().contains("WorkspaceSelector")) {
         SimpleParameterDefinition parameterDefinition =
             (SimpleParameterDefinition) paramDefProp.getParameterDefinition(parameterName);
         return parameterDefinition.createValue(jo.getString("value"));
       }
       return paramDef.createValue(req, jo);
     }
   }
   /*
    * when user try to rebuild a build that was invoked by
    * parameterized trigger plugin in that case ParameterDefinition
    * is null for that parametername that is paased by parameterize
    * trigger plugin,so for handling that scenario, we need to
    * create an instance of that specific ParameterValue with
    * passed parameter value by form.
    *
    * In contrast to all other parameterActions, ListSubversionTagsParameterValue uses "tag" instead of "value"
    */
   if (jo.containsKey("value")) {
     return cloneParameter(paramAction.getParameter(parameterName), jo.getString("value"));
   } else {
     return cloneParameter(paramAction.getParameter(parameterName), jo.getString("tag"));
   }
 }
 private void triggerBuilds(AbstractBuild build, BuildListener listener) {
   final ParametersAction origParamsAction = build.getAction(ParametersAction.class);
   final List<ParameterValue> origParams = origParamsAction.getParameters();
   final List<ParameterValue> newPrams = new ArrayList<ParameterValue>();
   boolean triggerNewBuild = false;
   NextLabelCause nextLabelCause = null;
   for (ParameterValue parameterValue : origParams) {
     if (parameterValue instanceof LabelParameterValue) {
       if (parameterValue instanceof NodeParameterValue) {
         NodeParameterValue origNodePram = (NodeParameterValue) parameterValue;
         final List<String> nextNodes = origNodePram.getNextLabels();
         if (nextNodes != null
             && !nextNodes.isEmpty()
             && shouldScheduleNextJob(build.getResult(), triggerIfResult)) {
           NodeParameterValue newNodeParam =
               new NodeParameterValue(origNodePram.getName(), nextNodes);
           newPrams.add(newNodeParam);
           final String nextLabel = newNodeParam.getLabel();
           if (nextLabel != null) {
             listener.getLogger().print("schedule single build on node " + nextLabel);
             nextLabelCause = new NextLabelCause(nextLabel);
             triggerNewBuild = true;
           } else {
             LOGGER.severe(
                 "can't trigger next build because next label could not be determined!");
           }
         }
       }
     } else {
       newPrams.add(parameterValue);
     }
   }
   if (triggerNewBuild) {
     // schedule the next build right away...
     // the ParametersAction will also contain the labels for the
     // next builds
     build.getProject().scheduleBuild(0, nextLabelCause, new ParametersAction(newPrams));
   }
 }
  @Test
  public void testRebuild() throws Exception {
    // job with promotion process
    FreeStyleProject p1 = j.createFreeStyleProject("promojob");

    // setup promotion process
    JobPropertyImpl promotion = new JobPropertyImpl(p1);
    p1.addProperty(promotion);
    PromotionProcess proc = promotion.addProcess("promo");
    proc.conditions.add(new SelfPromotionCondition(false));

    // build it
    FreeStyleBuild b1 = j.assertBuildStatusSuccess(p1.scheduleBuild2(0));
    j.waitUntilNoActivity();

    // verify that promotion happened
    Assert.assertSame(proc.getBuilds().getLastBuild().getTarget(), b1);

    // job with parameter
    FreeStyleProject p2 = j.createFreeStyleProject("paramjob");

    // add promoted build param
    p2.addProperty(
        new ParametersDefinitionProperty(
            new PromotedBuildParameterDefinition(
                "var", "promojob", "promo", "promoted build param to test rebuild")));

    // build with parameter
    FreeStyleBuild b2 = j.assertBuildStatusSuccess(p2.scheduleBuild2(0));

    // validate presence of parameter
    ParametersAction a1 = b2.getAction(ParametersAction.class);
    Assert.assertNotNull(a1);
    Assert.assertFalse(a1.getParameters().isEmpty());
    ParameterValue v1 = a1.getParameter("var");
    Assert.assertTrue(v1 instanceof PromotedBuildParameterValue);
    PromotedBuildParameterValue pbpv1 = (PromotedBuildParameterValue) v1;
    Assert.assertEquals(b1.getNumber(), pbpv1.getRun().getNumber());

    // rebuild it
    JenkinsRule.WebClient wc = j.createWebClient();
    HtmlPage page = wc.getPage(b2, "rebuild");
    HtmlForm form = page.getFormByName("config");
    j.submit(form);
    j.waitUntilNoActivity();

    // validate presence of parameter
    FreeStyleBuild rebuild = p2.getLastBuild();
    j.assertBuildStatusSuccess(rebuild);
    Assert.assertNotEquals(b2.getNumber(), rebuild.getNumber());
    ParametersAction a2 = rebuild.getAction(ParametersAction.class);
    Assert.assertNotNull(a2);
    Assert.assertFalse(a2.getParameters().isEmpty());
    ParameterValue v2 = a2.getParameter("var");
    Assert.assertTrue(v2 instanceof PromotedBuildParameterValue);
    PromotedBuildParameterValue pbpv2 = (PromotedBuildParameterValue) v2;
    Assert.assertEquals(b1.getNumber(), pbpv2.getRun().getNumber());
  }
  @Test
  public void test() throws IOException {
    Project project = r.createFreeStyleProject("project");

    project.addProperty(
        new ParametersDefinitionProperty(
            new StringParameterDefinition("key1", "value1"),
            new StringParameterDefinition("key2", "value2")));

    ParametersAction action =
        new ParametersAction(
            new StringParameterValue("key2", "not-value2"),
            new StringParameterValue("key3", "value3"));

    DefaultParameterValuesActionsTransform transform = new DefaultParameterValuesActionsTransform();

    ParametersAction result = transform.transformParametersAction(action, project);

    assertEquals(3, result.getParameters().size());

    assertStringParameterValueEquals("value1", result.getParameter("key1"));
    assertStringParameterValueEquals("not-value2", result.getParameter("key2"));
    assertStringParameterValueEquals("value3", result.getParameter("key3"));
  }
 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();
 }
    @Override
    protected Result doRun(final BuildListener listener) throws Exception {
      PrintStream logger = listener.getLogger();
      try {
        EnvVars envVars = getEnvironment(listener);

        Config config = IvyConfig.provider.getConfigById(project.getSettings());
        if (config != null) {
          FilePath tmp = getWorkspace().createTextTempFile("ivy", "xml", config.content);
          settings = tmp.getRemote();
          addAction(new CleanTempFilesAction(settings));

        } else {
          String settingsFile = project.getIvySettingsFile();
          if (settingsFile != null) {
            settings = getWorkspace().child(settingsFile).getRemote();
          }
        }

        if (!project.isAggregatorStyleBuild()) {
          // start module builds
          parseIvyDescriptorFiles(listener, logger, envVars);
          Set<IvyModule> triggeredModules = new HashSet<IvyModule>();
          if (!project.isIncrementalBuild() || IvyModuleSetBuild.this.getChangeSet().isEmptySet()) {
            for (IvyModule module : project.sortedActiveModules) {
              // Don't trigger builds if we've already triggered
              // one
              // of their dependencies.
              // It's safe to just get the direct dependencies
              // since
              // the modules are sorted in dependency order.
              List<AbstractProject> ups = module.getUpstreamProjects();
              boolean triggerBuild = true;
              for (AbstractProject upstreamDep : ups) {
                if (triggeredModules.contains(upstreamDep)) {
                  triggerBuild = false;
                  break;
                }
              }

              if (triggerBuild) {
                logger.println("Triggering " + module.getModuleName());
                module.scheduleBuild(
                    new ParameterizedUpstreamCause(
                        ((Run<?, ?>) IvyModuleSetBuild.this),
                        IvyModuleSetBuild.this.getActions(ParametersAction.class)));
              }
              triggeredModules.add(module);
            }
          } else {
            for (IvyModule module : project.sortedActiveModules) {
              // If there are changes for this module, add it.
              // Also add it if we've never seen this module
              // before,
              // or if the previous build of this module
              // failed or was unstable.
              boolean triggerBuild = false;
              if ((module.getLastBuild() == null)
                  || (!getChangeSetFor(module).isEmpty())
                  || (module.getLastBuild().getResult().isWorseThan(Result.SUCCESS))) {
                triggerBuild = true;
                List<AbstractProject> ups = module.getUpstreamProjects();
                for (AbstractProject upstreamDep : ups) {
                  if (triggeredModules.contains(upstreamDep)) {
                    triggerBuild = false;
                    triggeredModules.add(module);
                    break;
                  }
                }
              }

              if (triggerBuild) {
                logger.println("Triggering " + module.getModuleName());
                module.scheduleBuild(
                    new ParameterizedUpstreamCause(
                        ((Run<?, ?>) IvyModuleSetBuild.this),
                        IvyModuleSetBuild.this.getActions(ParametersAction.class)));
                triggeredModules.add(module);
              }
            }
          }
        } else {
          // do builds here
          try {
            List<BuildWrapper> wrappers = new ArrayList<BuildWrapper>();
            for (BuildWrapper w : project.getBuildWrappersList()) wrappers.add(w);
            ParametersAction parameters = getAction(ParametersAction.class);
            if (parameters != null)
              parameters.createBuildWrappers(IvyModuleSetBuild.this, wrappers);

            for (BuildWrapper w : wrappers) {
              Environment e = w.setUp(IvyModuleSetBuild.this, launcher, listener);
              if (e == null) return Result.FAILURE;
              buildEnvironments.add(e);
              e.buildEnvVars(envVars); // #3502: too late for
              // getEnvironment to do
              // this
            }

            if (!preBuild(listener, project.getPublishers())) return Result.FAILURE;

            Properties additionalProperties = null;
            if (project.isIncrementalBuild()) {
              parseIvyDescriptorFiles(listener, logger, envVars);
              List<String> changedModules = new ArrayList<String>();
              for (IvyModule m : project.sortedActiveModules) {
                // Check if incrementalBuild is selected and that
                // there are changes -
                // we act as if incrementalBuild is not set if there
                // are no changes.
                if (!IvyModuleSetBuild.this.getChangeSet().isEmptySet()) {
                  // If there are changes for this module, add it.
                  if (!getChangeSetFor(m).isEmpty()) {
                    changedModules.add(m.getModuleName().name);
                  }
                }
              }

              if (project.isAggregatorStyleBuild()) {
                additionalProperties = new Properties();
                additionalProperties.put(
                    project.getChangedModulesProperty() == null
                        ? "hudson.ivy.changedModules"
                        : project.getChangedModulesProperty(),
                    StringUtils.join(changedModules, ','));
              }
            }

            IvyBuilderType ivyBuilderType = project.getIvyBuilderType();
            hudson.tasks.Builder builder =
                ivyBuilderType.getBuilder(additionalProperties, null, buildEnvironments);
            logger.println(
                "Building project with " + ivyBuilderType.getDescriptor().getDisplayName());

            if (builder.perform(IvyModuleSetBuild.this, launcher, listener)) return Result.SUCCESS;

            return Result.FAILURE;
          } finally {
            // tear down in reverse order
            boolean failed = false;
            for (int i = buildEnvironments.size() - 1; i >= 0; i--) {
              if (!buildEnvironments.get(i).tearDown(IvyModuleSetBuild.this, listener)) {
                failed = true;
              }
            }
            buildEnvironments = null;
            // WARNING The return in the finally clause will trump
            // any return before
            if (failed) return Result.FAILURE;
          }
        }

        return null;
      } catch (AbortException e) {
        if (e.getMessage() != null) listener.error(e.getMessage());
        return Result.FAILURE;
      } catch (InterruptedIOException e) {
        e.printStackTrace(listener.error("Aborted Ivy execution for InterruptedIOException"));
        return Result.ABORTED;
      } catch (InterruptedException e) {
        e.printStackTrace(listener.error("Aborted Ivy execution for InterruptedException"));
        return Result.ABORTED;
      } catch (IOException e) {
        e.printStackTrace(listener.error(Messages.IvyModuleSetBuild_FailedToParseIvyXml()));
        return Result.FAILURE;
      } catch (RunnerAbortedException e) {
        return Result.FAILURE;
      } catch (RuntimeException e) {
        // bug in the code.
        e.printStackTrace(
            listener.error(
                "Processing failed due to a bug in the code. Please report this to [email protected]"));
        logger.println("project=" + project);
        logger.println("project.getModules()=" + project.getModules());
        throw e;
      }
    }
 private static ParametersAction mergeParameters(ParametersAction base, ParametersAction overlay) {
   LinkedHashMap<String, ParameterValue> params = new LinkedHashMap<String, ParameterValue>();
   for (ParameterValue param : base.getParameters()) params.put(param.getName(), param);
   for (ParameterValue param : overlay.getParameters()) params.put(param.getName(), param);
   return new ParametersAction(params.values().toArray(new ParameterValue[params.size()]));
 }
 private boolean isPullRequestBuild(AbstractBuild build, String pullRequestUrl) {
   ParametersAction parameters = build.getAction(ParametersAction.class);
   return parameters != null
       && parameters.getParameters().contains(new StringParameterValue("PR_URL", pullRequestUrl));
 }