// BufferedExec starts up a command and creates a stdin pipe and a buffered
// stdout & stderr pipes, wrapped in a BufferedCmd. The stdout buffer will be
// of stdoutBufSize bytes.
425853
func BufferedExec(name string, args ...string) (*BufferedCmd, error) {
	cmd := ExecCommand(name, args...)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}
	stderr, err := cmd.StderrPipe()
	if err != nil {
		return nil, err
	}

	stdin, err := cmd.StdinPipe()
	if err != nil {
		return nil, err
	}

	if err := cmd.Start(); err != nil {
		return nil, err
	}

	return &BufferedCmd{
		cmd,
		stdin,
		bufio.NewReaderSize(stdout, stdoutBufSize),
		bufio.NewReaderSize(stderr, stdoutBufSize),
	}, nil
}
591432
func (tx *Tx) ExecEx(ctx context.Context, sql string, options *QueryExOptions, arguments ...interface{}) (commandTag CommandTag, err error) {
	if tx.status != TxStatusInProgress {
		return CommandTag(""), ErrTxClosed
	}

	return tx.conn.ExecEx(ctx, sql, options, arguments...)
}
956834
func (c *Command) ExecuteC() (cmd *Command, err error) {
	// Regardless of what command execute is called on, run on Root only
	if c.HasParent() {
		return c.Root().ExecuteC()
	}

	// windows hook
	if preExecHookFn != nil {
		preExecHookFn(c)
	}

	// initialize help as the last point possible to allow for user
	// overriding
	c.InitDefaultHelpCmd()

	args := c.args

	// Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155
	if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {
		args = os.Args[1:]
	}

	var flags []string
	if c.TraverseChildren {
		cmd, flags, err = c.Traverse(args)
	} else {
		cmd, flags, err = c.Find(args)
	}
	if err != nil {
		// If found parse to a subcommand and then failed, talk about the subcommand
		if cmd != nil {
			c = cmd
		}
		if !c.SilenceErrors {
			c.Println("Error:", err.Error())
			c.Printf("Run '%v --help' for usage.\n", c.CommandPath())
		}
		return c, err
	}

	cmd.commandCalledAs.called = true
	if cmd.commandCalledAs.name == "" {
		cmd.commandCalledAs.name = cmd.Name()
	}

	err = cmd.execute(flags)
	if err != nil {
		// Always show help if requested, even if SilenceErrors is in
		// effect
		if err == flag.ErrHelp {
			cmd.HelpFunc()(cmd, args)
			return cmd, nil
		}

		// If root command has SilentErrors flagged,
		// all subcommands should respect it
		if !cmd.SilenceErrors && !c.SilenceErrors {
			c.Println("Error:", err.Error())
		}

		// If root command has SilentUsage flagged,
		// all subcommands should respect it
		if !cmd.SilenceUsage && !c.SilenceUsage {
			c.Println(cmd.UsageString())
		}
	}
	return cmd, err
}
107712
func pexec(id int64, fn Func) {
	defer func() {
		if err := recover(); err != nil {
			logger.Log.Errorf("Call timer function error, TimerID=%d, Error=%v", id, err)
		}
	}()

	fn()
}
1031633
func (c *contextExec) Exec(timeout time.Duration, cmd string, args []string) ([]byte, int, error) {
	resCh := make(chan execResult, 1)

	// Don't trust the underlying implementation to obey timeout
	ctx, cancel := context.WithTimeout(c.pctx, timeout)
	defer cancel()

	go func() {
		output, code, err := c.exec.Exec(timeout, cmd, args)
		select {
		case resCh <- execResult{output, code, err}:
		case <-ctx.Done():
		}
	}()

	select {
	case res := <-resCh:
		return res.buf, res.code, res.err
	case <-ctx.Done():
		return nil, 0, ctx.Err()
	}
}
1106090
func (p *Pipelined) Command(args ...interface{}) error {
	err := p.conn.SendCommand(args...)
	if err == nil {
		p.times++
	}
	return err
}
1041460
func (a *Agent) handleRemoteExec(msg *UserEvent) {
	a.logger.Printf("[DEBUG] agent: received remote exec event (ID: %s)", msg.ID)
	// Decode the event payload
	var event remoteExecEvent
	if err := json.Unmarshal(msg.Payload, &event); err != nil {
		a.logger.Printf("[ERR] agent: failed to decode remote exec event: %v", err)
		return
	}

	// Read the job specification
	var spec remoteExecSpec
	if !a.remoteExecGetSpec(&event, &spec) {
		return
	}

	// Write the acknowledgement
	if !a.remoteExecWriteAck(&event) {
		return
	}

	// Ensure we write out an exit code
	exitCode := 0
	defer a.remoteExecWriteExitCode(&event, &exitCode)

	// Check if this is a script, we may need to spill to disk
	var script string
	if len(spec.Script) != 0 {
		tmpFile, err := ioutil.TempFile("", "rexec")
		if err != nil {
			a.logger.Printf("[DEBUG] agent: failed to make tmp file: %v", err)
			exitCode = 255
			return
		}
		defer os.Remove(tmpFile.Name())
		os.Chmod(tmpFile.Name(), 0750)
		tmpFile.Write(spec.Script)
		tmpFile.Close()
		script = tmpFile.Name()
	} else {
		script = spec.Command
	}

	// Create the exec.Cmd
	a.logger.Printf("[INFO] agent: remote exec '%s'", script)
	var cmd *osexec.Cmd
	var err error
	if len(spec.Args) > 0 {
		cmd, err = exec.Subprocess(spec.Args)
	} else {
		cmd, err = exec.Script(script)
	}
	if err != nil {
		a.logger.Printf("[DEBUG] agent: failed to start remote exec: %v", err)
		exitCode = 255
		return
	}

	// Setup the output streaming
	writer := &rexecWriter{
		BufCh:    make(chan []byte, 16),
		BufSize:  remoteExecOutputSize,
		BufIdle:  remoteExecOutputDeadline,
		CancelCh: make(chan struct{}),
	}
	cmd.Stdout = writer
	cmd.Stderr = writer

	// Start execution
	if err := cmd.Start(); err != nil {
		a.logger.Printf("[DEBUG] agent: failed to start remote exec: %v", err)
		exitCode = 255
		return
	}

	// Wait for the process to exit
	exitCh := make(chan int, 1)
	go func() {
		err := cmd.Wait()
		writer.Flush()
		close(writer.BufCh)
		if err == nil {
			exitCh <- 0
			return
		}

		// Try to determine the exit code
		if exitErr, ok := err.(*osexec.ExitError); ok {
			if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
				exitCh <- status.ExitStatus()
				return
			}
		}
		exitCh <- 1
	}()

	// Wait until we are complete, uploading as we go
WAIT:
	for num := 0; ; num++ {
		select {
		case out := <-writer.BufCh:
			if out == nil {
				break WAIT
			}
			if !a.remoteExecWriteOutput(&event, num, out) {
				close(writer.CancelCh)
				exitCode = 255
				return
			}
		case <-time.After(spec.Wait):
			// Acts like a heartbeat, since there is no output
			if !a.remoteExecWriteOutput(&event, num, nil) {
				close(writer.CancelCh)
				exitCode = 255
				return
			}
		}
	}

	// Get the exit code
	exitCode = <-exitCh
}
1347849
func ExecPipe(program string, args ...string) error {
	return ExecPipeToFds(Fds{out, out}, program, args...)
}
1265859
func (r *remoteExec) Start(ch ssh.Channel) (*ExecResult, error) {
	// hook up stdout/err the channel so the user can interact with the command
	r.session.Stdout = ch
	r.session.Stderr = ch.Stderr()
	inputWriter, err := r.session.StdinPipe()
	if err != nil {
		return nil, trace.Wrap(err)
	}

	go func() {
		// copy from the channel (client) into stdin of the process
		io.Copy(inputWriter, ch)
		inputWriter.Close()
	}()

	err = r.session.Start(r.command)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	return nil, nil
}
1041085
func (e SearchService) PartialExec(idx, statement string, params map[string]interface{}) (res SearchResult, err error) {
	query := SearchQuery{
		Index: idx,
		Query: statement,
		// These are the defaults in chef: https://github.com/opscode/chef/blob/master/lib/chef/search/query.rb#L102-L105
		SortBy: "X_CHEF_id_CHEF_X asc",
		Start:  0,
		Rows:   1000,
	}

	fullUrl := fmt.Sprintf("search/%s", query)

	body, err := JSONReader(params)
	if err != nil {
		debug("Problem encoding params for body")
		return
	}

	err = e.client.magicRequestDecoder("POST", fullUrl, body, &res)
	return
}
731530
func RunDockerExec(containerID string, bashcmd []string) ([]byte, error) {
	oldStdin := os.Stdin
	os.Stdin = nil // temporary stdin=nil https://github.com/docker/docker/pull/9537
	command, err := generateDockerExecCommand(containerID, bashcmd, true)
	os.Stdin = oldStdin
	if err != nil {
		return nil, err
	}
	thecmd := exec.Command(command[0], command[1:]...)
	output, err := thecmd.CombinedOutput()
	if err != nil {
		err = DockerExecError{strings.Join(command, " "), err}
		return output, err
	}
	glog.V(1).Infof("Successfully ran command:'%s' output: %s\n", command, output)
	return output, nil
}
1147906
func (cniReq *cniServer) ipnsExecute(namespace string, args []string) ([]byte, error) {
	ipCmd := "ip"
	ipArgs := []string{"netns", "exec", namespace}

	ipArgs = append(ipArgs, args...)
	cniLog.Infof("processing cmd: %v", ipArgs)
	return exec.Command(ipCmd, ipArgs...).CombinedOutput()
}
1198492
func (c *Client) Exec() ([]interface{}, error) {
	var ret []interface{}
	err := c.command(
		&ret,
		[]byte("EXEC"),
	)
	return ret, err
}
712245
func NewBufferedOutput(output TextOutput, buffer int) *BufferedOutput {
	if buffer < 0 {
		buffer = 0
	}
	b := &BufferedOutput{
		o: output,
		c: make(chan bufferMsg, buffer)}
	go b.process()
	return b
}
434936
func ExecPipeToFds(fds Fds, program string, args ...string) error {
	log.Printf("+++ invoke: %s %v", program, args)
	defer log.Printf("--- invoke end")
	cmd := osexec.Command(program, args...)

	// replace nil streams with default
	if fds.Out == nil {
		fds.Out = out
	}
	if fds.Err == nil {
		fds.Err = out
	}

	cmd.Stdout, cmd.Stderr = fds.Out, fds.Err
	err := cmd.Run()
	if err != nil {
		err = fmt.Errorf("executing %s %v failed: %v", program, args, err)
	}
	return err
}
552356
func parseExec(opts execOptions, configFile *configfile.ConfigFile) *types.ExecConfig {
	execConfig := &types.ExecConfig{
		User:       opts.user,
		Privileged: opts.privileged,
		Tty:        opts.tty,
		Cmd:        opts.command,
		Detach:     opts.detach,
		Env:        opts.env.GetAll(),
		WorkingDir: opts.workdir,
	}

	// If -d is not set, attach to everything by default
	if !opts.detach {
		execConfig.AttachStdout = true
		execConfig.AttachStderr = true
		if opts.interactive {
			execConfig.AttachStdin = true
		}
	}

	if opts.detachKeys != "" {
		execConfig.DetachKeys = opts.detachKeys
	} else {
		execConfig.DetachKeys = configFile.DetachKeys
	}
	return execConfig
}
316362
func (t *TermHandlers) HandleExec(ch ssh.Channel, req *ssh.Request, ctx *ServerContext) error {
	execRequest, err := parseExecRequest(req, ctx)
	if err != nil {
		return trace.Wrap(err)
	}

	// a terminal has been previously allocate for this command.
	// run this inside an interactive session
	if ctx.GetTerm() != nil {
		return t.SessionRegistry.OpenSession(ch, req, ctx)
	}

	// If this code is running on a Teleport node and PAM is enabled, then open a
	// PAM context.
	var pamContext *pam.PAM
	if ctx.srv.Component() == teleport.ComponentNode {
		conf, err := t.SessionRegistry.srv.GetPAM()
		if err != nil {
			return trace.Wrap(err)
		}

		if conf.Enabled == true {
			// Note, stdout/stderr is discarded here, otherwise MOTD would be printed to
			// the users screen during exec requests.
			pamContext, err = pam.Open(&pam.Config{
				ServiceName: conf.ServiceName,
				Username:    ctx.Identity.Login,
				Stdin:       ch,
				Stderr:      ioutil.Discard,
				Stdout:      ioutil.Discard,
			})
			if err != nil {
				return trace.Wrap(err)
			}
			ctx.Debugf("Opening PAM context for exec request %q.", execRequest.GetCommand())
		}
	}

	// otherwise, regular execution
	result, err := execRequest.Start(ch)
	if err != nil {
		return trace.Wrap(err)
	}
	// if the program failed to start, we should send that result back
	if result != nil {
		ctx.Debugf("Exec request (%v) result: %v", execRequest, result)
		ctx.SendExecResult(*result)
	}

	// in case if result is nil and no error, this means that program is
	// running in the background
	go func() {
		result, err = execRequest.Wait()
		if err != nil {
			ctx.Errorf("Exec request (%v) wait failed: %v", execRequest, err)
		}
		if result != nil {
			ctx.SendExecResult(*result)
		}

		// If this code is running on a Teleport node and PAM is enabled, close the context.
		if ctx.srv.Component() == teleport.ComponentNode {
			conf, err := t.SessionRegistry.srv.GetPAM()
			if err != nil {
				ctx.Errorf("Unable to get PAM configuration from server: %v", err)
				return
			}

			if conf.Enabled == true {
				err = pamContext.Close()
				if err != nil {
					ctx.Errorf("Unable to close PAM context for exec request: %q: %v", execRequest.GetCommand(), err)
					return
				}
				ctx.Debugf("Closing PAM context for exec request: %q.", execRequest.GetCommand())
			}
		}
	}()

	return nil
}