func (w *Worker) ExecBin(binPath string, args []string, maxRunTime int64) (string, error) { var cmd *exec.Cmd var stdout bytes.Buffer var stderr bytes.Buffer var err error if len(args) == 0 { cmd = exec.Command(binPath) } else { cmd = exec.Command(binPath, args...) } cmd.Stdout = &stdout cmd.Stderr = &stderr cmd.Start() // attention! err, _ = w.CmdRunWithTimeout(cmd, time.Duration(maxRunTime)*time.Second, ) if err != nil { return "", err } if len(stderr.String()) != 0 { errMsg := strings.TrimRight(stderr.String(), "\n") return "", errors.NewError(errMsg) } return strings.TrimRight(stdout.String(), "\n"), nil }
func init() { registerCommand(&cmd.Command{ Name: "doc", UsageLine: `doc <pkg> <sym>[.<method>]`, Short: "show documentation for a package or symbol", Long: ` Doc shows documentation for a package or symbol. See 'go help doc'. `, Run: func(ctx *gb.Context, args []string) error { env := cmd.MergeEnv(os.Environ(), map[string]string{ "GOPATH": fmt.Sprintf("%s:%s", ctx.Projectdir(), filepath.Join(ctx.Projectdir(), "vendor")), }) if len(args) == 0 { args = append(args, ".") } args = append([]string{filepath.Join(ctx.Context.GOROOT, "bin", "godoc")}, args...) cmd := exec.Cmd{ Path: args[0], Args: args, Env: env, Stdin: os.Stdin, Stdout: os.Stdout, Stderr: os.Stderr, } return cmd.Run() }, ParseArgs: func(_ *gb.Context, _ string, args []string) []string { return args }, }) }
func TestStatStdin(t *testing.T) { switch runtime.GOOS { case "android", "plan9": t.Skipf("%s doesn't have /bin/sh", runtime.GOOS) } testenv.MustHaveExec(t) if Getenv("GO_WANT_HELPER_PROCESS") == "1" { st, err := Stdin.Stat() if err != nil { t.Fatalf("Stat failed: %v", err) } fmt.Println(st.Mode() & ModeNamedPipe) Exit(0) } var cmd *osexec.Cmd if runtime.GOOS == "windows" { cmd = osexec.Command("cmd", "/c", "echo output | "+Args[0]+" -test.run=TestStatStdin") } else { cmd = osexec.Command("/bin/sh", "-c", "echo output | "+Args[0]+" -test.run=TestStatStdin") } cmd.Env = append(Environ(), "GO_WANT_HELPER_PROCESS=1") output, err := cmd.CombinedOutput() if err != nil { t.Fatalf("Failed to spawn child process: %v %q", err, string(output)) } // result will be like "prw-rw-rw" if len(output) < 1 || output[0] != 'p' { t.Fatalf("Child process reports stdin is not pipe '%v'", string(output)) } }
// Configuration reload func Reload(binary, config, pidfile string) error { pid, err := ioutil.ReadFile(pidfile) if err != nil { return err } /* Setup all the command line parameters so we get an executable similar to /usr/local/bin/haproxy -f resources/haproxy_new.cfg -p resources/haproxy-private.pid -st 1234 */ arg0 := "-f" arg1 := config arg2 := "-p" arg3 := pidfile arg4 := "-st" arg5 := strings.Trim(string(pid), "\n") var cmd *exec.Cmd // If this is the first run, the PID value will be empty, otherwise it will be > 0 if len(arg5) > 0 { cmd = exec.Command(binary, arg0, arg1, arg2, arg3, arg4, arg5) } else { cmd = exec.Command(binary, arg0, arg1, arg2, arg3) } var out bytes.Buffer cmd.Stdout = &out cmdErr := cmd.Run() if cmdErr != nil { fmt.Println(cmdErr.Error()) return cmdErr } log.Info("HaproxyReload: " + out.String() + string(pid)) return nil }
func (spec SpecPackage) checkVersionPackageExact(defaults PlatformDefaults) (err error) { var cmd *exec.Cmd var verRex string switch spec.Type { case "homebrew": // sbt 0.12.3 0.12.4 0.13.0 cmd = exec.Command("/usr/local/bin/brew", "ls", "--versions", spec.Name) verRex = " " + spec.Version + "( |$)" default: return errors.New("Unknown package manager type " + spec.Type) } out, err := cmd.Output() if err != nil { return err } re, err := regexp.Compile(verRex) if err != nil { return fmt.Errorf("Bad verRex %s for package manager type %s", verRex, spec.Type) } if re.FindIndex(out) == nil && !spec.Absent { return errors.New("No such version installed") } return nil }
// startContainer starts the container. Returns the exit status or -1 and an // error. // // Signals sent to the current process will be forwarded to container. func startContainer(container *libcontainer.Config, term namespaces.Terminal, dataPath string, args []string) (int, error) { var ( cmd *exec.Cmd sigc = make(chan os.Signal, 10) ) signal.Notify(sigc) createCommand := func(container *libcontainer.Config, console, rootfs, dataPath, init string, pipe *os.File, args []string) *exec.Cmd { cmd = namespaces.DefaultCreateCommand(container, console, rootfs, dataPath, init, pipe, args) if logPath != "" { cmd.Env = append(cmd.Env, fmt.Sprintf("log=%s", logPath)) } return cmd } startCallback := func() { go func() { for sig := range sigc { cmd.Process.Signal(sig) } }() } return namespaces.Exec(container, term, "", dataPath, args, createCommand, startCallback) }
func runCommandWithOutput(cmd *exec.Cmd) (output string, exitCode int, err error) { exitCode = 0 out, err := cmd.CombinedOutput() exitCode = processExitCode(err) output = string(out) return }
func RedirectIOTo(cmd *exec.Cmd, myin io.Reader, myout, myerr io.Writer) { // redirect IO cmd.Stdout = myout cmd.Stderr = myerr cmd.Stdin = myin //return nil, err }
func (s *SlaveNode) babysitRootProcess(cmd *exec.Cmd) { // We want to let this process run "forever", but it will eventually // die... either on program termination or when its dependencies change // and we kill it. when it's requested to restart, err is "signal 9", // and we do nothing. s.trace("running the root command now") output, err := cmd.CombinedOutput() if err == nil { // TODO s.trace("root process exited; output was: %s", output) println(string(output)) /* ErrorConfigCommandCrashed(string(output)) */ } msg := err.Error() if s.hasSuccessfullyBooted == false { // TODO s.trace("root process exited with an error before it could boot: %s; output was: %s", msg, output) println(msg) /* ErrorConfigCommandCouldntStart(msg, string(output)) */ } else if msg == "signal 9" { s.trace("root process exited because we killed it & it will be restarted: %s; output was: %s", msg, output) } else { s.L.Lock() defer s.L.Unlock() if s.State == SUnbooted { s.trace("root process exited with error. Sending it to crashed state. Message was: %s; output: %s", msg, output) s.Error = fmt.Sprintf("Zeus root process (%s) died with message %s:\n%s", s.Name, msg, output) s.event <- true } else { s.trace("Unexpected state for root process to be in at this time: %s", s.State) } } }
func (b *Provider) mountDataset(vol *zfsVolume) error { // mount the dataset, snapshots will be readonly // 'zfs mount' currently can't perform on snapshots; seealso https://github.com/zfsonlinux/zfs/issues/173 alreadyMounted, err := isMount(vol.basemount) if err != nil { return fmt.Errorf("could not mount: %s", err) } if alreadyMounted { return nil } if err = os.MkdirAll(vol.basemount, 0644); err != nil { return fmt.Errorf("could not mount: %s", err) } var buf bytes.Buffer var cmd *exec.Cmd if vol.IsSnapshot() { cmd = exec.Command("mount", "-tzfs", vol.dataset.Name, vol.basemount) } else { cmd = exec.Command("zfs", "mount", vol.dataset.Name) } cmd.Stderr = &buf if err := cmd.Run(); err != nil { return fmt.Errorf("could not mount: %s (%s)", err, strings.TrimSpace(buf.String())) } return nil }
func waitSimple(command *Command, cmd *osexec.Cmd) error { err := cmd.Wait() if err != nil { glog.Errorf("Command exited with %s: %s", err, DebugString(command)) } return err }
// runInContext runs a command in the context of a Vagrantfile (from the same dir) func runInContext(cmd *exec.Cmd) error { // run the command from ~/.nanobox/apps/<config.App>. Running the command from // the directory that contains the Vagratfile ensure that the command can // atleast run (especially in cases like 'create' where a VM hadn't been created // yet, and a UUID isn't available) setContext(config.AppDir) // handleCMDout(cmd) // start the command; we need this to 'fire and forget' so that we can manually // capture and modify the commands output above if err := cmd.Start(); err != nil { return err } // wait for the command to complete/fail and exit, giving us a chance to scan // the output if err := cmd.Wait(); err != nil { return err } // switch back to project dir setContext(config.CWDir) return nil }
/* Start starts the passed-in *exec.Cmd command. It wraps the command in a *gexec.Session. The session pipes the command's stdout and stderr to two *gbytes.Buffers available as properties on the session: session.Out and session.Err. These buffers can be used with the gbytes.Say matcher to match against unread output: Ω(session.Out).Should(gbytes.Say("foo-out")) Ω(session.Err).Should(gbytes.Say("foo-err")) In addition, Session satisfies the gbytes.BufferProvider interface and provides the stdout *gbytes.Buffer. This allows you to replace the first line, above, with: Ω(session).Should(gbytes.Say("foo-out")) When outWriter and/or errWriter are non-nil, the session will pipe stdout and/or stderr output both into the session *gybtes.Buffers and to the passed-in outWriter/errWriter. This is useful for capturing the process's output or logging it to screen. In particular, when using Ginkgo it can be convenient to direct output to the GinkgoWriter: session, err := Start(command, GinkgoWriter, GinkgoWriter) This will log output when running tests in verbose mode, but - otherwise - will only log output when a test fails. The session wrapper is responsible for waiting on the *exec.Cmd command. You *should not* call command.Wait() yourself. Instead, to assert that the command has exited you can use the gexec.Exit matcher: Ω(session).Should(gexec.Exit()) When the session exits it closes the stdout and stderr gbytes buffers. This will short circuit any Eventuallys waiting fo the buffers to Say something. */ func Start(command *exec.Cmd, outWriter io.Writer, errWriter io.Writer) (*Session, error) { exited := make(chan struct{}) session := &Session{ Command: command, Out: gbytes.NewBuffer(), Err: gbytes.NewBuffer(), Exited: exited, lock: &sync.Mutex{}, exitCode: -1, } var commandOut, commandErr io.Writer commandOut, commandErr = session.Out, session.Err if outWriter != nil && !reflect.ValueOf(outWriter).IsNil() { commandOut = io.MultiWriter(commandOut, outWriter) } if errWriter != nil && !reflect.ValueOf(errWriter).IsNil() { commandErr = io.MultiWriter(commandErr, errWriter) } command.Stdout = commandOut command.Stderr = commandErr err := command.Start() if err == nil { go session.monitorForExit(exited) } return session, err }
func (w *Worker) CmdRunWithTimeout(cmd *exec.Cmd, timeout time.Duration) (error, bool) { done := make(chan error) go func() { done <- cmd.Wait() }() var err error select { case <-time.After(timeout): // timeout if err = cmd.Process.Kill(); err != nil { golog.Error("worker", "CmdRunTimeout", "kill error", 0, "path", cmd.Path, "error", err.Error(), ) } golog.Info("worker", "CmdRunWithTimeout", "kill process", 0, "path", cmd.Path, "error", errors.ErrExecTimeout.Error(), ) go func() { <-done // allow goroutine to exit }() return errors.ErrExecTimeout, true case err = <-done: return err, false } }
// "run" let's the user execute arbitrary commands func runFn(args []interface{}) (interface{}, error) { if len(args) < 1 { return nil, errors.New("run takes at least one argument") } commands := []string{} for _, arg := range args { if s, ok := arg.(string); ok { commands = append(commands, s) } else { return nil, errors.New("run only takes string arguments") } } var cmd *exec.Cmd if len(commands) == 1 { cmd = exec.Command(commands[0]) } else { cmd = exec.Command(commands[0], commands[1:]...) } log.Printf("executing command '%s' with arguments: %s\n", commands[0], strings.Join(commands[1:], ",")) if err := cmd.Run(); err == nil { cmd.Wait() } return nil, nil }
func (gb GenericBrowser) Open(s string) error { u, err := url.Parse(s) if err != nil { return err } // Enforce a scheme (windows requires scheme to be set to work properly). if u.Scheme != "https" { u.Scheme = "http" } s = u.String() // Escape characters not allowed by cmd/bash switch runtime.GOOS { case "windows": s = strings.Replace(s, "&", `^&`, -1) } var cmd *exec.Cmd if gb.Args != nil { cmd = exec.Command(gb.Cmd, append(gb.Args, s)...) } else { cmd = exec.Command(gb.Cmd, s) } return cmd.Run() }
// Unmount attempts to unmount the provided FUSE mount point, forcibly // if necessary. func Unmount(point string) error { fmt.Printf("Unmounting %s...\n", point) var cmd *exec.Cmd switch runtime.GOOS { case "darwin": cmd = exec.Command("diskutil", "umount", "force", point) case "linux": cmd = exec.Command("fusermount", "-u", point) default: return fmt.Errorf("unmount: unimplemented") } errc := make(chan error, 1) go func() { if err := exec.Command("umount", point).Run(); err == nil { errc <- err } // retry to unmount with the fallback cmd errc <- cmd.Run() }() select { case <-time.After(1 * time.Second): return fmt.Errorf("umount timeout") case err := <-errc: return err } }
func runCommandWithOutputForDuration(cmd *exec.Cmd, duration time.Duration) (output string, exitCode int, timedOut bool, err error) { var outputBuffer bytes.Buffer if cmd.Stdout != nil { err = errors.New("cmd.Stdout already set") return } cmd.Stdout = &outputBuffer if cmd.Stderr != nil { err = errors.New("cmd.Stderr already set") return } cmd.Stderr = &outputBuffer done := make(chan error) go func() { exitErr := cmd.Run() exitCode = processExitCode(exitErr) done <- exitErr }() select { case <-time.After(duration): killErr := cmd.Process.Kill() if killErr != nil { fmt.Printf("failed to kill (pid=%d): %v\n", cmd.Process.Pid, killErr) } timedOut = true break case err = <-done: break } output = outputBuffer.String() return }
func (w *World) CmdWithEnv(binary string, env []string, args ...string) *exec.Cmd { hasVerbose := func() bool { for _, v := range args { if v == "-verbose" || v == "--verbose" { return true } } return false } var cmd *exec.Cmd switch binary { case "camget", "camput", "camtool", "cammount": // TODO(mpl): lift the camput restriction when we have a unified logging mechanism if binary == "camput" && !hasVerbose() { // camput and camtool are the only ones to have a -verbose flag through cmdmain // but camtool is never used. (and cammount does not even have a -verbose). args = append([]string{"-verbose"}, args...) } cmd = exec.Command(filepath.Join(w.camRoot, "bin", binary), args...) clientConfigDir := filepath.Join(w.camRoot, "config", "dev-client-dir") cmd.Env = append([]string{ "CAMLI_CONFIG_DIR=" + clientConfigDir, // Respected by env expansions in config/dev-client-dir/client-config.json: "CAMLI_SERVER=" + w.ServerBaseURL(), "CAMLI_SECRET_RING=" + w.SecretRingFile(), "CAMLI_KEYID=" + w.ClientIdentity(), "CAMLI_AUTH=userpass:testuser:passTestWorld", }, env...) default: panic("Unknown binary " + binary) } return cmd }
func authorized() bool { if authorizedCheck() { return true } logger.Debug("Requesting superuser authentication") var cmd *exec.Cmd var sudoTool = "sudo" /*if !authorizedIsCheck() { _, err := exec.LookPath("gksudo") if err == nil { return "gksudo" } }*/ if sudoTool == "sudo" { cmd = exec.Command("sudo", "echo") } else { cmd = exec.Command("gksudo", "darknet") } _, err := cmd.CombinedOutput() if err != nil { return false } if authorizedCheck() { return true } return false }
// Run() an instance of this container and return it's exec.Command reference and a // channel that sends the exit code, when the container exits func (c *Container) run() (*exec.Cmd, chan error) { // the container name is semi random because containers can get wedged // in docker and can not be removed until a reboot (or aufs trickery) containerName := c.Name + "-" + uuid() exitChan := make(chan error, 1) args := make([]string, 0) args = append(args, "run", "-rm", "-name", containerName) // attach all exported ports for _, port := range c.Ports { args = append(args, "-p", fmt.Sprintf("%d:%d", port, port)) } // attach resources directory to all containers args = append(args, "-v", resourcesDir()+":"+"/usr/local/serviced/resources") // attach all exported volumes for name, volume := range c.Volumes { hostDir := path.Join(c.VolumesDir(), c.Name, name) if exists, _ := isDir(hostDir); !exists { if err := os.MkdirAll(hostDir, 0777); err != nil { glog.Errorf("could not create %s on host: %s", hostDir, err) exitChan <- err return nil, exitChan } } args = append(args, "-v", hostDir+":"+volume) } // set the image and command to run args = append(args, c.Repo+":"+c.Tag, "/bin/sh", "-c", c.Command) glog.V(1).Infof("Executing docker %s", args) var cmd *exec.Cmd tries := 5 var err error for { if tries > 0 { cmd = exec.Command("docker", args...) if err := cmd.Start(); err != nil { glog.Errorf("Could not start: %s", c.Name) c.stop() c.rm() time.Sleep(time.Second * 1) } else { break } } else { exitChan <- err return cmd, exitChan } tries = -1 } go func() { exitChan <- cmd.Wait() }() return cmd, exitChan }
func (b *builder) Build() error { var command *exec.Cmd if b.useGodep { command = exec.Command("godep", "go", "build", "-o", b.binary) } else { command = exec.Command("go", "build", "-o", b.binary) } command.Dir = b.dir output, err := command.CombinedOutput() if err != nil { return err } if command.ProcessState.Success() { b.errors = "" } else { b.errors = string(output) } if len(b.errors) > 0 { return fmt.Errorf(b.errors) } return nil }
func ExecImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) { if !StringP(First(args)) { err = ProcessError(fmt.Sprintf("exec requires a string command, but received %s.", String(First(args))), env) } cmdString := StringValue(First(args)) cmdArgs := make([]string, 0, Length(args)-1) var cmd *exec.Cmd if Length(args) > 1 { for cell := Cdr(args); !NilP(cell); cell = Cdr(cell) { value := Car(cell) if StringP(value) || SymbolP(value) { cmdArgs = append(cmdArgs, StringValue(value)) } else { cmdArgs = append(cmdArgs, String(value)) } } cmd = exec.Command(cmdString, cmdArgs...) } else { cmd = exec.Command(cmdString) } err = cmd.Start() return }
func (t *TtyConsole) AttachPipes(command *exec.Cmd, pipes *execdriver.Pipes) error { command.Stdout = t.SlavePty command.Stderr = t.SlavePty go func() { if wb, ok := pipes.Stdout.(interface { CloseWriters() error }); ok { defer wb.CloseWriters() } io.Copy(pipes.Stdout, t.MasterPty) }() if pipes.Stdin != nil { command.Stdin = t.SlavePty command.SysProcAttr.Setctty = true go func() { io.Copy(t.MasterPty, pipes.Stdin) pipes.Stdin.Close() }() } return nil }
func (spec SpecPackage) checkPackage(defaults PlatformDefaults) (err error) { var cmd *exec.Cmd switch spec.Type { case "rpm": rpm, err := exec.LookPath("rpm") if err != nil { return err } cmd = exec.Command(rpm, "-q", spec.Name) case "dpkg": dpkg, err := exec.LookPath("dpkg") if err != nil { return err } cmd = exec.Command(dpkg, "-L", spec.Name) case "pacman": // TODO case "ebuild": // TODO case "homebrew": cmd = exec.Command("/usr/local/bin/brew", "ls", spec.Name) case "gem": cmd = exec.Command("/bin/bash", "-ic", "gem contents "+spec.Name) default: return errors.New("Unknown package manager type " + spec.Type) } err = cmd.Run() if err != nil && !spec.Absent { return err } else { return nil } }
func writeGitRepositoryArchive(w io.Writer, path string, ref GitCommitRef) error { var cmd *exec.Cmd // TODO: Stream as tar with gzip if ref == EmptyGitCommitRef { cmd = exec.Command("/usr/bin/git", "archive", "--format", "zip", "master") } else { cmd = exec.Command("/usr/bin/git", "archive", "--format", "zip", string(ref)) } cmd.Env = []string{} cmd.Dir = path var stderr bytes.Buffer cmd.Stderr = utils.LimitWriter(&stderr, 20*1024) stdout, err := cmd.StdoutPipe() if err != nil { return err } if err := cmd.Start(); err != nil { return err } io.Copy(w, stdout) if err := cmd.Wait(); err != nil { return errors.New(fmt.Sprintf("Failed to archive repository: %s\n", err.Error()) + stderr.String()) } return nil }
func verifyCertWithSystem(block *pem.Block, add func(*Certificate)) { data := pem.EncodeToMemory(block) var cmd *exec.Cmd if needsTmpFiles() { f, err := ioutil.TempFile("", "cert") if err != nil { fmt.Fprintf(os.Stderr, "can't create temporary file for cert: %v", err) return } defer os.Remove(f.Name()) if _, err := f.Write(data); err != nil { fmt.Fprintf(os.Stderr, "can't write temporary file for cert: %v", err) return } if err := f.Close(); err != nil { fmt.Fprintf(os.Stderr, "can't write temporary file for cert: %v", err) return } cmd = exec.Command("/usr/bin/security", "verify-cert", "-c", f.Name(), "-l") } else { cmd = exec.Command("/usr/bin/security", "verify-cert", "-c", "/dev/stdin", "-l") cmd.Stdin = bytes.NewReader(data) } if cmd.Run() == nil { // Non-zero exit means untrusted cert, err := ParseCertificate(block.Bytes) if err != nil { return } add(cert) } }
// ExecAdd executes IPAM plugin, assuming CNI_COMMAND == ADD. // Parses and returns resulting IPConfig func ExecAdd(plugin string, netconf []byte) (*Result, error) { if os.Getenv("CNI_COMMAND") != "ADD" { return nil, fmt.Errorf("CNI_COMMAND is not ADD") } pluginPath := Find(plugin) if pluginPath == "" { return nil, fmt.Errorf("could not find %q plugin", plugin) } stdout := &bytes.Buffer{} c := exec.Cmd{ Path: pluginPath, Args: []string{pluginPath}, Stdin: bytes.NewBuffer(netconf), Stdout: stdout, Stderr: os.Stderr, } if err := c.Run(); err != nil { return nil, pluginErr(err, stdout.Bytes()) } res := &Result{} err := json.Unmarshal(stdout.Bytes(), res) return res, err }
// ForceUnmount attempts to forcibly unmount a given mount. // It does so by calling diskutil or fusermount directly. func ForceUnmount(m Mount) error { point := m.MountPoint() log.Warningf("Force-Unmounting %s...", point) var cmd *exec.Cmd switch runtime.GOOS { case "darwin": cmd = exec.Command("diskutil", "umount", "force", point) case "linux": cmd = exec.Command("fusermount", "-u", point) default: return fmt.Errorf("unmount: unimplemented") } errc := make(chan error, 1) go func() { defer close(errc) // try vanilla unmount first. if err := exec.Command("umount", point).Run(); err == nil { return } // retry to unmount with the fallback cmd errc <- cmd.Run() }() select { case <-time.After(7 * time.Second): return fmt.Errorf("umount timeout") case err := <-errc: return err } }
func run(cmd *exec.Cmd) { cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { log.Fatal(err) } }