Esempio n. 1
0
  private boolean checkoutCode(
      final Launcher launcher, final FilePath workspace, final OutputStream logger)
      throws IOException, InterruptedException {
    final List<String> commands = new ArrayList<String>(4);

    debug.log(Level.INFO, "Checking out code in: " + workspace.getName());

    commands.add(getDescriptor().getExecutable());
    commands.add("init");
    commands.add("-u");
    commands.add(manifestRepositoryUrl);
    if (manifestBranch != null) {
      commands.add("-b");
      commands.add(manifestBranch);
    }
    if (manifestFile != null) {
      commands.add("-m");
      commands.add(manifestFile);
    }
    if (mirrorDir != null) {
      commands.add("--reference=" + mirrorDir);
    }
    if (repoUrl != null) {
      commands.add("--repo-url=" + repoUrl);
      commands.add("--no-repo-verify");
    }
    int returnCode = launcher.launch().stdout(logger).pwd(workspace).cmds(commands).join();
    if (returnCode != 0) {
      return false;
    }
    if (workspace != null) {
      FilePath rdir = workspace.child(".repo");
      FilePath lm = rdir.child("local_manifest.xml");
      lm.delete();
      if (localManifest != null) {
        if (localManifest.startsWith("<?xml")) {
          lm.write(localManifest, null);
        } else {
          URL url = new URL(localManifest);
          lm.copyFrom(url);
        }
      }
    }

    returnCode = doSync(launcher, workspace, logger);
    if (returnCode != 0) {
      debug.log(Level.WARNING, "Sync failed. Resetting repository");
      commands.clear();
      commands.add(getDescriptor().getExecutable());
      commands.add("forall");
      commands.add("-c");
      commands.add("git reset --hard");
      launcher.launch().stdout(logger).pwd(workspace).cmds(commands).join();
      returnCode = doSync(launcher, workspace, logger);
      if (returnCode != 0) {
        return false;
      }
    }
    return true;
  }
Esempio n. 2
0
  public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
      throws InterruptedException, IOException {
    ArgumentListBuilder args = new ArgumentListBuilder();

    VariableResolver<String> vr = build.getBuildVariableResolver();

    String execName = NantInstallation.getExecutableName();

    // Get the path to the nant installation
    NantInstallation ni = getNant();
    if (ni == null) {
      args.add(
          launcher.isUnix()
              ? NantConstants.NANT_EXECUTABLE_UNIX
              : NantConstants.NANT_EXECUTABLE_WINDOWS);
    } else {
      args.add(ni.getExecutable(launcher));
    }

    // If a nant build file is specified, then add it as an argument, otherwise
    // nant will search for any file that ends in .build
    if (nantBuildFile != null && nantBuildFile.trim().length() > 0) {
      args.add("-buildfile:" + nantBuildFile);
    }

    // add the property declarations to the command line
    args.addKeyValuePairsFromPropertyString("-D:", properties, vr);

    // Remove all tabs, carriage returns, and newlines and replace them with
    // spaces, so that we can add them as parameters to the executable
    String normalizedTarget = targets.replaceAll("[\t\r\n]+", " ");
    if (normalizedTarget.trim().length() > 0) args.addTokenized(normalizedTarget);

    // According to the Ant builder source code, in order to launch a program
    // from the command line in windows, we must wrap it into cmd.exe.  This
    // way the return code can be used to determine whether or not the build failed.
    if (!launcher.isUnix()) {
      args = args.toWindowsCommand();
    }

    // Try to execute the command
    listener.getLogger().println("Executing command: " + args.toString());
    Map<String, String> env = build.getEnvironment(listener);
    try {
      int r =
          launcher.launch().cmds(args).envs(env).stdout(listener).pwd(build.getModuleRoot()).join();
      return r == 0;
    } catch (IOException e) {
      Util.displayIOException(e, listener);
      e.printStackTrace(listener.fatalError("command execution failed"));
      return false;
    }
  }
  @Override
  public void perform(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener)
      throws InterruptedException, IOException {
    ArgumentListBuilder args = new ArgumentListBuilder();

    EnvVars env = BuilderUtils.getEnvAndBuildVars(run, listener);
    SonarInstallation sonarInstallation =
        getSonarInstallation(getSonarInstallationName(), listener);
    MsBuildSQRunnerInstallation msBuildScanner =
        getDescriptor().getMsBuildScannerInstallation(msBuildScannerInstallationName);
    run.addAction(
        new SonarQubeScannerMsBuildParams(
            msBuildScannerInstallationName, getSonarInstallationName()));

    args.add(getExeName(msBuildScanner, env, launcher, listener, workspace));
    Map<String, String> props = getSonarProps(sonarInstallation);
    addArgsTo(args, sonarInstallation, env, props);

    int result =
        launcher
            .launch()
            .cmds(args)
            .envs(env)
            .stdout(listener)
            .pwd(BuilderUtils.getModuleRoot(run, workspace))
            .join();

    if (result != 0) {
      throw new AbortException(Messages.MSBuildScanner_ExecFailed(result));
    }
  }
  public Filter configureFilters(
      VariableResolver<String> variableResolver, AbstractBuild build, Launcher launcher)
      throws IOException, InterruptedException {
    List<Filter> filters = new ArrayList<Filter>();
    filters.add(new DefaultFilter());

    String[] excludedStrings = getExcludedRegionsNormalized();

    if (excludedStrings != null && excludedStrings.length > 0) {
      for (String s : excludedStrings) {
        if (!s.equals("")) {
          filters.add(new FileFilter(FileFilter.Type.DoesNotContainRegxp, s));
        }
      }
    }

    String filterRegexp = "";
    String[] viewPaths = getViewPaths(variableResolver, build, launcher);
    if (viewPaths != null) {
      filterRegexp = getViewPathsRegexp(viewPaths, launcher.isUnix());
    }
    if (StringUtils.isNotEmpty(filterRegexp)) {
      filters.add(new FileFilter(FileFilter.Type.ContainsRegxp, filterRegexp));
    }

    if (isFilteringOutDestroySubBranchEvent()) {
      filters.add(new DestroySubBranchFilter());
    }
    return new FilterChain(filters);
  }
Esempio n. 5
0
  /**
   * There are two things we need to check
   *
   * <ul>
   *   <li>files created or modified since last build time, we only need to check the source folder
   *   <li>file deleted since last build time, we have to compare source and destination folder
   * </ul>
   */
  @Override
  public boolean pollChanges(
      AbstractProject project, Launcher launcher, FilePath workspace, TaskListener listener)
      throws IOException, InterruptedException {

    long start = System.currentTimeMillis();

    PrintStream log = launcher.getListener().getLogger();
    log.println("FSSCM.pollChange: " + path);

    AllowDeleteList allowDeleteList = new AllowDeleteList(project.getRootDir());
    // we will only delete a file if it is listed in the allowDeleteList
    // ie. we will only delete a file if it is copied by us
    if (allowDeleteList.fileExists()) {
      allowDeleteList.load();
    } else {
      // watch list save file doesn't exist
      // we will assuem all existing files are under watch
      // ie. everything can be deleted
      Set<String> existingFiles = workspace.act(new RemoteListDir());
      allowDeleteList.setList(existingFiles);
    }

    RemoteFolderDiff.PollChange callable = new RemoteFolderDiff.PollChange();
    setupRemoteFolderDiff(callable, project, allowDeleteList.getList());

    boolean changed = workspace.act(callable);
    String str = callable.getLog();
    if (str.length() > 0) log.println(str);
    log.println("FSSCM.pollChange return " + changed);

    log.println(
        "FSSCM.poolChange completed in " + formatDurration(System.currentTimeMillis() - start));
    return changed;
  }
Esempio n. 6
0
  @SuppressWarnings("rawtypes")
  public Toolset(AbstractBuild build, Launcher launcher, ToolsetSettings properties)
      throws ToolsetException {
    try {
      // initialize globals
      this.settings = properties;
      this.envVars = build.getEnvironment(launcher.getListener());
      // initialize commands
      this.candle = new Candle(launcher, this.settings, this.envVars);
      this.light = new Light(launcher, this.settings, this.envVars);
      usedOnSlave = properties.get(Wix.USED_ON_SLAVE, false);

      this.candle.addWorkspace(build.getWorkspace());
      this.light.addWorkspace(build.getWorkspace());

      // check
      if (usedOnSlave) {
        lg.log("Wix Toolset plugin is running in slave mode.");
        lg.log("Do not test if toolset is installed.");
      } else {
        lg.log(
            this.candle.exists()
                ? messages.getString("COMPILER_FOUND")
                : messages.getString("COMPILER_NOT_FOUND"));
        lg.log(
            this.light.exists()
                ? messages.getString("LINKER_FOUND")
                : messages.getString("LINKER_NOT_FOUND"));
      }
    } catch (IOException e) {
      lg.severe(e);
    } catch (InterruptedException e) {
      lg.severe(e);
    }
  }
Esempio n. 7
0
  @Override
  public boolean checkout(
      AbstractBuild build,
      Launcher launcher,
      FilePath workspace,
      BuildListener listener,
      File changelogFile)
      throws IOException, InterruptedException {

    long start = System.currentTimeMillis();
    PrintStream log = launcher.getListener().getLogger();
    log.println("FSSCM.checkout " + path + " to " + workspace);
    Boolean b = Boolean.TRUE;

    AllowDeleteList allowDeleteList = new AllowDeleteList(build.getProject().getRootDir());

    if (clearWorkspace) {
      log.println("FSSCM.clearWorkspace...");
      workspace.deleteRecursive();
    }

    // we will only delete a file if it is listed in the allowDeleteList
    // ie. we will only delete a file if it is copied by us
    if (allowDeleteList.fileExists()) {
      allowDeleteList.load();
    } else {
      // watch list save file doesn't exist
      // we will assuem all existing files are under watch
      // ie. everything can be deleted
      Set<String> existingFiles = workspace.act(new RemoteListDir());
      allowDeleteList.setList(existingFiles);
    }

    RemoteFolderDiff.CheckOut callable = new RemoteFolderDiff.CheckOut();
    setupRemoteFolderDiff(callable, build.getProject(), allowDeleteList.getList());
    List<FolderDiff.Entry> list = workspace.act(callable);

    // maintain the watch list
    for (FolderDiff.Entry entry : list) {
      if (FolderDiff.Entry.Type.DELETED.equals(entry.getType())) {
        allowDeleteList.remove(entry.getFilename());
      } else {
        // added or modified
        allowDeleteList.add(entry.getFilename());
      }
    }
    allowDeleteList.save();

    // raw log
    String str = callable.getLog();
    if (str.length() > 0) log.println(str);

    ChangelogSet.XMLSerializer handler = new ChangelogSet.XMLSerializer();
    ChangelogSet changeLogSet = new ChangelogSet(build, list);
    handler.save(changeLogSet, changelogFile);

    log.println("FSSCM.check completed in " + formatDurration(System.currentTimeMillis() - start));
    return b;
  }
  @Test
  public void assertNoComputeraDoesNotThrowNPEWhenResolvingNodeName() {
    when(launcher.getComputer()).thenReturn(null);

    BuildVariableResolver resolver = new BuildVariableResolver(project, launcher);
    assertNull("Variable resolution was incorrect", resolver.resolve("NODE_NAME"));
    verifyZeroInteractions(project);
  }
  @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;
  }
 /**
  * Writes the configuration file required to opt out of SDK usage statistics gathering.
  *
  * @param launcher Used for running tasks on the remote node.
  * @param listener Used to access logger.
  */
 public static void optOutOfSdkStatistics(
     Launcher launcher, BuildListener listener, String androidSdkHome) {
   Callable<Void, Exception> optOutTask = new StatsOptOutTask(androidSdkHome, listener);
   try {
     launcher.getChannel().call(optOutTask);
   } catch (Exception e) {
     log(listener.getLogger(), "SDK statistics opt-out failed.", e);
   }
 }
Esempio n. 11
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;
  }
  @Test
  public void assertNodeNameIsResolved() {
    Computer computer = mock(Computer.class);
    when(launcher.getComputer()).thenReturn(computer);
    when(computer.getName()).thenReturn("AKIRA");

    BuildVariableResolver resolver = new BuildVariableResolver(project, launcher);
    assertEquals("Variable resolution was incorrect", "AKIRA", resolver.resolve("NODE_NAME"));
    verifyZeroInteractions(project);
  }
  @Override
  public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
      throws InterruptedException, IOException {
    PrintStream logger = listener.getLogger();
    EnvVariableResolver resolver = new EnvVariableResolver(build, listener);

    // Resolve the workflowName to workflowId
    BuildParam buildParam = new BuildParam(serverUrl, userName, password, tenant, null);
    OrchestratorClient client = new OrchestratorClient(buildParam);
    String workflowId = null;
    try {
      String resolvedWfName = resolver.getValueForBuildParameter(workflowName);

      List<Workflow> workflows = client.fetchWorkflows();
      for (Workflow workflow : workflows) {
        if (workflow.getName().equals(resolvedWfName)) {
          workflowId = workflow.getId();
          break;
        }
      }
    } catch (Exception e) {
      throw new IOException(e.getMessage(), e);
    }

    if (workflowId == null) {
      throw new IOException("Workflow doesn't exist in the server.");
    }

    BuildParam param =
        new BuildParam(
            resolver.getValueForBuildParameter(serverUrl),
            resolver.getValueForBuildParameter(userName),
            resolver.getValueForBuildParameter(password),
            resolver.getValueForBuildParameter(tenant),
            workflowId,
            waitExec,
            resolver.getValueForBuildParameter(inputParams));
    logger.println("Starting Orchestrator workflow execution : " + param.getWorkflowName());
    param.validate();

    OrchestratorCallable callable = new OrchestratorCallable(param);
    Map<String, String> outputParameters = launcher.getChannel().call(callable);

    if (outputParameters != null && outputParameters.size() > 0) {
      logger.println("Output Parameters from the workflow execution");
      for (Map.Entry entry : outputParameters.entrySet()) {
        logger.println(entry.getKey() + " : " + entry.getValue());
      }
    }

    OrchestratorEnvAction orchestratorAction = new OrchestratorEnvAction(outputParameters);
    build.addAction(orchestratorAction);

    return true;
  }
Esempio n. 14
0
 public String getSbtLaunchJar(Launcher launcher) throws IOException, InterruptedException {
   return launcher
       .getChannel()
       .call(
           new Callable<String, IOException>() {
             public String call() throws IOException {
               File sbtLaunchJarFile = getSbtLaunchJarFile();
               if (sbtLaunchJarFile.exists()) return sbtLaunchJarFile.getPath();
               return getHome();
             }
           });
 }
  /**
   * Installs the given platform and its dependencies into the given installation, if necessary.
   *
   * @param logger Logs things.
   * @param launcher Used to launch tasks on the remote node.
   * @param sdk SDK installation to install components for.
   * @param platform Specifies the platform to be installed.
   */
  public static void installPlatform(
      PrintStream logger, Launcher launcher, AndroidSdk sdk, String platform)
      throws IOException, InterruptedException {
    // Check whether this platform is already installed
    if (isPlatformInstalled(logger, launcher, sdk, platform)) {
      return;
    }

    // Check whether we are capable of installing individual components
    log(logger, Messages.PLATFORM_INSTALL_REQUIRED(platform));
    if (!launcher.isUnix() && platform.contains(":") && sdk.getSdkToolsVersion() < 16) {
      // SDK add-ons can't be installed on Windows until r16 due to http://b.android.com/18868
      log(logger, Messages.SDK_ADDON_INSTALLATION_UNSUPPORTED());
      return;
    }
    if (!sdk.supportsComponentInstallation()) {
      log(logger, Messages.SDK_COMPONENT_INSTALLATION_UNSUPPORTED());
      return;
    }

    // Automated installation of ABIs (required for android-14+) is not possible until r17, so
    // we should warn the user that we can't automatically set up an AVD with older SDK Tools.
    // See http://b.android.com/21880
    if ((platform.endsWith("14") || platform.endsWith("15"))
        && !sdk.supportsSystemImageInstallation()) {
      log(logger, Messages.ABI_INSTALLATION_UNSUPPORTED(), true);
    }

    // Determine which individual component(s) need to be installed for this platform
    List<String> components = getSdkComponentsForPlatform(logger, platform);
    if (components == null || components.size() == 0) {
      return;
    }

    // If a platform expanded to multiple dependencies (e.g. "GoogleMaps:7" -> android-7 + Maps)
    // then check whether we really need to install android-7, as it may already be installed
    if (components.size() > 1) {
      for (Iterator<String> it = components.iterator(); it.hasNext(); ) {
        String component = it.next();
        if (isPlatformInstalled(logger, launcher, sdk, component)) {
          it.remove();
        }
      }
    }

    // Grab the lock and attempt installation
    Semaphore semaphore = acquireLock();
    try {
      installComponent(logger, launcher, sdk, components.toArray(new String[0]));
    } finally {
      semaphore.release();
    }
  }
Esempio n. 16
0
  private boolean isGpgKeyAvailable(
      GpgKey gpgKey, AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
      throws IOException, InterruptedException {
    ArgumentListBuilder command = new ArgumentListBuilder();
    command.add("gpg", "--fingerprint", gpgKey.getName());
    Launcher.ProcStarter ps = launcher.new ProcStarter();
    ps = ps.cmds(command).stdout(listener);
    ps = ps.pwd(build.getWorkspace()).envs(build.getEnvironment(listener));
    Proc proc = launcher.launch(ps);

    return proc.join() == 0;
  }
  /**
   * Determines whether a snapshot image has already been created for this emulator.
   *
   * @throws IOException If execution of the emulator command fails.
   * @throws InterruptedException If execution of the emulator command is interrupted.
   */
  public boolean hasExistingSnapshot(Launcher launcher, AndroidSdk androidSdk)
      throws IOException, InterruptedException {
    final PrintStream logger = launcher.getListener().getLogger();

    // List available snapshots for this emulator
    ByteArrayOutputStream listOutput = new ByteArrayOutputStream();
    String args = String.format("-snapshot-list -no-window -avd %s", getAvdName());
    Utils.runAndroidTool(launcher, listOutput, logger, androidSdk, Tool.EMULATOR, args, null);

    // Check whether a Jenkins snapshot was listed in the output
    return Pattern.compile(Constants.REGEX_SNAPSHOT).matcher(listOutput.toString()).find();
  }
  @Override
  public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
      throws InterruptedException, IOException {
    EnvVars env = build.getEnvironment(listener);
    FilePath workDir = build.getModuleRoot();
    ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env);
    StringBuilder javaPathBuilder = new StringBuilder();

    JDK configuredJdk = build.getProject().getJDK();
    if (configuredJdk != null) {
      javaPathBuilder
          .append(build.getProject().getJDK().getBinDir().getCanonicalPath())
          .append(File.separator);
    }
    javaPathBuilder.append("java");
    if (!launcher.isUnix()) {
      javaPathBuilder.append(".exe");
    }
    String[] cmds = cmdLine.toCommandArray();
    try {
      // listener.getLogger().println("Executing: " + cmdLine.toStringWithQuote());
      int exitValue =
          launcher
              .launch()
              .cmds(new File(javaPathBuilder.toString()), cmds)
              .envs(env)
              .stdout(listener)
              .pwd(workDir)
              .join();
      boolean success = (exitValue == 0);
      build.setResult(success ? Result.SUCCESS : Result.FAILURE);
      return success;
    } catch (IOException e) {
      Util.displayIOException(e, listener);
      e.printStackTrace(listener.fatalError("command execution failed"));
      build.setResult(Result.FAILURE);
      return false;
    }
  }
  @Test
  public void assertComputerUserNameIsResolved() throws Exception {
    Map<Object, Object> map = new HashMap<Object, Object>();
    map.put("user.name", "Other_user");

    Computer computer = mock(Computer.class);
    when(launcher.getComputer()).thenReturn(computer);
    when(computer.getSystemProperties()).thenReturn(map);

    BuildVariableResolver resolver = new BuildVariableResolver(project, launcher);
    assertEquals("Variable resolution was incorrect", "Other_user", resolver.resolve("USER_NAME"));
    verifyZeroInteractions(project);
  }
  @Test
  public void assertComputerEnvVarIsResolved() throws Exception {
    Map<String, String> map = new HashMap<String, String>();
    map.put("ENV_VAR", "This is an env var");

    Computer computer = mock(Computer.class);
    when(launcher.getComputer()).thenReturn(computer);
    when(computer.getEnvVars()).thenReturn(map);

    BuildVariableResolver resolver = new BuildVariableResolver(project, launcher);
    assertEquals(
        "Variable resolution was incorrect", "This is an env var", resolver.resolve("ENV_VAR"));
    verifyZeroInteractions(project);
  }
Esempio n. 21
0
    @SuppressWarnings("serial")
    public String getExecutable(Launcher launcher) throws IOException, InterruptedException {
      return launcher
          .getChannel()
          .call(
              new Callable<String, IOException>() {
                public String call() throws IOException {
                  File exe = getExecutableFile();
                  if (exe.exists()) return exe.getPath();

                  throw new IOException(exe.getPath() + " doesn't exist");
                }
              });
    }
    /**
     * 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();
        }
      }
    }
  /**
   * Determines the Android platform for an existing emulator, via its metadata config file.
   *
   * @param launcher Used to access files on the remote node.
   * @param emuConfig The emulator whose target platform we want to determine.
   * @return The platform identifier.
   */
  private static String getPlatformFromExistingEmulator(
      Launcher launcher, final EmulatorConfig emuConfig) throws IOException, InterruptedException {
    return launcher
        .getChannel()
        .call(
            new Callable<String, IOException>() {
              public String call() throws IOException {
                File metadataFile = emuConfig.getAvdMetadataFile();
                Map<String, String> metadata = Utils.parseConfigFile(metadataFile);
                return metadata.get("target");
              }

              private static final long serialVersionUID = 1L;
            });
  }
Esempio n. 24
0
 private String getStaticManifest(
     final Launcher launcher, final FilePath workspace, final OutputStream logger)
     throws IOException, InterruptedException {
   final ByteArrayOutputStream output = new ByteArrayOutputStream();
   final List<String> commands = new ArrayList<String>(6);
   commands.add(getDescriptor().getExecutable());
   commands.add("manifest");
   commands.add("-o");
   commands.add("-");
   commands.add("-r");
   // TODO: should we pay attention to the output from this?
   launcher.launch().stderr(logger).stdout(output).pwd(workspace).cmds(commands).join();
   final String manifestText = output.toString();
   debug.log(Level.FINEST, manifestText);
   return manifestText;
 }
Esempio n. 25
0
  private void importGpgKey(
      String privateKey, AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
      throws InterruptedException, IOException {
    ArgumentListBuilder command = new ArgumentListBuilder();
    command.add("gpg", "--import", "-");
    Launcher.ProcStarter ps = launcher.new ProcStarter();
    ps = ps.cmds(command).stdout(listener);
    ps = ps.pwd(build.getWorkspace()).envs(build.getEnvironment(listener));

    InputStream is = new ByteArrayInputStream(privateKey.getBytes());

    ps.stdin(is);
    Proc proc = launcher.launch(ps);
    proc.join();
    is.close();
  }
Esempio n. 26
0
 private Proc startFitnesse(
     AbstractBuild<?, ?> build,
     Launcher launcher,
     EnvVars envVars,
     PrintStream logger,
     StdConsole console)
     throws IOException {
   logger.println("Starting new Fitnesse instance...");
   ProcStarter procStarter =
       launcher.launch().cmds(getJavaCmd(getWorkingDirectory(build), envVars));
   procStarter.pwd(
       new File(
           getAbsolutePathToFileThatMayBeRelativeToWorkspace(
               getWorkingDirectory(build), builder.getFitnesseJavaWorkingDirectory())));
   console.provideStdOutAndStdErrFor(procStarter);
   return procStarter.start();
 }
Esempio n. 27
0
  private void whatchanged(
      String revFrom, String revTo, OutputStream outputStream, String... extraargs)
      throws GitException {
    String revSpec = revFrom + ".." + revTo;

    ArgumentListBuilder args = new ArgumentListBuilder();
    args.add(getGitExe(), "whatchanged");
    args.add(extraargs);
    args.add(revSpec);

    try {
      if (launcher.launch().cmds(args).envs(environment).stdout(outputStream).pwd(workspace).join()
          != 0) {
        throw new GitException("Error launching git whatchanged");
      }
    } catch (Exception e) {
      throw new GitException("Error performing git whatchanged", e);
    }
  }
Esempio n. 28
0
  /**
   * **************************************************
   *
   * <p>private ProcStarter l(ArgumentListBuilder args)
   *
   * <p>**************************************************
   */
  private ProcStarter l(ArgumentListBuilder args) {
    String consoleString = "  RTC SCM - Jazz Client: Launching scm.exe...\n";
    boolean[] maskArray = args.toMaskArray();
    String[] cmdArray = args.toCommandArray();

    for (int i = 0; i < maskArray.length; i++) {
      if (maskArray[i] == false) {
        consoleString += cmdArray[i] + " ";
      } else {
        consoleString += "**** ";
      }
    }

    // output to console.
    PrintStream output = listener.getLogger();
    // output.println(consoleString);

    // set the default stdout
    return launcher.launch().cmds(args).stdout(listener);
  }
Esempio n. 29
0
 private int doSync(final Launcher launcher, final FilePath workspace, final OutputStream logger)
     throws IOException, InterruptedException {
   final List<String> commands = new ArrayList<String>(4);
   debug.log(Level.FINE, "Syncing out code in: " + workspace.getName());
   commands.clear();
   commands.add(getDescriptor().getExecutable());
   commands.add("sync");
   commands.add("-d");
   if (isCurrentBranch()) {
     commands.add("-c");
   }
   if (isQuiet()) {
     commands.add("-q");
   }
   if (jobs > 0) {
     commands.add("--jobs=" + jobs);
   }
   int returnCode = launcher.launch().stdout(logger).pwd(workspace).cmds(commands).join();
   return returnCode;
 }
Esempio n. 30
0
  /**
   * Perform the sbt build. Interpret the command arguments and create a command line, then run it.
   */
  @Override
  public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {

    EnvVars env = null;
    FilePath workDir = build.getModuleRoot();
    try {

      ArgumentListBuilder cmdLine = buildCmdLine(build, launcher, listener);
      String[] cmds = cmdLine.toCommandArray();
      env = build.getEnvironment(listener);

      if (subdirPath != null && subdirPath.length() > 0) {
        workDir = new FilePath(workDir, subdirPath);
      }

      int exitValue = launcher.launch().cmds(cmds).envs(env).stdout(listener).pwd(workDir).join();

      boolean success = (exitValue == 0);
      build.setResult(success ? Result.SUCCESS : Result.FAILURE);
      return success;
    } catch (IllegalArgumentException e) {
      // Util.displayIOException(e, listener);
      e.printStackTrace(listener.fatalError("command execution failed: " + e.getMessage()));
      build.setResult(Result.FAILURE);
      return false;
    } catch (IOException e) {
      Util.displayIOException(e, listener);
      e.printStackTrace(listener.fatalError("command execution failed: " + e.getMessage()));
      build.setResult(Result.FAILURE);
      return false;
    } catch (InterruptedException e) {
      // Util.displayIOException(e, listener);
      e.printStackTrace(listener.fatalError("command execution failed: " + e.getMessage()));
      build.setResult(Result.ABORTED);
      return false;
    }
  }