/**
   * Record the test results into the current build.
   *
   * @param junitFilePattern
   * @param build
   * @param listener
   * @return
   * @throws InterruptedException
   * @throws IOException
   */
  private boolean recordTestResult(
      String junitFilePattern, AbstractBuild<?, ?> build, BuildListener listener)
      throws InterruptedException, IOException {
    TestResultAction existingAction = build.getAction(TestResultAction.class);
    TestResultAction action;

    try {
      final long buildTime = build.getTimestamp().getTimeInMillis();

      TestResult existingTestResults = null;
      if (existingAction != null) {
        existingTestResults = existingAction.getResult();
      }
      TestResult result = getTestResult(junitFilePattern, build, existingTestResults, buildTime);

      if (existingAction == null) {
        action = new TestResultAction(build, result, listener);
      } else {
        action = existingAction;
        action.setResult(result, listener);
      }
      if (result.getPassCount() == 0 && result.getFailCount() == 0)
        new AbortException("None of the test reports contained any result");
    } catch (AbortException e) {
      if (build.getResult() == Result.FAILURE)
        // most likely a build failed before it gets to the test phase.
        // don't report confusing error message.
        return true;

      listener.getLogger().println(e.getMessage());
      build.setResult(Result.FAILURE);
      return true;
    }

    if (existingAction == null) {
      build.getActions().add(action);
    }

    if (action.getResult().getFailCount() > 0) build.setResult(Result.UNSTABLE);

    return true;
  }
Esempio n. 2
0
    private void checkout(BuildListener listener) throws Exception {
      try {
        for (int retryCount = project.getScmCheckoutRetryCount(); ; retryCount--) {
          // for historical reasons, null in the scm field means CVS, so we need to explicitly set
          // this to something
          // in case check out fails and leaves a broken changelog.xml behind.
          // see
          // http://www.nabble.com/CVSChangeLogSet.parse-yields-SAXParseExceptions-when-parsing-bad-*AccuRev*-changelog.xml-files-td22213663.html
          AbstractBuild.this.scm = new NullChangeLogParser();

          try {
            if (project.checkout(
                AbstractBuild.this, launcher, listener, new File(getRootDir(), "changelog.xml"))) {
              // check out succeeded
              SCM scm = project.getScm();

              AbstractBuild.this.scm = scm.createChangeLogParser();
              AbstractBuild.this.changeSet = AbstractBuild.this.calcChangeSet();

              for (SCMListener l : Hudson.getInstance().getSCMListeners())
                l.onChangeLogParsed(AbstractBuild.this, listener, changeSet);
              return;
            }
          } catch (AbortException e) {
            listener.error(e.getMessage());
          } catch (IOException e) {
            // checkout error not yet reported
            e.printStackTrace(listener.getLogger());
          }

          if (retryCount == 0) // all attempts failed
          throw new RunnerAbortedException();

          listener.getLogger().println("Retrying after 10 seconds");
          Thread.sleep(10000);
        }
      } catch (InterruptedException e) {
        listener.getLogger().println(Messages.AbstractProject_ScmAborted());
        LOGGER.log(Level.INFO, AbstractBuild.this + " aborted", e);
        throw new RunnerAbortedException();
      }
    }
Esempio n. 3
0
  /**
   * Entry point to the CLI command.
   *
   * <p>The default implementation uses args4j to parse command line arguments and call {@link
   * #run()}, but if that processing is undesirable, subtypes can directly override this method and
   * leave {@link #run()} to an empty method.
   *
   * @param args Arguments to the sub command. For example, if the CLI is invoked like "java -jar
   *     cli.jar foo bar zot", then "foo" is the sub-command and the argument list is ["bar","zot"].
   * @param locale Locale of the client (which can be different from that of the server.) Good
   *     behaving command implementation would use this locale for formatting messages.
   * @param stdin Connected to the stdin of the CLI client.
   * @param stdout Connected to the stdout of the CLI client.
   * @param stderr Connected to the stderr of the CLI client.
   * @return Exit code from the command.
   */
  public int main(
      List<String> args, Locale locale, InputStream stdin, PrintStream stdout, PrintStream stderr) {
    this.stdin = new BufferedInputStream(stdin);
    this.stdout = stdout;
    this.stderr = stderr;
    this.locale = locale;
    registerOptionHandlers();
    CmdLineParser p = getCmdLineParser();

    // add options from the authenticator
    SecurityContext sc = SecurityContextHolder.getContext();
    Authentication old = sc.getAuthentication();

    CliAuthenticator authenticator =
        Jenkins.getInstance().getSecurityRealm().createCliAuthenticator(this);
    sc.setAuthentication(getTransportAuthentication());
    new ClassParser().parse(authenticator, p);

    try {
      p.parseArgument(args.toArray(new String[args.size()]));
      Authentication auth = authenticator.authenticate();
      if (auth == Jenkins.ANONYMOUS) auth = loadStoredAuthentication();
      sc.setAuthentication(auth); // run the CLI with the right credential
      if (!(this instanceof LoginCommand || this instanceof HelpCommand))
        Jenkins.getInstance().checkPermission(Jenkins.READ);
      return run();
    } catch (CmdLineException e) {
      stderr.println(e.getMessage());
      printUsage(stderr, p);
      return -1;
    } catch (AbortException e) {
      // signals an error without stack trace
      stderr.println(e.getMessage());
      return -1;
    } catch (Exception e) {
      e.printStackTrace(stderr);
      return -1;
    } finally {
      sc.setAuthentication(old); // restore
    }
  }
    @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;
      }
    }