// Executes the given command on the client machine (localhost). If no command is given,
// executes shell
198806
func runLocalCommand(command []string) error {
	if len(command) == 0 {
		user, err := user.Current()
		if err != nil {
			return trace.Wrap(err)
		}
		shell, err := shell.GetLoginShell(user.Username)
		if err != nil {
			return trace.Wrap(err)
		}
		command = []string{shell}
	}
	cmd := exec.Command(command[0], command[1:]...)
	cmd.Stderr = os.Stderr
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	return cmd.Run()
}
1279897
func (s *sandbox) handleLocalhost() error {
	span, _ := s.trace("handleLocalhost")
	defer span.Finish()

	// If not running as the init daemon, there is nothing to do as the
	// localhost interface will already exist.
	if os.Getpid() != 1 {
		return nil
	}

	lo, err := netlink.LinkByName("lo")
	if err != nil {
		return err
	}

	return netlink.LinkSetUp(lo)
}
279386
func (c *Cluster) execute(async *Async) {
	if c == nil {
		panic("[Cluster] nil cluster argument")
	}
	if async == nil {
		panic("[Cluster] nil async argument")
	}
	var err error
	executed := false
	enqueued := false
	cmd := async.Command

	tries := byte(1)
	var lastExeNode *Node
	if rc, ok := cmd.(retryableCommand); ok {
		tries = c.executionAttempts
		lastExeNode = rc.getLastNode()
	}

	async.onExecute()
	for tries > 0 {
		if err = c.stateCheck(clusterRunning); err != nil {
			break
		}
		executed, err = c.nodeManager.ExecuteOnNode(c.nodes, cmd, lastExeNode)
		// NB: do *not* call cmd.onError here as it will have been called in connection
		if executed {
			// NB: "executed" means that a node sent the data to Riak and received a response
			if err == nil {
				// No need to re-try
				logDebug("[Cluster]", "successfully executed cmd '%s'", cmd.Name())
				break
			} else {
				// NB: retry since error occurred
				logDebug("[Cluster]", "executed cmd '%s': re-try due to error '%v'", cmd.Name(), err)
			}
		} else {
			// Command did NOT execute
			if err == nil {
				logDebug("[Cluster]", "did NOT execute cmd '%s', nil err", cmd.Name())
				// Command did not execute but there was no error, so enqueue it
				// TODO FUTURE should this only happen if retries exhausted?
				if c.queueCommands {
					if err = c.enqueueCommand(async); err == nil {
						enqueued = true
					}
					break
				}
			} else {
				// NB: retry since error occurred
				logDebug("[Cluster]", "did NOT execute cmd '%s': re-try due to error '%v'", cmd.Name(), err)
			}
		}

		tries--
		logDebug("[Cluster]", "cmd %s tries: %d", cmd.Name(), tries)

		if tries > 0 {
			cmd.onRetry()
			async.onRetry()
		} else {
			err = newClientError(ErrClusterNoNodesAvailable, err)
		}
	}
	if !enqueued {
		async.done(err)
	}
}
320079
func Execute() {
	if err := rootCmd.Execute(); err != nil {
		log.WithError(err).Error("Monitor failed")
		os.Exit(-1)
	}
}
1115408
func Run(command string, args ...string) error {
	cmd := exec.Command(command, args...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	return RunCommand(cmd, false)
}
1350436
func Execute() {
	if err := RootCmd.Execute(); err != nil {
		exitCode := 1
		if stat, ok := status.FromError(err); ok {
			exitCode = int(stat.Code())
			fmt.Fprintln(os.Stderr, stat.Message())
		} else {
			fmt.Fprintf(os.Stderr, "%v\n", err)
		}
		fmt.Fprintf(os.Stderr, "\nPlease use -h,--help for more information\n")
		os.Exit(exitCode)
	}
}
1165144
func Execute() {
	if err := RootCmd.Execute(); err != nil {
		// Cobra already outputs the error, typically because the user provided an unknown command.
		os.Exit(exit.BadUsage)
	}
}
637392
func (sshCommandRunner) LocalCommand(cmd string) (int, error) {
	cmdSlice := strings.Split(cmd, " ")
	osCmd := exec.Command(cmdSlice[0], cmdSlice[1:]...)
	osCmd.Stderr = os.Stderr
	osCmd.Stdout = os.Stdout
	osCmd.Start()
	err := osCmd.Wait()
	if err != nil {
		// Get the command's exit status if we can
		if exiterr, ok := err.(*exec.ExitError); ok {
			if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
				return status.ExitStatus(), nil
			}
		}
		// Otherwise, generic command error
		return -1, err
	}
	return 0, nil
}
604240
func Execute(ctx context.Context, executeWaitGroup *sync.WaitGroup, stat *pb.InstructionStat,
	name string, command *exec.Cmd,
	reader io.Reader, writer io.Writer, prevIsPipe, isPipe bool, closeOutput bool,
	errWriter io.Writer) error {

	defer func() {
		executeWaitGroup.Done()
		if closeOutput {
			if c, ok := writer.(io.Closer); ok {
				c.Close()
			}
		}
	}()

	var wg sync.WaitGroup

	if reader != nil {
		if prevIsPipe && isPipe {
			// println("step", name, "input is lines->lines")
			command.Stdin = reader
		} else if !prevIsPipe && !isPipe {
			// println("step", name, "input is msgpack->msgpack")
			command.Stdin = reader
		} else {
			inputWriter, stdinErr := command.StdinPipe()
			if stdinErr != nil {
				fmt.Fprintf(errWriter, "Failed to open StdinPipe: %v", stdinErr)
			} else {
				wg.Add(1)
				if !prevIsPipe && isPipe {
					// println("step", name, "input is msgpack->lines")
					go ChannelToLineWriter(&wg, stat, name, reader, inputWriter, errWriter)
				} else {
					// println("step", name, "input is lines->msgpack")
					go LineReaderToChannel(&wg, stat, name, reader, inputWriter, true, errWriter)
				}
			}
		}
	}

	command.Stdout = writer

	command.Stderr = errWriter

	// println(name, "starting...", strings.Join(command.Args, ","))

	if startError := command.Start(); startError != nil {
		return fmt.Errorf("Start error %v: %v\n", startError, command)
	}

	// fmt.Printf("%s Command is waiting..\n", name)
	errChan := make(chan error)
	go func() {
		wg.Wait()
		waitError := command.Wait()
		if waitError != nil {
			waitError = fmt.Errorf("%s Wait error %+v.\n", name, waitError)
		}
		errChan <- waitError
	}()

	// defer fmt.Printf("%s Command is finished.\n", name)

	select {
	case <-ctx.Done():
		println("cancel process", command.Process.Pid, name, "...")
		command.Process.Kill()
		command.Process.Release()
		return ctx.Err()
	case err := <-errChan:
		return err
	}

}
760476
func (t *TermHandlers) HandleShell(ch ssh.Channel, req *ssh.Request, ctx *ServerContext) error {
	var err error

	// creating an empty exec request implies a interactive shell was requested
	ctx.ExecRequest, err = NewExecRequest(ctx, "")
	if err != nil {
		return trace.Wrap(err)
	}

	if err := t.SessionRegistry.OpenSession(ch, req, ctx); err != nil {
		return trace.Wrap(err)
	}

	return nil
}
901167
func (r *RemoteRuntimeService) Exec(req *runtimeapi.ExecRequest) (*runtimeapi.ExecResponse, error) {
	ctx, cancel := getContextWithTimeout(r.timeout)
	defer cancel()

	resp, err := r.runtimeClient.Exec(ctx, req)
	if err != nil {
		klog.Errorf("Exec %s '%s' from runtime service failed: %v", req.ContainerId, strings.Join(req.Cmd, " "), err)
		return nil, err
	}

	if resp.Url == "" {
		errorMessage := "URL is not set"
		klog.Errorf("Exec failed: %s", errorMessage)
		return nil, errors.New(errorMessage)
	}

	return resp, nil
}
334358
func Command(scriptName string, args ...string) (*exec.Cmd, error) {
	// Make sure this is a script name, not a path.
	if strings.Contains(scriptName, "/") {
		return nil, fmt.Errorf("not a script name: %v", scriptName)
	}

	// Get the list of available scripts.
	root, err := gitutil.RepositoryRootAbsolutePath()
	if err != nil {
		return nil, err
	}

	scriptsDirPath := filepath.Join(root, config.LocalConfigDirname, ScriptDirname)

	scriptsDir, err := os.Open(scriptsDirPath)
	if err != nil {
		return nil, err
	}
	defer scriptsDir.Close()

	scripts, err := scriptsDir.Readdirnames(-1)
	if err != nil {
		return nil, err
	}

	// Choose the first available script for the given script name.
	// Return a command for that script based on the file extension and platform.
	currentPlatformId := runners.ParsePlatform(runtime.GOOS)

	for _, script := range scripts {
		// To understand the loop:
		//   script     = ${base}.${ext}
		//   base       = ${name}_${platform}
		//   (=> script = ${name}_${platform}.${ext})

		// Get the file extension.
		ext := filepath.Ext(script)
		if ext == "" {
			continue
		}

		// Get the file base, i.e. the filename without the file extension.
		base := script[:len(script)-len(ext)]

		// In case the whole base matches, this is a cross-platform script and we are done.
		// Otherwise we have to parse the base further and decide what to do.
		var platformId runners.Platform
		if base == scriptName {
			platformId = currentPlatformId
		} else {
			// Split the base.
			parts := strings.Split(base, "_")

			// Make sure the platform matches the current platform.
			platform := parts[len(parts)-1]
			platformId = runners.ParsePlatform(platform)
			if platformId != currentPlatformId {
				continue
			}

			// Make sure the name matches the requested script name.
			name := base[:len(base)-len(platform)-1]
			if name != scriptName {
				continue
			}
		}

		// Get the runner for the given file extension.
		// ext contains the dot, which we need to drop.
		runner := runners.GetRunner(ext[1:], platformId)
		if runner == nil {
			continue
		}
		cmd := runner.NewCommand(filepath.Join(scriptsDirPath, script))
		cmd.Args = append(cmd.Args, args...)
		cmd.Dir = root
		return cmd, nil
	}

	return nil, &ErrNotFound{scriptName}
}
579312
func (ec *ServiceManager) execute(service RunnableInterface) {
	service.Run()
	defer ec.wg.Done()
}
1266554
func run(dir, command string, args ...string) (string, error) {
	logger.Debugf("(%s) %s %v", dir, command, args)

	cmd := exec.Command(command, args...)
	if dir != "" {
		cmd.Dir = dir
	}

	out, err := cmd.CombinedOutput()
	output := string(out)

	logger.Debugf("output: %v", output)
	return output, err
}
1090815
func (client *sshClient) Run(cmd string) ([]byte, error) {
	// Establish a single command session
	session, err := client.client.NewSession()
	if err != nil {
		return nil, err
	}
	defer session.Close()

	// Execute the command and return any output
	client.logger.Trace("Running command on remote server", "cmd", cmd)
	return session.CombinedOutput(cmd)
}
609441
func (wd *remoteWD) execute(method, url string, data []byte) (json.RawMessage, error) {
	debugLog("-> %s %s\n%s", method, filteredURL(url), data)
	request, err := newRequest(method, url, data)
	if err != nil {
		return nil, err
	}

	response, err := HTTPClient.Do(request)
	if err != nil {
		return nil, err
	}

	buf, err := ioutil.ReadAll(response.Body)
	if debugFlag {
		if err == nil {
			// Pretty print the JSON response
			var prettyBuf bytes.Buffer
			if err = json.Indent(&prettyBuf, buf, "", "    "); err == nil && prettyBuf.Len() > 0 {
				buf = prettyBuf.Bytes()
			}
		}
		debugLog("<- %s [%s]\n%s", response.Status, response.Header["Content-Type"], buf)
	}
	if err != nil {
		return nil, errors.New(response.Status)
	}

	fullCType := response.Header.Get("Content-Type")
	cType, _, err := mime.ParseMediaType(fullCType)
	if err != nil {
		return nil, fmt.Errorf("got content type header %q, expected %q", fullCType, jsonContentType)
	}
	if cType != jsonContentType {
		return nil, fmt.Errorf("got content type %q, expected %q", cType, jsonContentType)
	}

	reply := new(serverReply)
	if err := json.Unmarshal(buf, reply); err != nil {
		if response.StatusCode != http.StatusOK {
			return nil, fmt.Errorf("bad server reply status: %s", response.Status)
		}
		return nil, err
	}
	if reply.Err != "" {
		return nil, &reply.Error
	}

	// Handle the W3C-compliant error format. In the W3C spec, the error is
	// embedded in the 'value' field.
	if len(reply.Value) > 0 {
		respErr := new(Error)
		if err := json.Unmarshal(reply.Value, respErr); err == nil && respErr.Err != "" {
			respErr.HTTPCode = response.StatusCode
			return nil, respErr
		}
	}

	// Handle the legacy error format.
	const success = 0
	if reply.Status != success {
		shortMsg, ok := remoteErrors[reply.Status]
		if !ok {
			shortMsg = fmt.Sprintf("unknown error - %d", reply.Status)
		}

		longMsg := new(struct {
			Message string
		})
		if err := json.Unmarshal(reply.Value, longMsg); err != nil {
			return nil, errors.New(shortMsg)
		}
		return nil, &Error{
			Err:        shortMsg,
			Message:    longMsg.Message,
			HTTPCode:   response.StatusCode,
			LegacyCode: reply.Status,
		}
	}

	return buf, nil
}
1284630
func (a *Astilectron) execute() (err error) {
	// Log
	astilog.Debug("Executing...")

	// Create command
	var ctx, _ = a.canceller.NewContext()
	var singleInstance string
	if a.options.SingleInstance == true {
		singleInstance = "true"
	} else {
		singleInstance = "false"
	}
	var cmd = exec.CommandContext(ctx, a.paths.AppExecutable(), append([]string{a.paths.AstilectronApplication(), a.listener.Addr().String(), singleInstance}, a.options.ElectronSwitches...)...)
	a.stderrWriter = astiexec.NewStdWriter(func(i []byte) { astilog.Debugf("Stderr says: %s", i) })
	a.stdoutWriter = astiexec.NewStdWriter(func(i []byte) { astilog.Debugf("Stdout says: %s", i) })
	cmd.Stderr = a.stderrWriter
	cmd.Stdout = a.stdoutWriter

	// Execute command
	if err = a.executeCmd(cmd); err != nil {
		return errors.Wrap(err, "executing cmd failed")
	}
	return
}