/** Exposes the name/value as an environment variable. */
 @Override
 public void buildEnvVars(AbstractBuild<?, ?> build, EnvVars env) {
   env.put(name, Boolean.toString(value));
   env.put(
       name.toUpperCase(Locale.ENGLISH),
       Boolean.toString(value)); // backward compatibility pre 1.345
 }
  private void addArgsTo(
      ArgumentListBuilder args,
      SonarInstallation sonarInst,
      EnvVars env,
      Map<String, String> props) {
    args.add("begin");

    args.add("/k:" + env.expand(projectKey) + "");
    args.add("/n:" + env.expand(projectName) + "");
    args.add("/v:" + env.expand(projectVersion) + "");

    // expand macros using itself
    EnvVars.resolve(props);

    for (Map.Entry<String, String> e : props.entrySet()) {
      if (!StringUtils.isEmpty(e.getValue())) {
        // expand macros using environment variables and hide passwords/tokens
        boolean hide =
            e.getKey().contains("password")
                || (!StringUtils.isEmpty(sonarInst.getServerAuthenticationToken())
                    && e.getKey().contains("login"));
        args.addKeyValuePair("/d:", e.getKey(), env.expand(e.getValue()), hide);
      }
    }

    args.add(sonarInst.getAdditionalAnalysisPropertiesWindows());
    args.addTokenized(sonarInst.getAdditionalProperties());
    args.addTokenized(additionalArguments);
  }
 /** {@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;
 }
예제 #4
0
  public SlackService newSlackService(AbstractBuild r, BuildListener listener) {
    String teamDomain = this.teamDomain;
    if (StringUtils.isEmpty(teamDomain)) {
      teamDomain = getDescriptor().getTeamDomain();
    }
    String authToken = this.authToken;
    if (StringUtils.isEmpty(authToken)) {
      authToken = getDescriptor().getToken();
    }
    String room = this.room;
    if (StringUtils.isEmpty(room)) {
      room = getDescriptor().getRoom();
    }

    EnvVars env = null;
    try {
      env = r.getEnvironment(listener);
    } catch (Exception e) {
      listener.getLogger().println("Error retrieving environment vars: " + e.getMessage());
      env = new EnvVars();
    }
    teamDomain = env.expand(teamDomain);
    authToken = env.expand(authToken);
    room = env.expand(room);

    return new StandardSlackService(teamDomain, authToken, room);
  }
예제 #5
0
  @Override
  public EnvVars getEnvironment(TaskListener log) throws IOException, InterruptedException {
    EnvVars env = super.getEnvironment(log);
    FilePath ws = getWorkspace();
    if (ws
        != null) // if this is done very early on in the build, workspace may not be decided yet.
                 // see HUDSON-3997
    env.put("WORKSPACE", ws.getRemote());
    // servlet container may have set CLASSPATH in its launch script,
    // so don't let that inherit to the new child process.
    // see http://www.nabble.com/Run-Job-with-JDK-1.4.2-tf4468601.html
    env.put("CLASSPATH", "");

    JDK jdk = project.getJDK();
    if (jdk != null) {
      Computer computer = Computer.currentComputer();
      if (computer != null) { // just in case were not in a build
        jdk = jdk.forNode(computer.getNode(), log);
      }
      jdk.buildEnvVars(env);
    }
    project.getScm().buildEnvVars(this, env);

    if (buildEnvironments != null) for (Environment e : buildEnvironments) e.buildEnvVars(env);

    for (EnvironmentContributingAction a :
        Util.filter(getActions(), EnvironmentContributingAction.class)) a.buildEnvVars(this, env);

    EnvVars.resolve(env);

    return env;
  }
  @Override
  public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
      throws InterruptedException, IOException {
    EnvVars envVars = build.getEnvironment(listener);
    envVars.overrideAll(build.getBuildVariables());
    boolean result = true;

    for (PostBuildStackBean stack : stacks) {
      final CloudFormation cloudFormation =
          newCloudFormation(stack, build, envVars, listener.getLogger());
      /*CloudFormation cloudFormation = new CloudFormation(
      		listener.getLogger(),
      		stack.getStackName(),
      		"",
      		new HashMap<String, String>(),
      		0,
      		stack.getParsedAwsAccessKey(envVars),
      		stack.getParsedAwsSecretKey(envVars),
      		stack.getAwsRegion(),
      		false,
      		envVars
      );*/
      if (cloudFormation.create()) {
        LOGGER.info("Success");
      } else {
        LOGGER.warning("Failed");
        result = false;
      }
    }
    return result;
  }
  private String getEnvDefinedMavenHome(EnvVars env) {
    String mavenHome = env.get("MAVEN_HOME");
    if (StringUtils.isNotBlank(mavenHome)) {
      return mavenHome;
    }

    return env.get("M2_HOME");
  }
  @Override
  public boolean perform(
      AbstractBuild<?, ?> build, Launcher launcher, final BuildListener listener) {
    if (build.getResult().isWorseOrEqualTo(Result.FAILURE)) return false;

    listener.getLogger().println(Messages.TestflightRecorder_InfoUploading());

    try {
      EnvVars vars = build.getEnvironment(listener);

      String workspace = vars.expand("$WORKSPACE");

      List<TestflightUploader.UploadRequest> urList =
          new ArrayList<TestflightUploader.UploadRequest>();

      for (TestflightTeam team : createDefaultPlusAdditionalTeams()) {
        try {
          TestflightUploader.UploadRequest ur = createPartialUploadRequest(team, vars, build);
          urList.add(ur);
        } catch (MisconfiguredJobException mje) {
          listener.getLogger().println(mje.getConfigurationMessage());
          return false;
        }
      }

      for (TestflightUploader.UploadRequest ur : urList) {
        TestflightRemoteRecorder remoteRecorder =
            new TestflightRemoteRecorder(workspace, ur, listener);

        final List<Map> parsedMaps;

        try {
          Object result = launcher.getChannel().call(remoteRecorder);
          parsedMaps = (List<Map>) result;
        } catch (UploadException ue) {
          listener
              .getLogger()
              .println(Messages.TestflightRecorder_IncorrectResponseCode(ue.getStatusCode()));
          listener.getLogger().println(ue.getResponseBody());
          return false;
        }

        if (parsedMaps.size() == 0) {
          listener.getLogger().println(Messages.TestflightRecorder_NoUploadedFile(ur.filePaths));
          return false;
        }
        for (Map parsedMap : parsedMaps) {
          addTestflightLinks(build, listener, parsedMap);
        }
      }
    } catch (Throwable e) {
      listener.getLogger().println(e);
      e.printStackTrace(listener.getLogger());
      return false;
    }

    return true;
  }
예제 #9
0
  /** Create an {@link ArgumentListBuilder} to run the build, given command arguments. */
  private ArgumentListBuilder buildCmdLine(
      AbstractBuild build, Launcher launcher, BuildListener listener)
      throws IllegalArgumentException, InterruptedException, IOException {
    ArgumentListBuilder args = new ArgumentListBuilder();

    //		DescriptorImpl descriptor = (DescriptorImpl) getDescriptor();

    EnvVars env = build.getEnvironment(listener);
    env.overrideAll(build.getBuildVariables());

    SbtInstallation sbt = getSbt();
    if (sbt == null) {
      throw new IllegalArgumentException("sbt-launch.jar not found");
    } else {
      Node currentNode = Computer.currentComputer().getNode();
      sbt = sbt.forNode(currentNode, listener);
      sbt = sbt.forEnvironment(env);

      String launcherPath = sbt.getSbtLaunchJar(launcher);

      if (launcherPath == null) {
        throw new IllegalArgumentException("sbt-launch.jar not found");
      }

      if (!launcher.isUnix()) {
        args.add("cmd.exe", "/C");
      }

      // java
      String javaExePath = (File.separatorChar == '\\') ? "java.exe" : "java";

      JDK jdk = build.getProject().getJDK();
      if (jdk != null) { // just in case were not in a build
        // use node specific installers, etc
        jdk = jdk.forNode(currentNode, listener);
        jdk = jdk.forEnvironment(env);

        javaExePath = jdk.getBinDir() + "/" + javaExePath;
      }

      args.add(javaExePath);

      splitAndAddArgs(jvmFlags, args);
      splitAndAddArgs(sbtFlags, args);

      args.add("-jar");

      args.add(launcherPath);

      for (String action : split(actions)) {
        args.add(action);
      }
    }

    return args;
  }
예제 #10
0
  /**
   * Runs every job DSL script provided in the plugin configuration, which results in new / updated
   * Jenkins jobs. The created / updated jobs are reported in the build result.
   */
  @Override
  public boolean perform(
      final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener)
      throws InterruptedException, IOException {
    try {
      EnvVars env = build.getEnvironment(listener);
      env.putAll(build.getBuildVariables());

      // We run the DSL, it'll need some way of grabbing a template config.xml and how to save it
      JenkinsJobManagement jm =
          new JenkinsJobManagement(listener.getLogger(), env, build, getLookupStrategy());

      ScriptRequestGenerator generator = new ScriptRequestGenerator(build, env);
      try {
        Set<ScriptRequest> scriptRequests =
            generator.getScriptRequests(
                targets, usingScriptText, scriptText, ignoreExisting, additionalClasspath);

        Set<GeneratedJob> freshJobs = new LinkedHashSet<GeneratedJob>();
        Set<GeneratedView> freshViews = new LinkedHashSet<GeneratedView>();
        Set<GeneratedConfigFile> freshConfigFiles = new LinkedHashSet<GeneratedConfigFile>();
        Set<GeneratedUserContent> freshUserContents = new LinkedHashSet<GeneratedUserContent>();
        for (ScriptRequest request : scriptRequests) {
          LOGGER.log(Level.FINE, String.format("Request for %s", request.getLocation()));

          GeneratedItems generatedItems = DslScriptLoader.runDslEngine(request, jm);
          freshJobs.addAll(generatedItems.getJobs());
          freshViews.addAll(generatedItems.getViews());
          freshConfigFiles.addAll(generatedItems.getConfigFiles());
          freshUserContents.addAll(generatedItems.getUserContents());
        }

        updateTemplates(build, listener, freshJobs);
        updateGeneratedJobs(build, listener, freshJobs);
        updateGeneratedViews(build, listener, freshViews);
        updateGeneratedConfigFiles(build, listener, freshConfigFiles);
        updateGeneratedUserContents(build, listener, freshUserContents);

        // Save onto Builder, which belongs to a Project.
        build.addAction(new GeneratedJobsBuildAction(freshJobs, getLookupStrategy()));
        build.addAction(new GeneratedViewsBuildAction(freshViews, getLookupStrategy()));
        build.addAction(new GeneratedConfigFilesBuildAction(freshConfigFiles));
        build.addAction(new GeneratedUserContentsBuildAction(freshUserContents));

        return true;
      } finally {
        generator.close();
      }
    } catch (DslException e) {
      LOGGER.log(
          Level.FINE,
          String.format("Exception while processing DSL scripts: %s", e.getMessage()),
          e);
      throw new AbortException(e.getMessage());
    }
  }
 public void setUp() throws Exception {
   super.setUp();
   EnvVars env = new EnvVars();
   // we don't want Maven, Ant, etc. to be discovered in the path for this test to work,
   // but on Unix these tools rely on other basic Unix tools (like env) for its operation,
   // so empty path breaks the test.
   env.put("PATH", "/bin:/usr/bin");
   env.put("M2_HOME", "empty");
   slave = createSlave(new LabelAtom("slave"), env);
   project = createFreeStyleProject();
   project.setAssignedLabel(slave.getSelfLabel());
 }
  @Test
  public void assertComputerEnvVarIsResolved() throws Exception {
    EnvVars map = new EnvVars();
    map.put("ENV_VAR", "This is an env var");

    when(computer.getEnvironment()).thenReturn(map);

    BuildVariableResolver resolver = new BuildVariableResolver(project, computer);
    assertEquals(
        "Variable resolution was incorrect", "This is an env var", resolver.resolve("ENV_VAR"));
    verifyZeroInteractions(project);
  }
  @Test
  public void assertBuildEnvVarIsResolved() throws Exception {
    EnvVars map = new EnvVars();
    map.put("BUILD_ID", "121212");

    when(build.getProject()).thenReturn(project);
    when(build.getEnvironment(TaskListener.NULL)).thenReturn(map);

    BuildVariableResolver resolver = new BuildVariableResolver(build, computer);
    assertEquals("Variable resolution was incorrect", "121212", resolver.resolve("BUILD_ID"));
    verify(build).getEnvironment(TaskListener.NULL);
    verifyZeroInteractions(project);
  }
    /**
     * Runs Docker command using Docker CLI.
     *
     * @param cmd Command to be executed
     * @param logStdOut If true, propagate STDOUT to the build log
     * @param logStdErr If true, propagate STDERR to the build log
     * @return Execution result
     * @throws IOException Execution error
     * @throws InterruptedException The build has been interrupted
     */
    private @Nonnull Result executeCmd(@Nonnull String cmd, boolean logStdOut, boolean logStdErr)
        throws IOException, InterruptedException {
      ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream();
      ByteArrayOutputStream baosStdErr = new ByteArrayOutputStream();
      OutputStream stdout =
          logStdOut ? new TeeOutputStream(listener.getLogger(), baosStdOut) : baosStdOut;
      OutputStream stderr =
          logStdErr ? new TeeOutputStream(listener.getLogger(), baosStdErr) : baosStdErr;

      // get Docker registry credentials
      KeyMaterial registryKey = getRegistry().newKeyMaterialFactory(build).materialize();
      // Docker server credentials. If server is null (right after upgrading) do not use credentials
      KeyMaterial serverKey =
          server == null ? null : server.newKeyMaterialFactory(build).materialize();

      logger.log(Level.FINER, "Executing: {0}", cmd);

      try {
        EnvVars env = new EnvVars();
        env.putAll(build.getEnvironment(listener));
        env.putAll(registryKey.env());
        if (serverKey != null) {
          env.putAll(serverKey.env());
        }

        boolean result =
            launcher
                    .launch()
                    .envs(env)
                    .pwd(build.getWorkspace())
                    .stdout(stdout)
                    .stderr(stderr)
                    .cmdAsSingleString(cmd)
                    .start()
                    .join()
                == 0;

        // capture the stdout so it can be parsed later on
        final String stdOutStr = DockerCLIHelper.getConsoleOutput(baosStdOut, logger);
        final String stdErrStr = DockerCLIHelper.getConsoleOutput(baosStdErr, logger);
        return new Result(result, stdOutStr, stdErrStr);

      } finally {
        registryKey.close();
        if (serverKey != null) {
          serverKey.close();
        }
      }
    }
예제 #15
0
  /**
   * An attempt to generate at least semi-useful EnvVars for polling calls, based on previous build.
   * Cribbed from various places.
   */
  public static EnvVars getPollEnvironment(
      AbstractProject p, FilePath ws, Launcher launcher, TaskListener listener)
      throws IOException, InterruptedException {
    EnvVars env;

    AbstractBuild b = (AbstractBuild) p.getLastBuild();

    if (b != null) {
      Node lastBuiltOn = b.getBuiltOn();

      if (lastBuiltOn != null) {
        env = lastBuiltOn.toComputer().getEnvironment().overrideAll(b.getCharacteristicEnvVars());
      } else {
        env = new EnvVars(System.getenv());
      }

      String rootUrl = Hudson.getInstance().getRootUrl();
      if (rootUrl != null) {
        env.put("HUDSON_URL", rootUrl);
        env.put("BUILD_URL", rootUrl + b.getUrl());
        env.put("JOB_URL", rootUrl + p.getUrl());
      }

      if (!env.containsKey("HUDSON_HOME")) {
        env.put("HUDSON_HOME", Hudson.getInstance().getRootDir().getPath());
      }

      if (ws != null) {
        env.put("WORKSPACE", ws.getRemote());
      }

      p.getScm().buildEnvVars(b, env);

      StreamBuildListener buildListener =
          new StreamBuildListener((OutputStream) listener.getLogger());

      for (NodeProperty nodeProperty : Hudson.getInstance().getGlobalNodeProperties()) {
        Environment environment = nodeProperty.setUp(b, launcher, (BuildListener) buildListener);
        if (environment != null) {
          environment.buildEnvVars(env);
        }
      }

      if (lastBuiltOn != null) {
        for (NodeProperty nodeProperty : lastBuiltOn.getNodeProperties()) {
          Environment environment = nodeProperty.setUp(b, launcher, buildListener);
          if (environment != null) {
            environment.buildEnvVars(env);
          }
        }
      }

      EnvVars.resolve(env);
    } else {
      env = new EnvVars(System.getenv());
    }

    return env;
  }
  /** Tests the generated list of custom fields. */
  @Bug(13173)
  public void testListOfCustomFields() {
    EnvVars envVars = new EnvVars();
    @SuppressWarnings({"unchecked", "rawtypes"})
    VariableResolver<String> varRes = new ByMap.ByMap(envVars);

    envVars.put("BUILD_ID", "1");
    String[] customFieldsNames = builder.createArrayOfCustomFieldsNames(varRes, envVars);

    assertNotNull(customFieldsNames);
    assertTrue(customFieldsNames.length == 3);
    assertEquals(customFieldsNames[0], "class");
    assertEquals(customFieldsNames[1], "time");
    assertEquals(customFieldsNames[2], "sample-job-1");
  }
예제 #17
0
  /**
   * Exposes {@code MAVEN_OPTS} to forked processes.
   *
   * <p>See {@link MavenModuleSetBuild#getEnvironment(TaskListener)} for discussion.
   */
  @Override
  public EnvVars getEnvironment(TaskListener log) throws IOException, InterruptedException {
    EnvVars envs = super.getEnvironment(log);

    // We need to add M2_HOME and the mvn binary to the PATH so if Maven
    // needs to run Maven it will pick the correct one.
    // This can happen if maven calls ANT which itself calls Maven
    // or if Maven calls itself e.g. maven-release-plugin
    MavenInstallation mvn = project.getParent().getMaven();
    if (mvn == null)
      throw new hudson.AbortException(Messages.MavenModuleSetBuild_NoMavenConfigured());
    mvn = mvn.forEnvironment(envs).forNode(Computer.currentComputer().getNode(), log);
    envs.put("M2_HOME", mvn.getHome());
    envs.put("PATH+MAVEN", mvn.getHome() + "/bin");
    return envs;
  }
  @Override
  public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
      throws InterruptedException, IOException {

    EnvVars env = build.getEnvironment(listener);
    env.overrideAll(build.getBuildVariables());

    EnvVariableResolver helper = new EnvVariableResolver(build, listener);

    boolean success = true;
    System.out.println("Loading Blueprint !");

    int counter = 1;
    for (BlueprintParam param : params) {

      System.out.println("Creating package from directory : " + param.getBlueprintPath());

      // Resolve any environment variables in the parameters
      BlueprintParam fparam =
          new BlueprintParam(
              helper.replaceBuildParamWithValue(param.getServerUrl()),
              helper.replaceBuildParamWithValue(param.getUserName()),
              helper.replaceBuildParamWithValue(param.getPassword()),
              helper.replaceBuildParamWithValue(param.getTenant()),
              param.getPackageBlueprint(),
              env.get("WORKSPACE") + "/" + param.getBlueprintPath(),
              param.getOverWrite(),
              param.getPublishBlueprint(),
              param.getServiceCategory());

      final Blueprint blueprint = newBlueprint(listener.getLogger(), fparam);

      try {
        if (blueprint.Create()) {
          this.blueprintList.add(blueprint);

        } else {
          build.setResult(Result.FAILURE);
          success = false;
          break;
        }
      } catch (ArchiveException e) {
        e.printStackTrace();
      }
    }
    return success;
  }
  @Test
  public void shouldExpandSha() throws Exception {
    when(run.getEnvironment(listener)).thenReturn(env);
    when(env.expand(Matchers.anyString())).thenReturn(EXPANDED);

    String context = new ManuallyEnteredShaSource("").get(run, listener);
    assertThat(context, equalTo(EXPANDED));
  }
예제 #20
0
  public ArrayList<String> getJavaCmd(FilePath workingDirectory, EnvVars envVars) {
    String java = "java";
    if (!builder.getFitnesseJdk(envVars).isEmpty()) {
      File customJavaHome =
          Hudson.getInstance().getJDK(builder.getFitnesseJdk(envVars)).getBinDir();
      java = new File(customJavaHome, java).getAbsolutePath();
    } else if (envVars.containsKey("JAVA_HOME")) {
      java = new File(new File(envVars.get("JAVA_HOME"), "bin"), java).getAbsolutePath();
    }
    String fitnesseJavaOpts = builder.getFitnesseJavaOpts(envVars);
    String[] java_opts =
        ("".equals(fitnesseJavaOpts) ? new String[0] : fitnesseJavaOpts.split(" "));

    String absolutePathToFitnesseJar =
        getAbsolutePathToFileThatMayBeRelativeToWorkspace(
            workingDirectory, builder.getFitnessePathToJar());
    String[] jar_opts = {"-jar", absolutePathToFitnesseJar};

    File fitNesseRoot =
        new File(
            getAbsolutePathToFileThatMayBeRelativeToWorkspace(
                workingDirectory, builder.getFitnessePathToRoot()));
    String[] fitnesse_opts = {
      "-d",
      fitNesseRoot.getParent(),
      "-r",
      fitNesseRoot.getName(),
      "-p",
      Integer.toString(builder.getFitnessePort())
    };

    // split additional fitness options and add them to those explicitly configured ones
    String[] addOps = splitOptions(builder.getAdditionalFitnesseOptions());

    String[] fitnesse_opts2 = new String[fitnesse_opts.length + addOps.length];
    System.arraycopy(fitnesse_opts, 0, fitnesse_opts2, 0, fitnesse_opts.length);
    System.arraycopy(addOps, 0, fitnesse_opts2, fitnesse_opts.length, addOps.length);

    ArrayList<String> cmd = new ArrayList<String>();
    cmd.add(java);
    if (java_opts.length > 0) cmd.addAll(Arrays.asList(java_opts));
    cmd.addAll(Arrays.asList(jar_opts));
    cmd.addAll(Arrays.asList(fitnesse_opts2));

    return cmd;
  }
예제 #21
0
 public HygieiaService newHygieiaService(AbstractBuild r, BuildListener listener) {
   String hygieiaAPIUrl = getDescriptor().getHygieiaAPIUrl();
   String hygieiaToken = getDescriptor().getHygieiaToken();
   String hygieiaJenkinsName = getDescriptor().getHygieiaJenkinsName();
   boolean useProxy = getDescriptor().isUseProxy();
   EnvVars env;
   try {
     env = r.getEnvironment(listener);
   } catch (Exception e) {
     listener.getLogger().println("Error retrieving environment vars: " + e.getMessage());
     env = new EnvVars();
   }
   hygieiaAPIUrl = env.expand(hygieiaAPIUrl);
   hygieiaToken = env.expand(hygieiaToken);
   hygieiaJenkinsName = env.expand(hygieiaJenkinsName);
   return new DefaultHygieiaService(hygieiaAPIUrl, hygieiaToken, hygieiaJenkinsName, useProxy);
 }
  public void test() {
    // Test default value
    ArbitraryParameterDefinition testDefinition =
        new ArbitraryParameterDefinition(
            "param_name", "FOo1=BARVALUE1\nfoo2=BAR2", "This is the description.");
    ArbitraryParameterValue testDefaultValue = testDefinition.getDefaultParameterValue();
    EnvVars testVars = new EnvVars(new HashMap<String, String>());
    testDefaultValue.buildEnvVars(null, testVars);
    assertEquals("BARVALUE1", testVars.get("FOo1"));
    assertEquals("BAR2", testVars.get("foo2"));

    // Test custom value
    ParameterValue testCustomValue =
        testDefinition.createValue("param=val val val\nA_Param='vel vel vel'\n");
    testCustomValue.buildEnvVars(null, testVars);
    assertEquals("val val val", testVars.get("param"));
    assertEquals("\'vel vel vel\'", testVars.get("A_Param"));
  }
  public boolean perform(
      final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener)
      throws VSphereException {

    PrintStream jLogger = listener.getLogger();
    EnvVars env;
    try {
      env = build.getEnvironment(listener);
    } catch (Exception e) {
      throw new VSphereException(e);
    }
    env.overrideAll(build.getBuildVariables());
    String expandedMemorySize = env.expand(memorySize);

    VSphereLogger.vsLogger(jLogger, "Preparing reconfigure: Memory");
    spec.setMemoryMB(Long.valueOf(expandedMemorySize));
    VSphereLogger.vsLogger(jLogger, "Finished!");
    return true;
  }
  private Collection<String> lookupCommitSha1s(
      @SuppressWarnings("rawtypes") AbstractBuild build, BuildListener listener) {

    if (commitSha1 != null && commitSha1.trim().length() > 0) {
      PrintStream logger = listener.getLogger();
      try {
        EnvVars environment = build.getEnvironment(listener);
        return Arrays.asList(environment.expand(commitSha1));
      } catch (IOException e) {
        logger.println("Unable to expand commit SHA value");
        e.printStackTrace(logger);
        return Arrays.asList();
      } catch (InterruptedException e) {
        logger.println("Unable to expand commit SHA value");
        e.printStackTrace(logger);
        return Arrays.asList();
      }
    }

    // Use a set to remove duplicates
    Collection<String> sha1s = new HashSet<String>();
    // MultiSCM may add multiple BuildData actions for each SCM, but we are covered in any case
    for (BuildData buildData : build.getActions(BuildData.class)) {
      // get the sha1 of the commit that was built

      String lastBuiltSha1 = buildData.getLastBuiltRevision().getSha1String();

      // Should never be null, but may be blank
      if (!lastBuiltSha1.isEmpty()) {
        sha1s.add(lastBuiltSha1);
      }

      // This might be different than the lastBuiltSha1 if using "Merge before build"
      String markedSha1 = buildData.lastBuild.getMarked().getSha1String();

      // Should never be null, but may be blank
      if (!markedSha1.isEmpty()) {
        sha1s.add(markedSha1);
      }
    }
    return sha1s;
  }
  @Test
  public void testConvertRecipientList_recipientStringShouldBeExpanded()
      throws AddressException, UnsupportedEncodingException {
    envVars.put("EMAIL_LIST", "*****@*****.**");

    Set<InternetAddress> internetAddresses =
        emailRecipientUtils.convertRecipientString("$EMAIL_LIST", envVars);

    assertEquals(1, internetAddresses.size());
    assertTrue(internetAddresses.contains(new InternetAddress("*****@*****.**")));
  }
  @Override
  public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener)
      throws InterruptedException, IOException {
    EnvVars env = build.getEnvironment(listener);
    env.overrideAll(build.getBuildVariables());

    if (Computer.currentComputer() instanceof SlaveComputer) {
      FilePath destinationFilePath;
      if (isOverrideDestinationFolder() && StringUtils.isNotBlank(getDestinationFolder())) {
        destinationFilePath = new FilePath(new File(env.expand(getDestinationFolder())));
      } else {
        destinationFilePath =
            CopyToSlaveUtils.getProjectWorkspaceOnMaster(build, listener.getLogger());
      }

      FilePath projectWorkspaceOnSlave = build.getProject().getWorkspace();

      String includes = env.expand(getIncludes());
      String excludes = env.expand(getExcludes());

      listener
          .getLogger()
          .printf(
              "[copy-to-slave] Copying '%s', excluding %s, from '%s' on '%s' to '%s' on the master.\n",
              includes,
              StringUtils.isBlank(excludes) ? "nothing" : '\'' + excludes + '\'',
              projectWorkspaceOnSlave.toURI(),
              Computer.currentComputer().getNode(),
              destinationFilePath.toURI());

      projectWorkspaceOnSlave.copyRecursiveTo(includes, excludes, destinationFilePath);
    } else if (Computer.currentComputer() instanceof MasterComputer) {
      listener
          .getLogger()
          .println(
              "[copy-to-slave] The build is taking place on the master node, no copy back to the master will take place.");
    }

    return true;
  }
예제 #27
0
파일: Mailer.java 프로젝트: pfeuffer/hudson
  @Override
  public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
      throws IOException, InterruptedException {
    if (debug) listener.getLogger().println("Running mailer");
    // substitute build parameters
    EnvVars env = build.getEnvironment(listener);
    String recip = env.expand(recipients);

    return new MailSender(
        recip, dontNotifyEveryUnstableBuild, sendToIndividuals, descriptor().getCharset()) {
      /** Check whether a path (/-separated) will be archived. */
      @Override
      public boolean artifactMatches(String path, AbstractBuild<?, ?> build) {
        ArtifactArchiver aa = build.getProject().getPublishersList().get(ArtifactArchiver.class);
        if (aa == null) {
          LOGGER.finer("No ArtifactArchiver found");
          return false;
        }
        String artifacts = aa.getArtifacts();
        for (String include : artifacts.split("[, ]+")) {
          String pattern = include.replace(File.separatorChar, '/');
          if (pattern.endsWith("/")) {
            pattern += "**";
          }
          if (SelectorUtils.matchPath(pattern, path)) {
            LOGGER.log(
                Level.FINER,
                "DescriptorImpl.artifactMatches true for {0} against {1}",
                new Object[] {path, pattern});
            return true;
          }
        }
        LOGGER.log(
            Level.FINER,
            "DescriptorImpl.artifactMatches for {0} matched none of {1}",
            new Object[] {path, artifacts});
        return false;
      }
    }.execute(build, listener);
  }
  public ConfigurationItem toConfigurationItem(
      DeployitDescriptorRegistry registry,
      FilePath workspace,
      EnvVars envVars,
      JenkinsDeploymentListener listener) {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(getName()), "Name is required.");
    ConfigurationItem deployable = registry.newInstance(type, envVars.expand(getName()));
    if (!isNullOrEmpty(tags)) {
      String resolvedTags = envVars.expand(tags);
      deployable.setProperty("tags", newHashSet(commaSeparatedListToList(resolvedTags)));
    }

    if (properties != null) {
      for (NameValuePair pair : properties) {
        String value = stripEnclosingQuotes(nullToEmpty(pair.propertyValue));
        value = envVars.expand(value);
        registry.setProperty(deployable, pair.propertyName, value);
      }
    }

    return deployable;
  }
예제 #29
0
 /*
  * (non-Javadoc)
  *
  * @see
  * jenkins.plugins.shiningpanda.command.Command#getEnvironment(hudson.FilePath
  * , hudson.EnvVars)
  */
 @Override
 protected EnvVars getEnvironment(FilePath pwd, EnvVars environment) {
   // Check if conversion required
   if (!convert)
     // If not required return the environment directly
     return environment;
   // Get a new one
   environment = new EnvVars(environment);
   // Add the working directory in the path so `./` are useless on UNIX
   environment.override("PATH+", pwd.getRemote());
   // Return the environment
   return environment;
 }
  /**
   * Note that with Hudson 1.341, trigger should be using {@link
   * BuildTrigger#buildDependencyGraph(AbstractProject, hudson.model.DependencyGraph)}.
   */
  public List<Future<AbstractBuild>> perform(
      AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
      throws InterruptedException, IOException {
    EnvVars env = build.getEnvironment(listener);
    env.overrideAll(build.getBuildVariables());

    try {
      if (condition.isMet(build.getResult())) {
        List<Action> actions = getBaseActions(build, listener);

        List<Future<AbstractBuild>> futures = new ArrayList<Future<AbstractBuild>>();
        for (AbstractProject project : getProjectList(env)) {
          List<Action> list = getBuildActions(actions, project);

          futures.add(schedule(build, project, list));
        }
        return futures;
      }
    } catch (DontTriggerException e) {
      // don't trigger on this configuration
    }
    return Collections.emptyList();
  }