private static void screenCaptureToFile(AbstractBuild build, AndroidDeviceContext device)
     throws IOException, InterruptedException {
   FilePath screencapFile = build.getWorkspace().createTempFile("screencap", ".png");
   OutputStream screencapStream = screencapFile.write();
   FilterOutputStream replaceFilterStream = new ReplaceFilterOutputStream(screencapStream);
   device.screenshot(replaceFilterStream);
   screencapFile.copyTo(new FilePath(build.getArtifactsDir()).child("screencap.png"));
 }
  public void addExecFiles(Iterable<FilePath> execFiles) throws IOException, InterruptedException {
    FilePath root = new FilePath(getExecFilesDir());
    int i = 0;
    for (FilePath file : execFiles) {
      FilePath separateExecDir;
      do {
        separateExecDir = new FilePath(root, "exec" + (i++));
      } while (separateExecDir.exists());

      FilePath fullExecName = separateExecDir.child("jacoco.exec");
      file.copyTo(fullExecName);
    }
  }
示例#3
0
    @WebMethod(name = "heapdump.hprof")
    public void doHeapDump(StaplerRequest req, StaplerResponse rsp)
        throws IOException, InterruptedException {
      owner.checkPermission(Jenkins.RUN_SCRIPTS);
      rsp.setContentType("application/octet-stream");

      FilePath dump = obtain();
      try {
        dump.copyTo(rsp.getCompressedOutputStream(req));
      } finally {
        dump.delete();
      }
    }
  /**
   * copy from MavenUtil but here we have to ignore localRepo path and setting as thoses paths comes
   * from the remote node and can not exist in master see
   * http://issues.jenkins-ci.org/browse/JENKINS-8711
   */
  private MavenEmbedder createEmbedder(TaskListener listener, AbstractBuild<?, ?> build)
      throws MavenEmbedderException, IOException, InterruptedException {
    MavenInstallation m = null;
    File settingsLoc = null, remoteGlobalSettingsFromConfig = null;
    String profiles = null;
    Properties systemProperties = null;
    String privateRepository = null;
    FilePath remoteSettingsFromConfig = null;

    File tmpSettings = File.createTempFile("jenkins", "temp-settings.xml");
    try {
      AbstractProject project = build.getProject();

      if (project instanceof MavenModuleSet) {
        MavenModuleSet mavenModuleSet = ((MavenModuleSet) project);
        profiles = mavenModuleSet.getProfiles();
        systemProperties = mavenModuleSet.getMavenProperties();

        // olamy see
        // we have to take about the settings use for the project
        // order tru configuration
        // TODO maybe in goals with -s,--settings last wins but not done in during pom parsing
        // or -Dmaven.repo.local
        // if not we must get ~/.m2/settings.xml then $M2_HOME/conf/settings.xml

        // TODO check if the remoteSettings has a localRepository configured and disabled it

        String settingsConfigId = mavenModuleSet.getSettingConfigId();
        String altSettingsPath = null;

        if (!StringUtils.isBlank(settingsConfigId)) {
          Config config =
              SettingsProviderUtils.findConfig(settingsConfigId, MavenSettingsProvider.class);
          if (config == null) {
            listener
                .getLogger()
                .println(
                    " your Apache Maven build is setup to use a config with id "
                        + settingsConfigId
                        + " but cannot find the config");
          } else {
            listener
                .getLogger()
                .println("redeploy publisher using settings config with name " + config.name);
            String settingsContent = config.content;
            if (config.content != null) {
              remoteSettingsFromConfig =
                  SettingsProviderUtils.copyConfigContentToFilePath(config, build.getWorkspace());
              altSettingsPath = remoteSettingsFromConfig.getRemote();
            }
          }
        }

        if (mavenModuleSet.getAlternateSettings() != null) {
          altSettingsPath = mavenModuleSet.getAlternateSettings();
        }

        String globalSettingsConfigId = mavenModuleSet.getGlobalSettingConfigId();
        if (!StringUtils.isBlank(globalSettingsConfigId)) {
          Config config =
              SettingsProviderUtils.findConfig(
                  globalSettingsConfigId, GlobalMavenSettingsProvider.class);
          if (config == null) {
            listener
                .getLogger()
                .println(
                    " your Apache Maven build is setup to use a global settings config with id "
                        + globalSettingsConfigId
                        + " but cannot find the config");
          } else {
            listener
                .getLogger()
                .println(
                    "redeploy publisher using global settings config with name " + config.name);
            if (config.content != null) {
              remoteGlobalSettingsFromConfig =
                  SettingsProviderUtils.copyConfigContentToFile(config);
            }
          }
        }
        Node buildNode = build.getBuiltOn();

        if (buildNode == null) {
          // assume that build was made on master
          buildNode = Jenkins.getInstance();
        }

        if (StringUtils.isBlank(altSettingsPath)) {
          // get userHome from the node where job has been executed
          String remoteUserHome = build.getWorkspace().act(new GetUserHome());
          altSettingsPath = remoteUserHome + "/.m2/settings.xml";
        }

        // we copy this file in the master in a  temporary file
        FilePath filePath = new FilePath(tmpSettings);
        FilePath remoteSettings = build.getWorkspace().child(altSettingsPath);
        if (!remoteSettings.exists()) {
          // JENKINS-9084 we finally use $M2_HOME/conf/settings.xml as maven do

          String mavenHome =
              ((MavenModuleSet) project).getMaven().forNode(buildNode, listener).getHome();
          String settingsPath = mavenHome + "/conf/settings.xml";
          remoteSettings = build.getWorkspace().child(settingsPath);
        }
        listener
            .getLogger()
            .println(
                "Maven RedeployPublished use remote "
                    + (buildNode != null ? buildNode.getNodeName() : "local")
                    + " maven settings from : "
                    + remoteSettings.getRemote());
        remoteSettings.copyTo(filePath);
        settingsLoc = tmpSettings;
      }

      MavenEmbedderRequest mavenEmbedderRequest =
          new MavenEmbedderRequest(
              listener,
              m != null ? m.getHomeDir() : null,
              profiles,
              systemProperties,
              privateRepository,
              settingsLoc);

      if (remoteGlobalSettingsFromConfig != null) {
        mavenEmbedderRequest.setGlobalSettings(remoteGlobalSettingsFromConfig);
      }

      mavenEmbedderRequest.setTransferListener(
          new ConsoleMavenTransferListener(listener.getLogger()));

      return MavenUtil.createEmbedder(mavenEmbedderRequest);
    } finally {
      if (tmpSettings != null) {
        tmpSettings.delete();
      }
      if (remoteSettingsFromConfig != null) {
        remoteSettingsFromConfig.delete();
      }
      FileUtils.deleteQuietly(remoteGlobalSettingsFromConfig);
    }
  }
  private int archiveArtifacts(Collection<ArtifactDTO> artifacts) {
    int count = 0;

    FilePath workspace = build.getWorkspace();
    // Check if workspace exists.
    if (null == workspace) {
      muxlog.error("Missing workspace to archive artifacts from.");
      // TODO: consider this a failure?
      // build.setResult(Result.FAILURE);
      return count;
    }

    try {
      FilePath archiveDirectory = new FilePath(build.getArtifactsDir());
      archiveDirectory.mkdirs();
      log.debug("Archiving to {}", archiveDirectory);

      VirtualChannel channel = workspace.getChannel();
      for (ArtifactDTO artifact : artifacts) {
        if (null != artifact.getCreatedProject() && maybeIncludePom(artifact)) {
          MavenCoordinatesDTO gav = artifact.getCoordinates();

          // File information for the artifact.
          File file = ArtifactDTOHelper.getFile(artifact);
          // TODO: filter out nulls when generating the artifact list; i.e. at ArtifactRecorder
          if (file != null) {
            // Executing on the master; do not try to canonicalize the path since it could have been
            // defined
            // from a remote file system that is not the same as the masters.  E.g. master being
            // linux,
            // remote being windows.
            // TODO: consider making a FilePath constructor using channel and file and extract the
            // path
            // so that users don't have to think about differences between canonical, absolute, and
            // path.
            FilePath source = new FilePath(channel, file.getPath());

            // Store in archive using a similar format as a Maven repository.
            FilePath target =
                archiveDirectory
                    .child(gav.getGroupId())
                    .child(gav.getArtifactId())
                    .child(gav.getVersion())
                    // Resolve source filename using the same node that created the file.  This
                    // should
                    // ensure that the name portion is properly extracted since the file system is
                    // the same.
                    .child(source.getName());

            if (log.isTraceEnabled()) {
              // Separate calls to get more info when there are failures.
              log.trace("Created path to archive: {} on channel {}", target, target.getChannel());
              log.trace(
                  "Copying FROM {} on channel {} TO {} on channel {}",
                  $(source, source.getChannel(), target, target.getChannel()));
            }

            source.copyTo(target);
            // TODO: catch IOException and continue with rest of artifacts?
            artifact.withArchivedFile(target.getRemote());
            count++;
          } else {
            muxlog.error("Failed to archive Maven 3 artifact {} -" + " unresolved.", gav);
          }
        }
      }
    }
    // No need to stop the build due to these exceptions.
    catch (IOException e) {
      Util.displayIOException(e, listener);
      muxlog.error("Failed to archive Maven 3 artifacts", e);
    } catch (InterruptedException e) {
      muxlog.error("Failed to archive Maven 3 artifacts", e);
    }

    return count;
  }
  /** {@inheritDoc} */
  public boolean perform(Build<?, ?> build, Launcher launcher, BuildListener listener)
      throws InterruptedException, IOException {
    if (coverageReportPattern == null) {
      listener.getLogger().println("Skipping coverage reports as coverageReportPattern is null");
      return false;
    }
    if (!Result.SUCCESS.equals(build.getResult())) {
      listener.getLogger().println("Skipping coverage reports as the build was not successful...");
      return true;
    }

    listener.getLogger().println("Publishing PureCoverage reports...");
    FilePath buildTarget = new FilePath(build.getRootDir());

    FilePath[] reports = new FilePath[0];
    final FilePath moduleRoot = build.getParent().getWorkspace();
    try {
      reports = moduleRoot.list(coverageReportPattern);
    } catch (IOException e) {
      Util.displayIOException(e, listener);
      e.printStackTrace(listener.fatalError("Unable to find PureCoverage results"));
      build.setResult(Result.FAILURE);
    }

    if (reports.length == 0) {
      listener
          .getLogger()
          .println(
              "No coverage results were found using the pattern '"
                  + coverageReportPattern
                  + "'.  Did you generate the report(s)?");
      build.setResult(Result.FAILURE);
      return true;
    }

    if (reports.length > 1) {
      listener
          .getLogger()
          .println(
              "PureCoverage publisher found more than one report that match the pattern. "
                  + "Currently, accumulating PureCoverage results is not implemented!");
      build.setResult(Result.FAILURE);
      return true;
    }

    FilePath singleReport = reports[0];
    final FilePath targetPath = new FilePath(buildTarget, CoverageReportsFinder.COVERAGE_PREFIX);
    try {
      singleReport.copyTo(targetPath);
    } catch (IOException e) {
      Util.displayIOException(e, listener);
      e.printStackTrace(
          listener.fatalError(
              "Unable to copy coverage from " + singleReport + " to " + buildTarget));
      build.setResult(Result.FAILURE);
    }

    listener.getLogger().println("Parsing PureCoverage results...");
    ProjectCoverage projectCoverage = null;
    CoverageReportsFinder finder = new CoverageReportsFinder();
    for (File coverageResult : finder.findReports(build)) {
      try {
        CoverageParser coverageParser = new PureCoverageParser();
        projectCoverage = coverageParser.parse(coverageResult);
      } catch (IOException e) {
        Util.displayIOException(e, listener);
        e.printStackTrace(listener.fatalError("Unable to parse " + coverageResult));
        build.setResult(Result.FAILURE);
        return false;
      }
    }

    CoverageResult coverageResult = new CoverageResult(build, projectCoverage);
    build.getActions().add(new CoverageBuildAction(build, coverageResult));

    return true;
  }