Exemple #1
0
    private boolean runPolling() {
      try {
        // to make sure that the log file contains up-to-date text,
        // don't do buffering.
        StreamTaskListener listener = new StreamTaskListener(getLogFile());

        try {
          PrintStream logger = listener.getLogger();
          long start = System.currentTimeMillis();
          logger.println("Started on " + DateFormat.getDateTimeInstance().format(new Date()));
          boolean result = job.poll(listener).hasChanges();
          logger.println(
              "Done. Took " + Util.getTimeSpanString(System.currentTimeMillis() - start));
          if (result) logger.println("Changes found");
          else logger.println("No changes");
          return result;
        } catch (Error e) {
          e.printStackTrace(listener.error("Failed to record SCM polling"));
          LOGGER.log(Level.SEVERE, "Failed to record SCM polling", e);
          throw e;
        } catch (RuntimeException e) {
          e.printStackTrace(listener.error("Failed to record SCM polling"));
          LOGGER.log(Level.SEVERE, "Failed to record SCM polling", e);
          throw e;
        } finally {
          listener.close();
        }
      } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Failed to record SCM polling", e);
        return false;
      }
    }
  /**
   * Collect reports from the given {@link DirectoryScanner}, while filtering out all files that
   * were created before the given time.
   */
  public void parse(long buildTime, DirectoryScanner results) throws IOException {
    String[] includedFiles = results.getIncludedFiles();
    File baseDir = results.getBasedir();

    boolean parsed = false;

    for (String value : includedFiles) {
      File reportFile = new File(baseDir, value);
      // only count files that were actually updated during this build
      if ((buildTime - 3000 /*error margin*/ <= reportFile.lastModified()) || !checkTimestamps) {
        if (reportFile.length() == 0) {
          // this is a typical problem when JVM quits abnormally, like OutOfMemoryError during a
          // test.
          SuiteResult sr = new SuiteResult(reportFile.getName(), "", "");
          sr.addCase(
              new CaseResult(
                  sr,
                  "<init>",
                  "Test report file " + reportFile.getAbsolutePath() + " was length 0"));
          TestResult testResult = new TestResult(this, "(unknown)", sr);
          childrenBySuiteName.put(testResult.getName(), testResult);
        } else {
          parse(reportFile);
        }
        parsed = true;
      }
    }

    if (!parsed) {
      long localTime = System.currentTimeMillis();
      if (localTime < buildTime - 1000) /*margin*/
        // build time is in the the future. clock on this slave must be running behind
        throw new AbortException(
            "Clock on this slave is out of sync with the master, and therefore \n"
                + "I can't figure out what test results are new and what are old.\n"
                + "Please keep the slave clock in sync with the master.");

      File f = new File(baseDir, includedFiles[0]);
      throw new AbortException(
          String.format(
              "Test reports were found but none of them are new. Did tests run? \n"
                  + "For example, %s is %s old\n",
              f, Util.getTimeSpanString(buildTime - f.lastModified())));
    }
  }
    @Override
    @GuardedBy("hudson.model.Queue.lock")
    public long check(final SlaveComputer c) {
      if (c.isOffline() && c.isLaunchSupported()) {
        final HashMap<Computer, Integer> availableComputers = new HashMap<Computer, Integer>();
        for (Computer o : Jenkins.getInstance().getComputers()) {
          if ((o.isOnline() || o.isConnecting()) && o.isPartiallyIdle() && o.isAcceptingTasks()) {
            final int idleExecutors = o.countIdle();
            if (idleExecutors > 0) availableComputers.put(o, idleExecutors);
          }
        }

        boolean needComputer = false;
        long demandMilliseconds = 0;
        for (Queue.BuildableItem item : Queue.getInstance().getBuildableItems()) {
          // can any of the currently idle executors take this task?
          // assume the answer is no until we can find such an executor
          boolean needExecutor = true;
          for (Computer o : Collections.unmodifiableSet(availableComputers.keySet())) {
            Node otherNode = o.getNode();
            if (otherNode != null && otherNode.canTake(item) == null) {
              needExecutor = false;
              final int availableExecutors = availableComputers.remove(o);
              if (availableExecutors > 1) {
                availableComputers.put(o, availableExecutors - 1);
              } else {
                availableComputers.remove(o);
              }
              break;
            }
          }

          // this 'item' cannot be built by any of the existing idle nodes, but it can be built by
          // 'c'
          Node checkedNode = c.getNode();
          if (needExecutor && checkedNode != null && checkedNode.canTake(item) == null) {
            demandMilliseconds = System.currentTimeMillis() - item.buildableStartMilliseconds;
            needComputer = demandMilliseconds > inDemandDelay * 1000 * 60 /*MINS->MILLIS*/;
            break;
          }
        }

        if (needComputer) {
          // we've been in demand for long enough
          logger.log(
              Level.INFO,
              "Launching computer {0} as it has been in demand for {1}",
              new Object[] {c.getName(), Util.getTimeSpanString(demandMilliseconds)});
          c.connect(false);
        }
      } else if (c.isIdle()) {
        final long idleMilliseconds = System.currentTimeMillis() - c.getIdleStartMilliseconds();
        if (idleMilliseconds > idleDelay * 1000 * 60 /*MINS->MILLIS*/) {
          // we've been idle for long enough
          logger.log(
              Level.INFO,
              "Disconnecting computer {0} as it has been idle for {1}",
              new Object[] {c.getName(), Util.getTimeSpanString(idleMilliseconds)});
          c.disconnect(new OfflineCause.IdleOfflineCause());
        } else {
          // no point revisiting until we can be confident we will be idle
          return TimeUnit.MILLISECONDS.toMinutes(
              TimeUnit.MINUTES.toMillis(idleDelay) - idleMilliseconds);
        }
      }
      return 1;
    }
 /** Gets the string that says how long did it toook for this build to be promoted. */
 public String getDelayString(AbstractBuild<?, ?> owner) {
   long duration =
       timestamp.getTimeInMillis() - owner.getTimestamp().getTimeInMillis() - owner.getDuration();
   return Util.getTimeSpanString(duration);
 }
 /**
  * Gets the string that says how long since this promotion had happened.
  *
  * @return string like "3 minutes" "1 day" etc.
  */
 public String getTimestampString() {
   long duration = new GregorianCalendar().getTimeInMillis() - timestamp.getTimeInMillis();
   return Util.getTimeSpanString(duration);
 }
Exemple #6
0
 @Override
 public String getWhy() {
   long diff = timestamp.getTimeInMillis() - System.currentTimeMillis();
   if (diff > 0) return Messages.Queue_InQuietPeriod(Util.getTimeSpanString(diff));
   else return Messages.Queue_Unknown();
 }
  public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
      throws InterruptedException, IOException {
    if (build.getResult().isWorseThan(getTreshold())) return true; // build failed. Don't publish

    List<MavenAbstractArtifactRecord> mavenAbstractArtifactRecords = getActions(build, listener);
    if (mavenAbstractArtifactRecords == null || mavenAbstractArtifactRecords.isEmpty()) {
      listener.getLogger().println("[ERROR] No artifacts are recorded. Is this a Maven project?");
      build.setResult(Result.FAILURE);
      return true;
    }

    if (build instanceof MavenModuleSetBuild
        && ((MavenModuleSetBuild) build).getParent().isArchivingDisabled()) {
      listener
          .getLogger()
          .println(
              "[ERROR] You cannot use the \"Deploy artifacts to Maven repository\" feature if you "
                  + "disabled automatic artifact archiving");
      build.setResult(Result.FAILURE);
      return true;
    }

    long startupTime = Calendar.getInstance().getTimeInMillis();

    try {
      MavenEmbedder embedder = createEmbedder(listener, build);
      ArtifactRepositoryLayout layout =
          (ArtifactRepositoryLayout) embedder.lookup(ArtifactRepositoryLayout.ROLE, "default");
      ArtifactRepositoryFactory factory =
          (ArtifactRepositoryFactory) embedder.lookup(ArtifactRepositoryFactory.ROLE);
      ArtifactRepository artifactRepository = null;
      if (url != null) {
        // By default we try to get the repository definition from the job configuration
        artifactRepository = getDeploymentRepository(factory, layout, id, url);
      }
      for (MavenAbstractArtifactRecord mavenAbstractArtifactRecord : mavenAbstractArtifactRecords) {
        if (artifactRepository == null
            && mavenAbstractArtifactRecord instanceof MavenArtifactRecord) {
          // If no repository definition is set on the job level we try to take it from the POM
          MavenArtifactRecord mavenArtifactRecord =
              (MavenArtifactRecord) mavenAbstractArtifactRecord;
          artifactRepository =
              getDeploymentRepository(
                  factory,
                  layout,
                  mavenArtifactRecord.repositoryId,
                  mavenArtifactRecord.repositoryUrl);
        }
        if (artifactRepository == null) {
          listener
              .getLogger()
              .println(
                  "[ERROR] No Repository settings defined in the job configuration or distributionManagement of the module.");
          build.setResult(Result.FAILURE);
          return true;
        }
        mavenAbstractArtifactRecord.deploy(embedder, artifactRepository, listener);
      }
      listener
          .getLogger()
          .println(
              "[INFO] Deployment done in "
                  + Util.getTimeSpanString(Calendar.getInstance().getTimeInMillis() - startupTime));
      return true;
    } catch (MavenEmbedderException e) {
      e.printStackTrace(listener.error(e.getMessage()));
    } catch (ComponentLookupException e) {
      e.printStackTrace(listener.error(e.getMessage()));
    } catch (ArtifactDeploymentException e) {
      e.printStackTrace(listener.error(e.getMessage()));
    }
    // failed
    build.setResult(Result.FAILURE);
    listener
        .getLogger()
        .println(
            "[INFO] Deployment failed after "
                + Util.getTimeSpanString(Calendar.getInstance().getTimeInMillis() - startupTime));
    return true;
  }
Exemple #8
0
 /** Returns a human-readable string representation of when this user was last active. */
 public String getLastChangeTimeString() {
   if (lastChange == null) return "N/A";
   long duration = new GregorianCalendar().getTimeInMillis() - ordinal();
   return Util.getTimeSpanString(duration);
 }
Exemple #9
0
 /** Human readable string of when this polling is started. */
 public String getDuration() {
   return Util.getTimeSpanString(System.currentTimeMillis() - startTime);
 }