Invokes jenkins.exe with a SCM management command.

<p>
If it fails in a way that indicates the presence of UAC, retry in an UAC compatible manner.
543726
static int runElevated(File jenkinsExe, String command, TaskListener out, File pwd) throws IOException, InterruptedException {
        try {
            return new LocalLauncher(out).launch().cmds(jenkinsExe, command).stdout(out).pwd(pwd).join();
        } catch (IOException e) {
            if (e.getMessage().contains("CreateProcess") && e.getMessage().contains("=740")) {
                // fall through
            } else {
                throw e;
            }
        }

        // error code 740 is ERROR_ELEVATION_REQUIRED, indicating that
        // we run in UAC-enabled Windows and we need to run this in an elevated privilege
        SHELLEXECUTEINFO sei = new SHELLEXECUTEINFO();
        sei.fMask = SEE_MASK_NOCLOSEPROCESS;
        sei.lpVerb = "runas";
        sei.lpFile = jenkinsExe.getAbsolutePath();
        sei.lpParameters = "/redirect redirect.log "+command;
        sei.lpDirectory = pwd.getAbsolutePath();
        sei.nShow = SW_HIDE;
        if (!Shell32.INSTANCE.ShellExecuteEx(sei))
            throw new IOException("Failed to shellExecute: "+ Native.getLastError());

        try {
            return Kernel32Utils.waitForExitProcess(sei.hProcess);
        } finally {
            try (InputStream fin = Files.newInputStream(new File(pwd,"redirect.log").toPath())) {
                IOUtils.copy(fin, out.getLogger());
            } catch (InvalidPathException e) {
                // ignore;
            }
        }
    }
1196782
@Override
    public final Object preInvoke(EJSDeployedSupport s,
                                  ContainerTx tx) // d139352-2
                    throws RemoteException {
        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isEntryEnabled())
            Tr.entry(tc, "preInvoke");

        setState(POOLED, IN_METHOD);

        if (isTraceOn && tc.isEntryEnabled())
            Tr.exit(tc, "preInvoke");
        return ivEjbInstance;
    }
968576
private void executeSlave(final ForkedJvmInfo slave, final EventBus aggregatedBus)
    throws Exception
  {
    final String uniqueSeed = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS", Locale.ROOT).format(new Date());

    final Path classNamesFile = tempFile(uniqueSeed, "junit4-J" + slave.id, ".suites", getTempDir());
    temporaryFiles.add(classNamesFile);

    final Path classNamesDynamic = tempFile(uniqueSeed, "junit4-J" + slave.id, ".dynamic-suites", getTempDir());
    final Path streamsBufferFile = tempFile(uniqueSeed, "junit4-J" + slave.id, ".spill", getTempDir());

    // Dump all test class names to a temporary file.
    String testClassPerLine = Joiner.on("\n").join(slave.testSuites);
    log("Test class names:\n" + testClassPerLine, Project.MSG_VERBOSE);
    Files.write(classNamesFile, testClassPerLine.getBytes(StandardCharsets.UTF_8));

    // Prepare command line for java execution.
    CommandlineJava commandline;
    commandline = (CommandlineJava) getCommandline().clone();
    commandline.createClasspath(getProject()).add(addSlaveClasspath());
    commandline.setClassname(SlaveMainSafe.class.getName());
    if (slave.slaves == 1) {
      commandline.createArgument().setValue(SlaveMain.OPTION_FREQUENT_FLUSH);
    }

    // Set up full output files.
    Path sysoutFile = tempFile(uniqueSeed,
        "junit4-J" + slave.id, ".sysout", getTempDir());
    Path syserrFile = tempFile(uniqueSeed,
        "junit4-J" + slave.id, ".syserr", getTempDir());

    // Set up communication channel.
    Path eventFile = tempFile(uniqueSeed, "junit4-J" + slave.id, ".events", getTempDir());
    temporaryFiles.add(eventFile);
    commandline.createArgument().setValue(SlaveMain.OPTION_EVENTSFILE);
    commandline.createArgument().setFile(eventFile.toFile());
    
    if (sysouts) {
      commandline.createArgument().setValue(SlaveMain.OPTION_SYSOUTS);
    }
    
    if (debugStream) {
      commandline.createArgument().setValue(SlaveMain.OPTION_DEBUGSTREAM);
    }

    TailInputStream eventStream = new TailInputStream(eventFile);

    // Process user-defined RunListener classes.
    if (!runListeners.isEmpty()) {
      String classNames = runListeners.stream().map(x -> x.getClassName()).collect(Collectors.joining(","));

      commandline.createArgument().setValue(SlaveMain.OPTION_RUN_LISTENERS);
      commandline.createArgument().setValue(classNames);
    }

    // Set up input suites file.
    commandline.createArgument().setValue("@" + classNamesFile.toAbsolutePath().normalize());

    // May or may not use dynamic load balancing, but if == 0 then we're for sure
    // not using it.
    if (dynamicAssignmentRatio > 0) {
      commandline.createArgument().setValue(SlaveMain.OPTION_STDIN);
    }

    final EventBus eventBus = new EventBus("slave-" + slave.id);
    final DiagnosticsListener diagnosticsListener = new DiagnosticsListener(slave, this);
    eventBus.register(diagnosticsListener);
    eventBus.register(new AggregatingListener(aggregatedBus, slave));

    final AtomicReference<Charset> clientCharset = new AtomicReference<Charset>();
    final AtomicBoolean clientWithLimitedCharset = new AtomicBoolean(); 
    final PrintWriter w = new PrintWriter(Files.newBufferedWriter(classNamesDynamic, StandardCharsets.UTF_8));
    eventBus.register(new Object() {
      @Subscribe
      public void onIdleSlave(final SlaveIdle idleSlave) {
        aggregatedBus.post(new SlaveIdle() {
          @Override
          public void finished() {
            idleSlave.finished();
          }

          @Override
          public void newSuite(String suiteName) {
            if (!clientCharset.get().newEncoder().canEncode(suiteName)) {
              clientWithLimitedCharset.set(true);
              log("Forked JVM J" + slave.id + " skipped suite (cannot encode suite name in charset " +
                  clientCharset.get() + "): " + suiteName, Project.MSG_WARN);
              return;
            }

            log("Forked JVM J" + slave.id + " stole suite: " + suiteName, Project.MSG_VERBOSE);
            w.println(suiteName);
            w.flush();
            idleSlave.newSuite(suiteName);
          }
        });
      }

      @Subscribe
      public void onBootstrap(final BootstrapEvent e) {
        Charset cs = Charset.forName(((BootstrapEvent) e).getDefaultCharsetName());
        clientCharset.set(cs);

        slave.start = System.currentTimeMillis();
        slave.setBootstrapEvent(e);
        aggregatedBus.post(new ChildBootstrap(slave));
      }

      @Subscribe
      public void receiveQuit(QuitEvent e) {
        slave.end = System.currentTimeMillis();
      }      
    });

    Closer closer = Closer.create();
    closer.register(eventStream);
    closer.register(w);
    try {
      OutputStream sysout = closer.register(new BufferedOutputStream(Files.newOutputStream(sysoutFile)));
      OutputStream syserr = closer.register(new BufferedOutputStream(Files.newOutputStream(syserrFile)));
      RandomAccessFile streamsBuffer = closer.register(new RandomAccessFile(streamsBufferFile.toFile(), "rw"));

      Execute execute = forkProcess(slave, eventBus, commandline, eventStream, sysout, syserr, streamsBuffer);
      log("Forked JVM J" + slave.id + " finished with exit code: " + execute.getExitValue(), Project.MSG_DEBUG);

      if (execute.isFailure()) {
        final int exitStatus = execute.getExitValue();
        switch (exitStatus) {
          case SlaveMain.ERR_NO_JUNIT:
            throw new BuildException("Forked JVM's classpath must include a junit4 JAR.");
          case SlaveMain.ERR_OLD_JUNIT:
            throw new BuildException("Forked JVM's classpath must use JUnit 4.10 or newer.");
          default:
            Closeables.close(sysout, false);
            Closeables.close(syserr, false);

            StringBuilder message = new StringBuilder();
            if (exitStatus == SlaveMain.ERR_OOM) {
              message.append("Forked JVM ran out of memory.");
            } else {
              message.append("Forked process returned with error code: ").append(exitStatus).append(".");
            }

            if (Files.size(sysoutFile) > 0 || Files.size(syserrFile) > 0) {
              if (exitStatus != SlaveMain.ERR_OOM) {
                message.append(" Very likely a JVM crash. ");
              }

              if (jvmOutputAction.contains(JvmOutputAction.PIPE)) {
                message.append(" Process output piped in logs above.");
              } else if (!jvmOutputAction.contains(JvmOutputAction.IGNORE)) {
                if (Files.size(sysoutFile) > 0) {
                  message.append(" See process stdout at: " + sysoutFile.toAbsolutePath());
                }
                if (Files.size(syserrFile) > 0) {
                  message.append(" See process stderr at: " + syserrFile.toAbsolutePath());
                }
              }
            }
            throw new BuildException(message.toString());
        }
      }
    } catch (Throwable t) {
      throw closer.rethrow(t);
    } finally {
      try {
        closer.close();
      } finally {
        com.google.common.io.Files.asByteSource(classNamesDynamic.toFile())
          .copyTo(com.google.common.io.Files.asByteSink(classNamesFile.toFile(), FileWriteMode.APPEND));
        Files.delete(classNamesDynamic);
        Files.delete(streamsBufferFile);

        // Check sysout/syserr lengths.
        checkJvmOutput(aggregatedBus, sysoutFile, slave, "stdout");
        checkJvmOutput(aggregatedBus, syserrFile, slave, "stderr");        
      }
    }

    if (!diagnosticsListener.quitReceived()) {
      throw new BuildException("Quit event not received from the forked process? This may indicate JVM crash or runner bugs.");
    }

    if (clientWithLimitedCharset.get() && dynamicAssignmentRatio > 0) {
      throw new BuildException("Forked JVM J" + slave.id + " was not be able to decode class names when using" +
          " charset: " + clientCharset + ". Do not use " +
          "dynamic suite balancing to work around this problem (-DdynamicAssignmentRatio=0).");
    }
  }
1356321
def remote_run(cmd, instance_name, detach=False, retries=1):
  """"""
  if detach:
    cmd = SCREEN.format(command=cmd)
  args = SSH.format(instance_name=instance_name).split()
  args.append(cmd)
  for i in range(retries + 1):
    try:
      if i > 0:
        tf.logging.info("Retry %d for %s", i, args)
      return sp.check_call(args)
    except sp.CalledProcessError as e:
      if i == retries:
        raise e
37584
public void throw_dev_failed(Exception e, String command, boolean from_inout_cmd) throws DevFailed {
		iConnection.throw_dev_failed(this, e, command, from_inout_cmd);
	}
358797
public int command_inout_asynch(final DeviceProxy deviceProxy, final String cmdname,
            final DeviceData data_in) throws DevFailed {
        return command_inout_asynch(deviceProxy, cmdname, data_in, false);
    }
829958
def runRemoteCommand(self, cmd, args, abandonOnFailure=True,
                         evaluateCommand=lambda cmd: cmd.didFail()):
        """"""
        cmd = remotecommand.RemoteCommand(cmd, args)
        if hasattr(self, "rc_log"):
            cmd.useLog(self.rc_log, False)
        d = self.runCommand(cmd)

        def commandComplete(cmd):
            if abandonOnFailure and cmd.didFail():
                raise buildstep.BuildStepFailed()
            return evaluateCommand(cmd)

        d.addCallback(lambda res: commandComplete(cmd))
        return d
711085
def execute_and_report(command, *args, **kwargs):
    
    logging.info("Execute: %s %s" % (command, " ".join(args)))
    try:
        status, out, err = execute(command, *args, **kwargs)
        if status == 0:
            logging.info(
                "%s Finished successfully. Exit Code: 0.",
                os.path.basename(command),
            )
            return True
        else:
            try:
                logging.error(
                    "%s failed! Exit Code: %s\nOut: %s\nError: %s",
                    os.path.basename(command),
                    status,
                    out,
                    err,
                )
            except Exception as e:
                # This fails when some non ASCII characters are returned
                # from the application
                logging.error(
                    "%s failed [%s]! Exit Code: %s\nOut: %s\nError: %s",
                    e,
                    os.path.basename(command),
                    status,
                    repr(out),
                    repr(err),
                )
            return False
    except Exception:
        logging.exception(
            "%s failed! Exception thrown!", os.path.basename(command)
        )
        return False
66786
private void cscCommand() throws MojoExecutionException {
        generateAssemblyInfo();
        String cscPath = findCscCommand();
        List<String> commandList = new LinkedList<String>(cspath);
        commandList.add(0, cscPath);
        commandList.add(1, "/target:library");
        commandList.add(2, "/out:" + namespace + ".dll");
        if (isLinux()) {
            commandList.add(3, "/reference:System.Web.Services");
        }
        String[] command = commandList.toArray(new String[commandList.size()]);
        ProcessBuilder builder = new ProcessBuilder();
        builder.redirectErrorStream(true);
        builder.directory(outputDirectory);
        builder.command(command);
        try {
            executeACommand(builder.start());
        } catch (InterruptedException | IOException e) {
            throw new MojoExecutionException("Error, while executing command: "
                    + Arrays.toString(command) + "\n", e);
        }
    }
1165005
@Override
    public void verifyMIC ( byte[] data, byte[] mic ) throws CIFSException {
        try {
            this.gssContext.verifyMIC(mic, 0, mic.length, data, 0, data.length, new MessageProp(false));
        }
        catch ( GSSException e ) {
            throw new CIFSException("Failed to verify MIC", e);
        }
    }
674121
public void command_inout_asynch(String cmdname, CallBack cb) throws DevFailed {
        deviceProxyDAO.command_inout_asynch(this, cmdname, cb);
    }
1061865
public void invokeUnchecked(CodeBuilder cb) {
    cb.visitMethodInsn(
        opcode(),
        owner().internalName(),
        method().getName(),
        method().getDescriptor(),
        // This is for whether the methods owner is an interface.  This is mostly to handle java8
        // default methods on interfaces.  We don't care about those currently, but ASM requires
        // this.
        opcode() == Opcodes.INVOKEINTERFACE);
  }
765551
protected void fireCommandRegistered(AbstractCommand command) {
        
        Assert.notNull(command, "command");
        
        if (commandRegistryListeners.isEmpty()) {
            return;
        }
        
        CommandRegistryEvent event = new CommandRegistryEvent(this, command);
        
        for (Iterator i = commandRegistryListeners.iterator(); i.hasNext();) {
            ((CommandRegistryListener)i.next()).commandRegistered(event);
        }
        
    }
854035
@Nonnull
  public static ESuccess check (@Nonnull @Nonempty final String sServerSideKey,
                                @Nullable final String sReCaptchaResponse)
  {
    ValueEnforcer.notEmpty (sServerSideKey, "ServerSideKey");

    if (StringHelper.hasNoText (sReCaptchaResponse))
      return ESuccess.SUCCESS;

    final HttpClientFactory aHCFactory = new HttpClientFactory ();
    // For proxy etc
    aHCFactory.setUseSystemProperties (true);

    try (HttpClientManager aMgr = new HttpClientManager (aHCFactory))
    {
      final HttpPost aPost = new HttpPost (new SimpleURL ("https://www.google.com/recaptcha/api/siteverify").add ("secret",
                                                                                                                  sServerSideKey)
                                                                                                            .add ("response",
                                                                                                                  sReCaptchaResponse)
                                                                                                            .getAsURI ());
      final ResponseHandlerJson aRH = new ResponseHandlerJson ();
      final IJson aJson = aMgr.execute (aPost, aRH);
      if (aJson != null && aJson.isObject ())
      {
        final boolean bSuccess = aJson.getAsObject ().getAsBoolean ("success", false);

        if (GlobalDebug.isDebugMode ())
          LOGGER.info ("ReCpatcha Response for '" + sReCaptchaResponse + "': " + aJson.getAsJsonString ());

        return ESuccess.valueOf (bSuccess);
      }
    }
    catch (final IOException ex)
    {
      LOGGER.warn ("Error checking ReCaptcha response", ex);
    }
    return ESuccess.FAILURE;
  }
368087
public int command_inout_asynch(final DeviceProxy deviceProxy, final String cmdname,
            final boolean forget) throws DevFailed {
        return command_inout_asynch(deviceProxy, cmdname, new DeviceData(), forget);
    }
183137
private void processCommand(List<String> command) throws Exception {
        processBuilder.command(command);
        Process p = processBuilder.start();
        checkReturnCode(p, processBuilder.command().toString(), ReturnCode.OK.getValue(), ReturnCode.ALREADY_EXISTS.getValue());
        if (!acceptLicense) {
            throw new BuildException("To install a feature, you must accept the feature's license terms and conditions.");
        }
    }
261105
protected final @Nonnull Result<T> monitorDetailed() throws InterruptedException {
        Map<Computer,Future<T>> futures = new HashMap<>();
        Set<Computer> skipped = new HashSet<>();

        for (Computer c : Jenkins.getInstance().getComputers()) {
            try {
                VirtualChannel ch = c.getChannel();
                futures.put(c,null);    // sentinel value
                if (ch!=null) {
                    Callable<T, ?> cc = createCallable(c);
                    if (cc!=null)
                        futures.put(c,ch.callAsync(cc));
                }
            } catch (RuntimeException | IOException e) {
                LOGGER.log(WARNING, "Failed to monitor "+c.getDisplayName()+" for "+getDisplayName(), e);
            }
        }

        final long now = System.currentTimeMillis();
        final long end = now + getMonitoringTimeOut();

        final Map<Computer,T> data = new HashMap<>();

        for (Entry<Computer, Future<T>> e : futures.entrySet()) {
            Computer c = e.getKey();
            Future<T> f = futures.get(c);
            data.put(c, null);  // sentinel value

            if (f!=null) {
                try {
                    data.put(c,f.get(Math.max(0,end-System.currentTimeMillis()), MILLISECONDS));
                } catch (RuntimeException | TimeoutException | ExecutionException x) {
                    LOGGER.log(WARNING, "Failed to monitor " + c.getDisplayName() + " for " + getDisplayName(), x);
                }
            } else {
                skipped.add(c);
            }
        }

        return new Result<>(data, skipped);
    }