func run(c *exec.Cmd) error { r := c.Run() if r != nil { return fmt.Errorf("%s %s: %s", c.Path, c.Args[0], r) } return nil }
func run(src string) error { // Create a temp folder. tempDir, err := ioutil.TempDir("", "goexec_") if err != nil { return err } defer func() { err := os.RemoveAll(tempDir) if err != nil { fmt.Fprintln(os.Stderr, "warning: error removing temp dir:", err) } }() // Write the source code file. tempFile := filepath.Join(tempDir, "gen.go") err = ioutil.WriteFile(tempFile, []byte(src), 0600) if err != nil { return err } // Compile and run the program. var cmd *exec.Cmd switch *compilerFlag { case "gc": cmd = exec.Command("go", "run", tempFile) case "gopherjs": cmd = exec.Command("gopherjs", "run", tempFile) } cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr return cmd.Run() }
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 }
// 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 (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() }
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 (i *Image) Resize(dst, format string, w, h, q int, optimize bool) error { wh := fmt.Sprintf("%dx%d", w, h) if w == 0 { wh = fmt.Sprintf("x%d", h) } if h == 0 { wh = fmt.Sprintf("%d", w) } if format == "" { format = i.Type } dstImagick := format + ":" + dst var cmd *exec.Cmd if q > 0 { cmd = exec.Command("convert", i.Filename, "-strip", "-resize", wh, "-quality", fmt.Sprintf("%d", q), dstImagick) } else { cmd = exec.Command("convert", i.Filename, "-strip", "-resize", wh, dstImagick) } if err := cmd.Run(); err != nil { return err } i.Width = w i.Height = h i.Type = format if optimize { i.optimize(dst) } return nil }
// Graphviz generates a specification for the graphviz program that visualizes the // communication graph of a stitch. func graphviz(outputFormat string, slug string, dot string) { f, err := util.AppFs.Create(slug + ".dot") if err != nil { panic(err) } defer f.Close() f.Write([]byte(dot)) if outputFormat == "graphviz" { return } defer exec.Command("rm", slug+".dot").Run() // Dependencies: // - easy-graph (install Graph::Easy from cpan) // - graphviz (install from your favorite package manager) var writeGraph *exec.Cmd switch outputFormat { case "ascii": writeGraph = exec.Command("graph-easy", "--input="+slug+".dot", "--as_ascii") case "pdf": writeGraph = exec.Command("dot", "-Tpdf", "-o", slug+".pdf", slug+".dot") } writeGraph.Stdout = os.Stdout writeGraph.Stderr = os.Stderr writeGraph.Run() }
func (command Command) Run() { fmt.Printf("Initializing %s\n", command.Name) if command.Before != nil { command.Before() } args := strings.Split(command.Value, " ") var cmd *exec.Cmd if len(args) > 1 { cmd = exec.Command(args[0], args[1:len(args)]...) } else { cmd = exec.Command(args[0]) } err := cmd.Run() if err != nil { log.Fatal(err) } for _, subcommand := range command.SubCommands { subcommand.Run() } fmt.Printf("Finished %s\n", command.Name) }
func GetDiff(repoPath, commitid string) (*Diff, error) { repo, err := git.OpenRepository(repoPath) if err != nil { return nil, err } commit, err := repo.GetCommit(commitid) if err != nil { return nil, err } rd, wr := io.Pipe() var cmd *exec.Cmd // First commit of repository. if commit.ParentCount() == 0 { cmd = exec.Command("git", "show", commitid) } else { c, _ := commit.Parent(0) cmd = exec.Command("git", "diff", c.Id.String(), commitid) } cmd.Dir = repoPath cmd.Stdout = wr cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr go func() { cmd.Run() wr.Close() }() defer rd.Close() return ParsePatch(cmd, rd) }
func runAndLog(cmd *exec.Cmd) (string, string, error) { var stdout, stderr bytes.Buffer log.Printf("Executing: %s %v", cmd.Path, cmd.Args[1:]) cmd.Stdout = &stdout cmd.Stderr = &stderr err := cmd.Run() stdoutString := strings.TrimSpace(stdout.String()) stderrString := strings.TrimSpace(stderr.String()) if _, ok := err.(*exec.ExitError); ok { message := stderrString if message == "" { message = stdoutString } err = fmt.Errorf("VMware error: %s", message) } log.Printf("stdout: %s", stdoutString) log.Printf("stderr: %s", stderrString) // Replace these for Windows, we only want to deal with Unix // style line endings. returnStdout := strings.Replace(stdout.String(), "\r\n", "\n", -1) returnStderr := strings.Replace(stderr.String(), "\r\n", "\n", -1) return returnStdout, returnStderr, err }
// requires dotfile path, home path func install_vim(dp string, hp string) { src1 := filepath.Join(dp, ".vim") dst1 := filepath.Join(hp, ".vim") symlink(src1, dst1) src2 := filepath.Join(dp, ".vimrc") dst2 := filepath.Join(hp, ".vimrc") symlink(src2, dst2) var gitcmd *exec.Cmd _, err := os.Lstat(filepath.Join(dp, ".vim", "bundle", "vundle")) if err == nil { fmt.Printf("Skipping vundle clone because" + " .vim/bundle/vundle exists") goto vundle_init } if err.(*os.PathError).Err.Error() != "no such file or directory" { panic(fmt.Sprintf("Failed to handle stat of"+ ".vim/bundle/vundle %s.", err)) } gitcmd = exec.Command("git", "clone", "https://github.com/gmarik/vundle.git", filepath.Join(dp, ".vim/bundle/vundle")) err = gitcmd.Run() if err != nil { panic(fmt.Sprintf("Failed to clone vundle. %s", err)) } vundle_init: vcmd := exec.Command("vim", "+BundleInstall", "+qall") err = vcmd.Run() if err != nil { panic(fmt.Sprintf("Failed to init vundle. %s", err)) } }
// GC enters the pod by fork/exec()ing the stage1's /gc similar to /init. // /gc can expect to have its CWD set to the pod root. // stage1Path is the path of the stage1 rootfs func GC(pdir string, uuid *types.UUID, stage1Path string, debug bool) error { err := unregisterPod(pdir, uuid) if err != nil { // Probably not worth abandoning the rest log.Printf("Warning: could not unregister pod with metadata service: %v", err) } ep, err := getStage1Entrypoint(pdir, gcEntrypoint) if err != nil { return fmt.Errorf("error determining gc entrypoint: %v", err) } args := []string{filepath.Join(stage1Path, ep)} if debug { args = append(args, "--debug") } args = append(args, uuid.String()) c := exec.Cmd{ Path: args[0], Args: args, Stderr: os.Stderr, Dir: pdir, } return c.Run() }
func run(cmd *exec.Cmd) { cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { log.Fatal(err) } }
func (srv *HopServer) cleanUp() { // Pre Down if srv.cfg.Down != "" { args := strings.Split(srv.cfg.Down, " ") var cmd *exec.Cmd if len(args) == 1 { cmd = exec.Command(args[0]) } else { cmd = exec.Command(args[0], args[1:]...) } logger.Info(srv.cfg.Down) cmd.Run() } c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGINT, syscall.SIGTERM) <-c for _, hpeer := range srv.peers { srv.toClient(hpeer, HOP_FLG_FIN|HOP_FLG_ACK, []byte{}, false) srv.toClient(hpeer, HOP_FLG_FIN|HOP_FLG_ACK, []byte{}, false) srv.toClient(hpeer, HOP_FLG_FIN, []byte{}, false) srv.toClient(hpeer, HOP_FLG_FIN, []byte{}, false) } clearMSS(srv.iface.Name(), true) os.Exit(0) }
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 }
// GC enters the pod by fork/exec()ing the stage1's /gc similar to /init. // /gc can expect to have its CWD set to the pod root. func GC(pdir string, uuid *types.UUID) error { err := unregisterPod(pdir, uuid) if err != nil { // Probably not worth abandoning the rest log.PrintE("warning: could not unregister pod with metadata service", err) } stage1Path := common.Stage1RootfsPath(pdir) ep, err := getStage1Entrypoint(pdir, gcEntrypoint) if err != nil { return errwrap.Wrap(errors.New("error determining 'gc' entrypoint"), err) } args := []string{filepath.Join(stage1Path, ep)} if debugEnabled { args = append(args, "--debug") } args = append(args, uuid.String()) c := exec.Cmd{ Path: args[0], Args: args, Stderr: os.Stderr, Dir: pdir, } return c.Run() }
func (h *Host) Run(command string) error { var cmd *exec.Cmd if runtime.GOOS == "windows" { cmd = exec.Command("cmd", "/c", command) } else { cmd = exec.Command("sh", "-c", command) } realWriter := &RealWriter{ NewLine: true, Prefix: "[" + h.Name + "]: ", } outWriter := &writer{ realWriter: realWriter, Type: 1, } errWriter := &writer{ realWriter: realWriter, Type: 2, } cmd.Stdout = outWriter cmd.Stderr = errWriter cmd.Stdin = os.Stdin err := cmd.Run() if err != nil { return err } return nil }
// runs dist bootrap to build the compilers for a target platform func distBootstrap(goRoot string, p Platform) (err error) { // the dist tool gets put in the pkg/tool/{host_platform} directory after we've built // the compilers/stdlib for the host platform hostPlatform := Platform{runtime.GOOS, runtime.GOARCH} scriptPath, err := filepath.Abs(filepath.Join(goRoot, "pkg", "tool", hostPlatform.String(), "dist")) if err != nil { return } // but we want to run it from the src directory scriptDir, err := filepath.Abs(filepath.Join(goRoot, "src")) if err != nil { return } bootstrapCmd := exec.Cmd{ Path: scriptPath, Args: []string{scriptPath, "bootstrap", "-v"}, Env: append(os.Environ(), "GOOS="+p.OS, "GOARCH="+p.Arch), Dir: scriptDir, Stdout: os.Stdout, Stderr: os.Stderr, } return bootstrapCmd.Run() }
func (a *AutoInstOptions) install() { sfx := "" if a.InstallSuffix != "" { sfx = a.InstallSuffix } osArchSfx := osArch + sfx if a.Env == nil { a.Env = map[string]string{} } roots := []string{} if p := a.Env["GOROOT"]; p != "" { roots = append(roots, filepath.Join(p, "pkg", osArchSfx)) } for _, p := range pathList(a.Env["GOPATH"]) { roots = append(roots, filepath.Join(p, "pkg", osArchSfx)) } if len(roots) == 0 { return } archiveOk := func(fn string) bool { for _, root := range roots { _, err := os.Stat(filepath.Join(root, fn)) if err == nil { return true } } return false } el := envSlice(a.Env) installed := []string{} for path, fn := range a.imports() { if !archiveOk(fn) { var cmd *exec.Cmd if sfx == "" { cmd = exec.Command("go", "install", path) } else { cmd = exec.Command("go", "install", "-installsuffix", sfx, path) } cmd.Env = el cmd.Stderr = ioutil.Discard cmd.Stdout = ioutil.Discard cmd.Run() if archiveOk(fn) { installed = append(installed, path) } } } if len(installed) > 0 { postMessage("auto-installed: %v", strings.Join(installed, ", ")) } }
func (cat *Catalog) pullCatalog() error { log.Debugf("Pulling the catalog %s from the repo to sync any new changes to %s", cat.CatalogID, cat.catalogRoot) // git --git-dir=./DATA/value/.git/ --work-tree=./DATA/value/ checkout new_branch gitCheckoutCmd := exec.Command("git", "--git-dir="+cat.catalogRoot+"/.git", "--work-tree="+cat.catalogRoot, "checkout", cat.URLBranch) out, gitCheckoutErr := gitCheckoutCmd.Output() if gitCheckoutErr != nil { errorStr := "Git checkout failure from git err: " + gitCheckoutErr.Error() log.Error(errorStr) } log.Debugf("Branch to be worked on : %s\n", out) var e *exec.Cmd e = exec.Command("git", "-C", cat.catalogRoot, "pull", "-r", "origin", cat.URLBranch) err := e.Run() if err != nil { log.Errorf("Failed to pull the catalog from git repo %s, error: %v", cat.URL, err.Error()) return err } log.Debugf("Update submodules of the catalog %s from the repo to sync any new changes to %s", cat.CatalogID, cat.catalogRoot) e = exec.Command("git", "-C", cat.catalogRoot, "submodule", "update", "--init", "--recursive") err = e.Run() if err != nil { log.Errorf("Failed to update submodules of the catalog from git repo %s, error: %v", cat.URL, err.Error()) return err } cat.LastUpdated = time.Now().Format(time.RFC3339) cat.State = "active" return nil }
// "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 }
// same as Run(), but the error value returned will contain the entire command line that failed func run(cmd *exec.Cmd) error { err := cmd.Run() if err != nil { return &commandLineError{*cmd, err} } return nil }
// 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 StopPgpool(w rest.ResponseWriter, r *rest.Request) { logit.Info.Println("StopPgpool called") response := StopPgpoolResponse{} req := StopPgpoolRequest{} err := r.DecodeJsonPayload(&req) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusInternalServerError) return } var cmd *exec.Cmd cmd = exec.Command("stop-pgpool.sh", req.Path) var out bytes.Buffer var stderr bytes.Buffer cmd.Stdout = &out cmd.Stderr = &stderr err = cmd.Run() if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), 400) return } response.Output = out.String() response.Status = "OK" w.WriteJson(&response) }
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 } }
// dividedOutput runs the command and returns its standard output and standard error. func dividedOutput(c *exec.Cmd) (stdout []byte, stderr []byte, err error) { var outb, errb bytes.Buffer c.Stdout = &outb c.Stderr = &errb err = c.Run() return outb.Bytes(), errb.Bytes(), 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 runCmdWithStdIo(cmd exec.Cmd) error { cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr return cmd.Run() }