예제 #1
0
  public void setBuildOpts(Workspace workspace) throws AbortException {

    ClientHelper p4 = new ClientHelper(credential, listener, client);

    try {
      // setup the client workspace to use for the build.
      if (!p4.setClient(workspace)) {
        String err = "Undefined workspace: " + workspace.getFullName();
        logger.severe(err);
        listener.error(err);
        throw new AbortException(err);
      }

      // fetch and calculate change to sync to or review to unshelve.
      status = getStatus(workspace);
      head = p4.getClientHead();
      review = getReview(workspace);
      buildChange = getBuildChange(workspace);

    } catch (Exception e) {
      String err = "Unable to setup workspace: " + e;
      logger.severe(err);
      listener.error(err);
      throw new AbortException(err);
    } finally {
      p4.disconnect();
    }
  }
  @Override
  public void run() {
    ReviewInput reviewInput = createReview();

    String reviewEndpoint = resolveEndpointURL();

    HttpPost httpPost = createHttpPostEntity(reviewInput, reviewEndpoint);

    if (httpPost == null) {
      return;
    }

    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient
        .getCredentialsProvider()
        .setCredentials(
            new AuthScope(null, -1),
            new UsernamePasswordCredentials(
                config.getGerritHttpUserName(), config.getGerritHttpPassword()));
    try {
      HttpResponse httpResponse = httpclient.execute(httpPost);
      String response = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");
      listener.getLogger().print(response);
      if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        listener.error(httpResponse.getStatusLine().getReasonPhrase());
      }
    } catch (Exception e) {
      listener.error("Failed to submit result", e);
    }
  }
예제 #3
0
  /**
   * Fetch information from a particular remote repository. Attempt to fetch from submodules, if
   * they exist in the local WC
   *
   * @param git
   * @param listener
   * @param remoteRepository
   * @throws
   */
  private void fetchFrom(
      IGitAPI git, File workspace, TaskListener listener, RemoteConfig remoteRepository) {
    try {
      listener.getLogger().println("Fetching from " + remoteRepository.getName());
      git.fetch(remoteRepository);

      List<IndexEntry> submodules = new GitUtils(listener, git).getSubmodules("HEAD");

      for (IndexEntry submodule : submodules) {
        try {
          RemoteConfig submoduleRemoteRepository =
              getSubmoduleRepository(remoteRepository, submodule.getFile());

          File subdir = new File(workspace, submodule.getFile());
          IGitAPI subGit =
              new GitAPI(git.getGitExe(), new FilePath(subdir), listener, git.getEnvironment());

          subGit.fetch(submoduleRemoteRepository);
        } catch (Exception ex) {
          listener.error(
              "Problem fetching from "
                  + remoteRepository.getName()
                  + " - could be unavailable. Continuing anyway");
        }
      }
    } catch (GitException ex) {
      listener.error(
          "Problem fetching from "
              + remoteRepository.getName()
              + " / "
              + remoteRepository.getName()
              + " - could be unavailable. Continuing anyway");
    }
  }
 @Override
 protected void launch(EC2Computer computer, TaskListener listener, Instance inst)
     throws AmazonClientException, IOException, InterruptedException {
   int processedTime = 0;
   JIException exception = null;
   // TODO 自動生成されたメソッド・スタブ
   this.host = getHostName(computer);
   while (TIMEOUT > processedTime) {
     try {
       wmiLaunch(computer, listener);
       return;
     } catch (JIException e) {
       listener.getLogger().println("Waiting for DCOM to come up. Sleeping " + WAIT);
       Thread.sleep(WAIT * 1000);
       processedTime += WAIT * 1000;
       exception = e;
     }
   }
   // if not return, then print error.
   if (exception.getErrorCode() == 5) {
     // access denied error
     exception.printStackTrace(
         listener.error(Messages.ManagedWindowsServiceLauncher_AccessDenied()));
   } else {
     exception.printStackTrace(listener.error(exception.getMessage()));
   }
 }
예제 #5
0
  @Override
  public void perform(Run<?, ?> build, FilePath ws, Launcher launcher, TaskListener listener)
      throws InterruptedException {
    if (artifacts.length() == 0) {
      listener.error(Messages.ArtifactArchiver_NoIncludes());
      build.setResult(Result.FAILURE);
      return;
    }

    if (onlyIfSuccessful
        && build.getResult() != null
        && build.getResult().isWorseThan(Result.UNSTABLE)) {
      listener.getLogger().println(Messages.ArtifactArchiver_SkipBecauseOnlyIfSuccessful());
      return;
    }

    listener.getLogger().println(Messages.ArtifactArchiver_ARCHIVING_ARTIFACTS());
    try {
      String artifacts = build.getEnvironment(listener).expand(this.artifacts);

      Map<String, String> files =
          ws.act(new ListFiles(artifacts, excludes, defaultExcludes, caseSensitive));
      if (!files.isEmpty()) {
        build
            .pickArtifactManager()
            .archive(ws, launcher, BuildListenerAdapter.wrap(listener), files);
        if (fingerprint) {
          new Fingerprinter(artifacts).perform(build, ws, launcher, listener);
        }
      } else {
        Result result = build.getResult();
        if (result != null && result.isBetterOrEqualTo(Result.UNSTABLE)) {
          // If the build failed, don't complain that there was no matching artifact.
          // The build probably didn't even get to the point where it produces artifacts.
          listenerWarnOrError(listener, Messages.ArtifactArchiver_NoMatchFound(artifacts));
          String msg = null;
          try {
            msg =
                ws.validateAntFileMask(
                    artifacts, FilePath.VALIDATE_ANT_FILE_MASK_BOUND, caseSensitive);
          } catch (Exception e) {
            listenerWarnOrError(listener, e.getMessage());
          }
          if (msg != null) listenerWarnOrError(listener, msg);
        }
        if (!allowEmptyArchive) {
          build.setResult(Result.FAILURE);
        }
        return;
      }
    } catch (IOException e) {
      Util.displayIOException(e, listener);
      e.printStackTrace(listener.error(Messages.ArtifactArchiver_FailedToArchive(artifacts)));
      build.setResult(Result.FAILURE);
      return;
    }
  }
  /** {@inheritDoc} */
  @NonNull
  @Override
  protected void retrieve(@NonNull final SCMHeadObserver observer, @NonNull TaskListener listener)
      throws IOException {
    SVNRepositoryView repository = null;
    try {
      listener.getLogger().println("Opening conection to " + remoteBase);
      SVNURL repoURL = SVNURL.parseURIEncoded(remoteBase);
      repository = openSession(repoURL);

      String repoPath =
          SubversionSCM.DescriptorImpl.getRelativePath(repoURL, repository.getRepository());
      List<String> prefix = Collections.emptyList();
      fetch(
          listener,
          repository,
          -1,
          repoPath,
          toPaths(splitCludes(includes)),
          prefix,
          prefix,
          toPaths(splitCludes(excludes)),
          getCriteria(),
          observer);
    } catch (SVNException e) {
      e.printStackTrace(listener.error("Could not communicate with Subversion server"));
      throw new IOException(e);
    } finally {
      closeSession(repository);
    }
  }
예제 #7
0
 private void listenerWarnOrError(TaskListener listener, String message) {
   if (allowEmptyArchive) {
     listener.getLogger().println(String.format("WARN: %s", message));
   } else {
     listener.error(message);
   }
 }
예제 #8
0
 protected void perform(TaskListener listener) {
   for (Map.Entry<AbstractBuild, String> e : tagSet.entrySet()) {
     TagAction ta = e.getKey().getAction(TagAction.class);
     if (ta == null) {
       listener.error(e.getKey() + " doesn't have CVS tag associated with it. Skipping");
       continue;
     }
     listener.getLogger().println(Messages.CVSSCM_TagginXasY(e.getKey(), e.getValue()));
     try {
       e.getKey().keepLog();
     } catch (IOException x) {
       x.printStackTrace(listener.error(Messages.CVSSCM_FailedToMarkForKeep(e.getKey())));
     }
     ta.perform(e.getValue(), listener);
     listener.getLogger().println();
   }
 }
 private String getWspFilter(AbstractBuild<?, ?> build, TaskListener listener) {
   try {
     return TokenMacro.expandAll(build, listener, getWspFilter());
   } catch (Exception e) {
     listener.error("failed to expand tokens in: %s%n", getWspFilter());
   }
   return getWspFilter();
 }
예제 #10
0
  @Override
  public void perform(final TaskListener listener)
      throws IOException, InterruptedException, CommandException, AuthenticationException {
    for (CvsRepository repository : revisionState.getModuleFiles().keySet()) {
      for (CvsFile file : revisionState.getModuleState(repository)) {
        AbstractCvs owner = parent.getParent();
        final Client cvsClient =
            owner.getCvsClient(repository, build.getEnvironment(listener), listener);
        final GlobalOptions globalOptions =
            owner.getGlobalOptions(repository, build.getEnvironment(listener));

        globalOptions.setCVSRoot(repository.getCvsRoot());

        RtagCommand rtagCommand = new RtagCommand();

        rtagCommand.setTag(tagName);
        rtagCommand.setTagByRevision(file.getRevision());
        rtagCommand.addModule(file.getName());
        rtagCommand.setMakeBranchTag(createBranch);
        rtagCommand.setOverrideExistingTag(moveTag);
        cvsClient
            .getEventManager()
            .addCVSListener(new BasicListener(listener.getLogger(), listener.getLogger()));

        try {
          cvsClient.executeCommand(rtagCommand, globalOptions);
        } catch (CommandAbortedException e) {
          e.printStackTrace(listener.error("The CVS rtag command was aborted"));
          throw e;
        } catch (CommandException e) {
          e.printStackTrace(listener.error("Error while trying to run CVS rtag command"));
          throw e;
        } catch (AuthenticationException e) {
          e.printStackTrace(
              listener.error("Authentication error while trying to run CVS rtag command"));
          throw e;
        } finally {
          try {
            cvsClient.getConnection().close();
          } catch (IOException ex) {
            listener.error("Could not close client connection: " + ex.getMessage());
          }
        }
      }
    }
  }
 public String getPackageId(AbstractBuild<?, ?> build, TaskListener listener)
     throws IOException, InterruptedException {
   try {
     return TokenMacro.expandAll(build, listener, getPackageId());
   } catch (MacroEvaluationException e) {
     listener.error("Failed to expand macros in Package ID: %s", getPackageId());
     return getPackageId();
   }
 }
    private void install(Computer c, TaskListener listener) {
        try {
            final List<SlaveRestarter> restarters = new ArrayList<SlaveRestarter>(SlaveRestarter.all());

            VirtualChannel ch = c.getChannel();
            if (ch==null) return;  // defensive check

            List<SlaveRestarter> effective = ch.call(new Callable<List<SlaveRestarter>, IOException>() {
                public List<SlaveRestarter> call() throws IOException {
                    Engine e = Engine.current();
                    if (e == null) return null;    // not running under Engine

                    try {
                        Engine.class.getMethod("addListener", EngineListener.class);
                    } catch (NoSuchMethodException _) {
                        return null;    // running with older version of remoting that doesn't support adding listener
                    }

                    // filter out ones that doesn't apply
                    for (Iterator<SlaveRestarter> itr = restarters.iterator(); itr.hasNext(); ) {
                        SlaveRestarter r =  itr.next();
                        if (!r.canWork())
                            itr.remove();
                    }

                    e.addListener(new EngineListenerAdapter() {
                        @Override
                        public void onDisconnect() {
                            try {
                                for (SlaveRestarter r : restarters) {
                                    try {
                                        LOGGER.info("Restarting slave via "+r);
                                        r.restart();
                                    } catch (Exception x) {
                                        LOGGER.log(SEVERE, "Failed to restart slave with "+r, x);
                                    }
                                }
                            } finally {
                                // if we move on to the reconnection without restart,
                                // don't let the current implementations kick in when the slave loses connection again
                                restarters.clear();
                            }
                        }
                    });

                    return restarters;
                }
            });

            listener.getLogger().println("Effective SlaveRestarter on " + c.getDisplayName() + ": " + effective);
        } catch (Throwable e) {
            e.printStackTrace(listener.error("Failed to install restarter"));
        }
    }
예제 #13
0
 public String call() throws IOException {
   File home = new File(mvnHome);
   if (MavenProcessFactory.debug) listener.getLogger().println("Using mvnHome: " + mvnHome);
   File bootDir = new File(home, "boot");
   File[] classworlds = bootDir.listFiles(CLASSWORLDS_FILTER);
   if (classworlds == null || classworlds.length == 0) {
     listener.error(Messages.MavenProcessFactory_ClassWorldsNotFound(home));
     throw new RunnerAbortedException();
   }
   return classworlds[0].getAbsolutePath();
 }
 @Override
 public void afterDisconnect(SlaveComputer computer, TaskListener listener) {
   try {
     JIDefaultAuthInfoImpl auth = createAuth();
     JISession session = JISession.createSession(auth);
     session.setGlobalSocketTimeout(60000);
     SWbemServices services = WMI.connect(session, computer.getName());
     Win32Service slaveService = services.getService("jenkinsslave");
     if (slaveService != null) {
       listener.getLogger().println(Messages.ManagedWindowsServiceLauncher_StoppingService());
       slaveService.StopService();
     }
     // destroy session to free the socket
     JISession.destroySession(session);
   } catch (UnknownHostException e) {
     e.printStackTrace(listener.error(e.getMessage()));
   } catch (JIException e) {
     e.printStackTrace(listener.error(e.getMessage()));
   }
 }
예제 #15
0
  /**
   * **************************************************
   *
   * <p>private ByteArrayOutputStream popen(ArgumentListBuilder args)
   *
   * <p>Runs the command and captures the output.
   *
   * <p>**************************************************
   */
  private ByteArrayOutputStream popen(ArgumentListBuilder args, String jazzExecutable)
      throws IOException, InterruptedException {
    try {

      // scm produces text in the platform default encoding, so we need to convert it back to UTF-8
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      WriterOutputStream o =
          new WriterOutputStream(
              new OutputStreamWriter(baos, "UTF-8"), java.nio.charset.Charset.forName("UTF-8"));

      PrintStream output = listener.getLogger();

      ForkOutputStream fos = new ForkOutputStream(o, output);
      ProcStarter pstarter = run(args, jazzExecutable);

      if (joinWithPossibleTimeout(pstarter.stdout(fos), listener, null) == 0) {
        o.flush();
        return baos;
      } else {
        String errorString = "Failed to run ";
        boolean[] maskArray = args.toMaskArray();
        String[] cmdArray = args.toCommandArray();

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

        listener.error(errorString);
        throw new AbortException();
      }
    } catch (Exception e) {
      listener.error("Exception in popen " + e);
      throw new AbortException();
    }
  }
예제 #16
0
 /** Gets the revision ID of the tip of the workspace. */
 public @CheckForNull String tip(FilePath repository) throws IOException, InterruptedException {
   String id =
       popen(
           repository,
           listener,
           false,
           new ArgumentListBuilder("log", "--rev", ".", "--template", "{node}"));
   if (!REVISIONID_PATTERN.matcher(id).matches()) {
     listener.error("Expected to get an id but got '" + id + "' instead.");
     return null; // HUDSON-7723
   }
   return id;
 }
예제 #17
0
  /**
   * **************************************************
   *
   * <p>public boolean workspaceExists() throws IOException, InterruptedException {
   *
   * <p>Call <tt>scm history</tt> command.
   *
   * <p>
   *
   * <p>Will check if the workspace exists.
   *
   * @return <tt>true</tt> on exists
   * @throws IOException
   * @throws InterruptedException **************************************************
   */
  public boolean workspaceExists(AbstractBuild build) throws IOException, InterruptedException {
    // output to console.
    PrintStream output = listener.getLogger();
    Command cmd = new HistoryCommand(configuration);
    output.println(
        "  RTC SCM - Jazz Client: Run History command to determine if workspace exists - it is OK if an error is returned below: (Problem running 'history')");

    // Get variables from system.
    String jobName = "";

    try {
      jobName = build.getEnvironment(null).get("JOB_NAME");
    } catch (Exception e) {
      listener.error("" + e);
    }
    // Add the abstract build to the configuration.
    // This call happens before the load and accept so we can set these items for later use.
    configuration.setBuild(build);
    configuration.setTaskListener(listener);
    configuration.setJobName(jobName);
    configuration.consoleOut("    -- Initializing build object --");

    StringBuffer strBuf = new StringBuffer();
    joinWithPossibleTimeout(run(cmd.getArguments()), listener, strBuf, build, null);
    boolean result = true;
    String stdOut = strBuf.toString();

    if (stdOut.contains("did not match any workspaces") || stdOut.contains("Unmatched workspace")) {
      listener.error("The workspace probably doesn't exist.");

      output.println("  RTC SCM - Jazz Client: Specified workspace does not exist...");

      result = false;
    } else {
      output.println("  RTC SCM - Jazz Client: Specified workspace already exists...");
    }
    return result;
  }
  /**
   * Construct the post.
   *
   * @param reviewInput input
   * @param reviewEndpoint end point
   * @return the entity
   */
  private HttpPost createHttpPostEntity(ReviewInput reviewInput, String reviewEndpoint) {
    HttpPost httpPost = new HttpPost(reviewEndpoint);
    String asJson = GSON.toJson(reviewInput);

    StringEntity entity = null;
    try {
      entity = new StringEntity(asJson);
    } catch (UnsupportedEncodingException e) {
      listener.error("Failed to create JSON for posting", e);
      return null;
    }
    entity.setContentType("application/json");
    httpPost.setEntity(entity);
    return httpPost;
  }
예제 #19
0
  /**
   * **************************************************
   *
   * <p>private int joinWithPossibleTimeout(ProcStarter proc, final TaskListener listener,
   * StringBuffer strBuf, AbstractBuild currentBuild) throws IOException, InterruptedException
   *
   * <p>**************************************************
   */
  protected int joinWithPossibleTimeout(
      ProcStarter proc,
      final TaskListener listener,
      StringBuffer strBuf,
      AbstractBuild currentBuild,
      String stringToHide)
      throws IOException, InterruptedException {
    boolean useTimeout = configuration.isUseTimeout();
    long timeoutValue = configuration.getTimeoutValue();

    int result = -1;

    try {
      PipedInputStream pis = null;
      if (strBuf != null) {
        PipedOutputStream pos = new PipedOutputStream();
        pis = new PipedInputStream(pos, 1000000);
        proc = proc.stdout(pos);
      }

      hudson.Proc procStarted = proc.start();
      if (useTimeout) {
        result = procStarted.joinWithTimeout(timeoutValue, TimeUnit.SECONDS, listener);
      } else {
        result = procStarted.join();
      }

      if (strBuf != null) {
        byte[] stdoutDataArr = new byte[pis.available()];
        pis.read(stdoutDataArr, 0, stdoutDataArr.length);
        String stdoutStr = new String(stdoutDataArr);
        if (stringToHide != null) {
          stdoutStr = stdoutStr.replaceAll(stringToHide, "****");
        }
        strBuf.append(stdoutStr);
        PrintStream output = listener.getLogger();
        output.println(stdoutStr);
      }
    } catch (InterruptedException e) {
      throw e;
    } catch (Exception e) {
      if (listener != null) {
        listener.error("Exception caught in joinWithPossibleTimeout: " + e);
      }
    }

    return result;
  } // End: joinWithPossibleTimeout(...)
예제 #20
0
  /** Runs the command and captures the output. */
  public String popen(
      FilePath repository, TaskListener listener, boolean useTimeout, ArgumentListBuilder args)
      throws IOException, InterruptedException {
    args = seed().add(args.toCommandArray());

    ByteArrayOutputStream rev = new ByteArrayOutputStream();
    if (MercurialSCM.joinWithPossibleTimeout(
            l(args).pwd(repository).stdout(rev), useTimeout, listener)
        == 0) {
      return rev.toString();
    } else {
      listener.error("Failed to run " + args.toStringWithQuote());
      listener.getLogger().write(rev.toByteArray());
      throw new AbortException();
    }
  }
예제 #21
0
  /**
   * Start from scratch and clone the whole repository. Cloning into an existing directory is not
   * allowed, so the workspace is first deleted entirely, then <tt>git clone</tt> is performed.
   *
   * @param remoteConfig remote config
   * @throws GitException if deleting or cloning the workspace fails
   */
  public void clone(final RemoteConfig remoteConfig) throws GitException {
    listener.getLogger().println("Cloning repository " + remoteConfig.getName());
    final int[] gitVer = getGitVersion();

    // TODO: Not here!
    try {
      workspace.deleteRecursive();
    } catch (Exception e) {
      e.printStackTrace(listener.error("Failed to clean the workspace"));
      throw new GitException("Failed to delete workspace", e);
    }

    // Assume only 1 URL for this repository
    final String source = remoteConfig.getURIs().get(0).toPrivateString();

    try {
      workspace.act(
          new FileCallable<String>() {

            private static final long serialVersionUID = 1L;

            public String invoke(File workspace, VirtualChannel channel) throws IOException {
              final ArgumentListBuilder args = new ArgumentListBuilder();
              args.add("clone");
              if ((gitVer[0] >= 1) && (gitVer[1] >= 7)) {
                args.add("--progress");
              }
              if (reference != null) {
                File referencePath = new File(reference);
                if (referencePath.exists() && referencePath.isDirectory()) {
                  args.add("--reference", reference);
                }
              }
              args.add("-o", remoteConfig.getName());
              args.add(source);
              args.add(workspace.getAbsolutePath());
              return launchCommandIn(args, null);
            }
          });
    } catch (Exception e) {
      throw new GitException("Could not clone " + source, e);
    }
  }
 private void scheduleBuild(
     BranchProjectFactory<P, R> factory,
     final P item,
     SCMRevision revision,
     TaskListener listener,
     String name) {
   if (ParameterizedJobMixIn.scheduleBuild2(
           item, 0, new CauseAction(new SCMTrigger.SCMTriggerCause("Branch indexing")))
       != null) {
     listener.getLogger().println("Scheduled build for branch: " + name);
     try {
       factory.setRevisionHash(item, revision);
     } catch (IOException e) {
       e.printStackTrace(listener.error("Could not update last revision hash"));
     }
   } else {
     listener.getLogger().println("Failed to schedule build for branch: " + name);
   }
 }
  @Override
  public String evaluate(AbstractBuild<?, ?> context, TaskListener listener, String macroName)
      throws MacroEvaluationException, IOException, InterruptedException {
    if (!context.getWorkspace().child(path).exists()) {
      return StringUtils.isNotBlank(fileNotFoundMessage)
          ? String.format(fileNotFoundMessage, path)
          : "ERROR: File '" + path + "' does not exist";
    }

    // do some environment variable substitution
    try {
      EnvVars env = context.getEnvironment(listener);
      path = env.expand(path);
    } catch (Exception e) {
      listener.error("Error retrieving environment");
    }

    try {
      return context.getWorkspace().child(path).readToString();
    } catch (IOException e) {
      return "ERROR: File '" + path + "' could not be read";
    }
  }
예제 #24
0
  @NonNull
  @Override
  protected void retrieve(@NonNull final SCMHeadObserver observer, @NonNull TaskListener listener)
      throws IOException, InterruptedException {
    String cacheEntry = getCacheEntry();
    Lock cacheLock = getCacheLock(cacheEntry);
    cacheLock.lock();
    try {
      File cacheDir = getCacheDir(cacheEntry);
      Git git =
          Git.with(listener, new EnvVars(System.getenv()))
              .in(cacheDir)
              .using(GitTool.getDefaultInstallation().getGitExe());
      GitClient client = git.getClient();
      client.addDefaultCredentials(getCredentials());
      if (!client.hasGitRepo()) {
        listener.getLogger().println("Creating git repository in " + cacheDir);
        client.init();
      }
      String remoteName = getRemoteName();
      listener.getLogger().println("Setting " + remoteName + " to " + getRemote());
      client.setRemoteUrl(remoteName, getRemote());
      listener.getLogger().println("Fetching " + remoteName + "...");
      List<RefSpec> refSpecs = getRefSpecs();
      client.fetch(remoteName, refSpecs.toArray(new RefSpec[refSpecs.size()]));
      listener.getLogger().println("Pruning stale remotes...");
      final Repository repository = client.getRepository();
      try {
        client.prune(new RemoteConfig(repository.getConfig(), remoteName));
      } catch (UnsupportedOperationException e) {
        e.printStackTrace(listener.error("Could not prune stale remotes"));
      } catch (URISyntaxException e) {
        e.printStackTrace(listener.error("Could not prune stale remotes"));
      }
      listener.getLogger().println("Getting remote branches...");
      SCMSourceCriteria branchCriteria = getCriteria();
      RevWalk walk = new RevWalk(repository);
      try {
        walk.setRetainBody(false);
        for (Branch b : client.getRemoteBranches()) {
          if (!b.getName().startsWith(remoteName + "/")) {
            continue;
          }
          final String branchName = StringUtils.removeStart(b.getName(), remoteName + "/");
          listener.getLogger().println("Checking branch " + branchName);
          if (isExcluded(branchName)) {
            continue;
          }
          if (branchCriteria != null) {
            RevCommit commit = walk.parseCommit(b.getSHA1());
            final long lastModified = TimeUnit.SECONDS.toMillis(commit.getCommitTime());
            final RevTree tree = commit.getTree();
            SCMSourceCriteria.Probe probe =
                new SCMSourceCriteria.Probe() {
                  @Override
                  public String name() {
                    return branchName;
                  }

                  @Override
                  public long lastModified() {
                    return lastModified;
                  }

                  @Override
                  public boolean exists(@NonNull String path) throws IOException {
                    TreeWalk tw = TreeWalk.forPath(repository, path, tree);
                    try {
                      return tw != null;
                    } finally {
                      if (tw != null) {
                        tw.release();
                      }
                    }
                  }
                };
            if (branchCriteria.isHead(probe, listener)) {
              listener.getLogger().println("Met criteria");
            } else {
              listener.getLogger().println("Does not meet criteria");
              continue;
            }
          }
          SCMHead head = new SCMHead(branchName);
          SCMRevision hash = new SCMRevisionImpl(head, b.getSHA1String());
          observer.observe(head, hash);
          if (!observer.isObserving()) {
            return;
          }
        }
      } finally {
        walk.dispose();
      }

      listener.getLogger().println("Done.");
    } finally {
      cacheLock.unlock();
    }
  }
  private void wmiLaunch(final EC2Computer computer, final TaskListener listener)
      throws IOException, InterruptedException, JIException {
    try {
      final PrintStream logger = listener.getLogger();
      final String name = host;

      logger.println(Messages.ManagedWindowsServiceLauncher_ConnectingTo(name));

      InetAddress host = InetAddress.getByName(name);

      try {
        Socket s = new Socket();
        s.connect(new InetSocketAddress(host, 135), 5000);
        s.close();
      } catch (IOException e) {
        logger.println(
            "Failed to connect to port 135 of "
                + name
                + ". Is Windows firewall blocking this port? Or did you disable DCOM service?");
        // again, let it continue.
      }

      JIDefaultAuthInfoImpl auth = createAuth();
      JISession session = JISession.createSession(auth);
      session.setGlobalSocketTimeout(60000);
      SWbemServices services = WMI.connect(session, name);

      String path = computer.getNode().getRemoteFS();
      if (path.indexOf(':') == -1)
        throw new IOException(
            "Remote file system root path of the slave needs to be absolute: " + path);
      SmbFile remoteRoot =
          new SmbFile(
              "smb://" + name + "/" + path.replace('\\', '/').replace(':', '$') + "/",
              createSmbAuth());

      if (!remoteRoot.exists()) remoteRoot.mkdirs();

      try { // does Java exist?
        logger.println("Checking if Java exists");
        WindowsRemoteProcessLauncher wrpl = new WindowsRemoteProcessLauncher(name, auth);
        Process proc = wrpl.launch("%JAVA_HOME%\\bin\\java -fullversion", "c:\\");
        proc.getOutputStream().close();
        IOUtils.copy(proc.getInputStream(), logger);
        proc.getInputStream().close();
        int exitCode = proc.waitFor();
        if (exitCode == 1) { // we'll get this error code if Java is not found
          logger.println("No Java found. Downloading JDK");
          JDKInstaller jdki = new JDKInstaller("jdk-6u16-oth-JPR@CDS-CDS_Developer", true);
          URL jdk = jdki.locate(listener, Platform.WINDOWS, CPU.i386);

          listener.getLogger().println("Installing JDK");
          copyStreamAndClose(
              jdk.openStream(), new SmbFile(remoteRoot, "jdk.exe").getOutputStream());

          String javaDir = path + "\\jdk"; // this is where we install Java to

          WindowsRemoteFileSystem fs = new WindowsRemoteFileSystem(name, createSmbAuth());
          fs.mkdirs(javaDir);

          jdki.install(
              new WindowsRemoteLauncher(listener, wrpl),
              Platform.WINDOWS,
              fs,
              listener,
              javaDir,
              path + "\\jdk.exe");
        }
      } catch (Exception e) {
        e.printStackTrace(listener.error("Failed to prepare Java"));
      }

      String id = generateServiceId(path);
      Win32Service slaveService = services.getService(id);
      if (slaveService == null) {
        logger.println(Messages.ManagedWindowsServiceLauncher_InstallingSlaveService());
        if (!DotNet.isInstalled(2, 0, name, auth)) {
          // abort the launch
          logger.println(Messages.ManagedWindowsServiceLauncher_DotNetRequired());
          return;
        }

        // copy exe
        logger.println(Messages.ManagedWindowsServiceLauncher_CopyingSlaveExe());
        copyStreamAndClose(
            getClass().getResource("/windows-service/jenkins.exe").openStream(),
            new SmbFile(remoteRoot, "jenkins-slave.exe").getOutputStream());

        copySlaveJar(logger, remoteRoot);

        // copy jenkins-slave.xml
        logger.println(Messages.ManagedWindowsServiceLauncher_CopyingSlaveXml());
        String nodeNameEncoded = java.net.URLEncoder.encode(nodeName, "UTF-8").replace("+", "%20");
        String xml =
            generateSlaveXml(
                id,
                "\"%JAVA_HOME%\\bin\\java\"",
                " -jnlpUrl "
                    + Hudson.getInstance().getRootUrl()
                    + "computer/"
                    + nodeNameEncoded
                    + "/slave-agent.jnlp");
        copyStreamAndClose(
            new ByteArrayInputStream(xml.getBytes("UTF-8")),
            new SmbFile(remoteRoot, "jenkins-slave.xml").getOutputStream());

        // install it as a service
        logger.println(Messages.ManagedWindowsServiceLauncher_RegisteringService());
        Document dom = new SAXReader().read(new StringReader(xml));
        Win32Service svc = services.Get("Win32_Service").cast(Win32Service.class);
        int r =
            svc.Create(
                id,
                dom.selectSingleNode("/service/name").getText() + " at " + path,
                path + "\\jenkins-slave.exe",
                Win32OwnProcess,
                0,
                "Manual",
                true);
        if (r != 0) {
          throw new JIException(-1, ("Failed to create a service: " + svc.getErrorMessage(r)));
        }
        slaveService = services.getService(id);
      } else {
        copySlaveJar(logger, remoteRoot);
      }

      logger.println(Messages.ManagedWindowsServiceLauncher_StartingService());
      slaveService.start();

      // wait until we see the port.txt, but don't do so forever
      logger.println(Messages.ManagedWindowsServiceLauncher_WaitingForService());
      SmbFile portFile = new SmbFile(remoteRoot, "port.txt");
      for (int i = 0; !portFile.exists(); i++) {
        if (i >= 30) {
          throw new JIException(-1, Messages.ManagedWindowsServiceLauncher_ServiceDidntRespond());
        }
        Thread.sleep(1000);
      }
      int p = readSmbFile(portFile);

      // connect
      logger.println(Messages.ManagedWindowsServiceLauncher_ConnectingToPort(p));
      final Socket s = new Socket(name, p);

      // ready
      computer.setChannel(
          new BufferedInputStream(new SocketInputStream(s)),
          new BufferedOutputStream(new SocketOutputStream(s)),
          listener.getLogger(),
          new Listener() {
            @Override
            public void onClosed(Channel channel, IOException cause) {
              afterDisconnect(computer, listener);
            }
          });
      // destroy session to free the socket
      JISession.destroySession(session);
    } catch (SmbException e) {
      e.printStackTrace(listener.error(e.getMessage()));
    } catch (DocumentException e) {
      e.printStackTrace(listener.error(e.getMessage()));
    }
  }