func StartDesiredVersion(binDir string, args []string) { fs, err := parseConfig(args) if err != nil { return } ver := checkInternalVersion(fs) fmt.Printf("etcd-starter: starting etcd version %s\n", ver) var p string switch ver { case internalV1: p = path.Join(binDir, "1", "etcd") case internalV2: p = path.Join(binDir, "2", "etcd") case internalV2Proxy: p = path.Join(binDir, "2", "etcd") if _, err := os.Stat(standbyInfo4(fs.Lookup("data-dir").Value.String())); err != nil { fmt.Printf("etcd-starter: detected standby_info file. Adding --proxy=on flag to ensure node runs in v2.0 proxy mode.\n") fmt.Printf("etcd-starter: before removing v0.4 data, --proxy=on flag MUST be added.\n") } // append proxy flag to args to trigger proxy mode args = append(args, "-proxy=on") default: log.Panicf("etcd-starter: unhandled start version") } fmt.Printf("etcd-starter: starting with %s %v with env %v\n", p, args, syscall.Environ()) err = syscall.Exec(p, append([]string{p}, args...), syscall.Environ()) if err != nil { log.Fatalf("etcd-starter: failed to execute %s: %v", p, err) } }
func execIfAliases(config *lxd.Config, origArgs []string) { newArgs := []string{} expandedAlias := false for _, arg := range origArgs { changed := false for k, v := range config.Aliases { if k == arg { expandedAlias = true changed = true newArgs = append(newArgs, strings.Split(v, " ")...) break } } if !changed { newArgs = append(newArgs, arg) } } if expandedAlias { path, err := exec.LookPath(origArgs[0]) if err != nil { fmt.Fprintf(os.Stderr, i18n.G("processing aliases failed %s\n"), err) os.Exit(5) } ret := syscall.Exec(path, newArgs, syscall.Environ()) fmt.Fprintf(os.Stderr, i18n.G("processing aliases failed %s\n"), ret) os.Exit(5) } }
func startInternalV1() { p := os.Getenv("ETCD_BINARY_DIR") if p == "" { p = defaultInternalV1etcdBinaryDir } p = path.Join(p, "1") err := syscall.Exec(p, os.Args, syscall.Environ()) if err != nil { log.Fatalf("starter: failed to execute internal v1 etcd: %v", err) } }
func doLook(c *cli.Context) { name := c.Args().First() if name == "" { cli.ShowCommandHelp(c, "look") os.Exit(1) } reposFound := []*LocalRepository{} walkLocalRepositories(func(repo *LocalRepository) { if repo.Matches(name) { reposFound = append(reposFound, repo) } }) switch len(reposFound) { case 0: utils.Log("error", "No repository found") os.Exit(1) case 1: if runtime.GOOS == "windows" { cmd := exec.Command(os.Getenv("COMSPEC")) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Dir = reposFound[0].FullPath err := cmd.Start() if err == nil { cmd.Wait() os.Exit(0) } } else { shell := os.Getenv("SHELL") if shell == "" { shell = "/bin/sh" } utils.Log("cd", reposFound[0].FullPath) err := os.Chdir(reposFound[0].FullPath) utils.PanicIf(err) syscall.Exec(shell, []string{shell}, syscall.Environ()) } default: utils.Log("error", "More than one repositories are found; Try more precise name") for _, repo := range reposFound { utils.Log("error", "- "+strings.Join(repo.PathParts, "/")) } } }
func Do() { for { argv0 := os.Args[0] closeFD() err := syscall.Exec(argv0, os.Args, syscall.Environ()) if err != nil { log.Printf("restart error: %s: %v", argv0, err) time.Sleep(1 * time.Second) continue } log.Panicf("unreachable") } }
func execIfAliases(config *lxd.Config, origArgs []string) { newArgs, expanded := expandAlias(config, origArgs) if !expanded { return } path, err := exec.LookPath(origArgs[0]) if err != nil { fmt.Fprintf(os.Stderr, i18n.G("processing aliases failed %s\n"), err) os.Exit(5) } ret := syscall.Exec(path, newArgs, syscall.Environ()) fmt.Fprintf(os.Stderr, i18n.G("processing aliases failed %s\n"), ret) os.Exit(5) }
func DoSshToDroplet(route *Route) { droplet := FindDropletByName(Client, route.Params["droplet_name"]) fmt.Printf("DoSshToDroplet: %s\n", droplet) if droplet == nil { fmt.Fprintf(os.Stderr, "Droplet name not found\n") os.Exit(1) } err := syscall.Exec("/usr/bin/ssh", []string{"ssh", "root@" + droplet.Ip_address}, syscall.Environ()) if err != nil { fmt.Fprintf(os.Stderr, "Error executing ssh cmd: %s\n", err) os.Exit(1) } }
// Env returns the current OS environment for this running process. func Env() map[string]string { vals := syscall.Environ() e := make(map[string]string, len(vals)) for _, i := range vals { // this is not particularly speedy. Good enough for a first try parts := strings.SplitN(i, "=", 2) k := parts[0] // There can be multiple values for an environment variable (see stdlib syscall source) // so just call Getenv on each. We could optimize and do the "magic" here, but // there is little performance gane to be had for potentially buggy code. if v, ok := syscall.Getenv(k); ok { e[k] = v } } return e }
func main() { argsIndex := 1 // 0 is the name of this program, 1 is either the one to launch or the "wait" option if len(os.Args) < 2 { log.Fatal("ERROR: no arguments. Use [-wait] programname [arg arg arg]\n") } // Do this awkward thing so we can pass along the rest of the command line as-is doWait := false doHide := true for i := 1; i < 3 && (i+1) < len(os.Args); i++ { if strings.EqualFold(os.Args[argsIndex], "-wait") { argsIndex++ doWait = true } else if strings.EqualFold(os.Args[argsIndex], "-show") { argsIndex++ doHide = false } } attr := &syscall.ProcAttr{ Files: []uintptr{uintptr(syscall.Stdin), uintptr(syscall.Stdout), uintptr(syscall.Stderr)}, Env: syscall.Environ(), Sys: &syscall.SysProcAttr{ HideWindow: doHide, CreationFlags: flagCreateNewConsole, }, } fmt.Printf("Launching %s with args %v\n", os.Args[argsIndex], os.Args[argsIndex:]) pid, handle, err := syscall.StartProcess(os.Args[argsIndex], os.Args[argsIndex:], attr) fmt.Printf("%v, %v, %v\n", pid, handle, err) if doWait { p, err := os.FindProcess(pid) if err != nil { fmt.Printf("Launcher can't find %d\n", pid) } pstate, err := p.Wait() if err == nil && pstate.Success() { time.Sleep(100 * time.Millisecond) } else { fmt.Printf("Unsuccessful wait: Error %v, pstate %v\n", err, *pstate) } } }
func gotoPlayground(dirPath, filePath string) error { shell, err := exec.LookPath(getenv("SHELL", "/bin/sh")) if err != nil { return err } if err := os.Chdir(dirPath); err != nil { return err } fmt.Fprintf(os.Stderr, "\tcd %s\n", dirPath) var argv []string if config.Edit { editor, err := getEditorCommand() if err != nil { return err } fmt.Fprintf(os.Stderr, "\t%s %s\n", editor, filePath) argv = []string{ shell, "-c", fmt.Sprintf("%s %s; exec %s", editor, filePath, shell), } } else { argv = []string{shell} } libs, err := filepath.Abs(filepath.Join(dirPath, "golibs")) if err != nil { return err } if err := os.Setenv("GOPATH", libs+":"+os.Getenv("GOPATH")); err != nil { return err } return syscall.Exec(shell, argv, syscall.Environ()) }
func startProcess(name string, argv []string, attr *ProcAttr) (p *Process, err error) { // If there is no SysProcAttr (ie. no Chroot or changed // UID/GID), double-check existence of the directory we want // to chdir into. We can make the error clearer this way. if attr.Dir != "" && attr.Chroot == "" { if _, err := os.Stat(attr.Dir); err != nil { pe := err.(*os.PathError) pe.Op = "chdir" return nil, pe } } if attr.Env == nil { attr.Env = syscall.Environ() } pid, e := forkExec(name, argv, attr) if e != nil { return nil, &os.PathError{"fork/exec", name, e} } return newProcess(pid), nil }
func doLook(c *cli.Context) { name := c.Args().First() if name == "" { cli.ShowCommandHelp(c, "look") os.Exit(1) } reposFound := []*LocalRepository{} walkLocalRepositories(func(repo *LocalRepository) { if repo.Matches(name) { reposFound = append(reposFound, repo) } }) switch len(reposFound) { case 0: utils.Log("error", "No repository found") case 1: shell := os.Getenv("SHELL") if shell == "" { shell = "/bin/sh" } utils.Log("cd", reposFound[0].FullPath) err := os.Chdir(reposFound[0].FullPath) utils.PanicIf(err) syscall.Exec(shell, []string{shell}, syscall.Environ()) default: utils.Log("error", "More than one repositories are found; Try more precise name") for _, repo := range reposFound { utils.Log("error", "- "+strings.Join(repo.PathParts, "/")) } } }
// Environ returns a copy of strings representing the environment, // in the form "key=value". func Environ() []string { return syscall.Environ() }
// Environ returns a copy of strings representing the environment, // in the form "key=value". func Environ() []string { // 返回所有环境变量的一份拷贝 return syscall.Environ() }
func (req *request) exec() { conf := req.cmdConf cmd := exec.Command(conf.Cmd, req.cmdArgs...) //when use cache,disable the env params env := syscall.Environ() if conf.CacheLife < 3 { for k, v := range req.cmdEnv { env = append(env, k+"="+v) } } cmd.Env = env var out bytes.Buffer cmd.Stdout = &out var outErr bytes.Buffer cmd.Stderr = &outErr err := cmd.Start() if err != nil { req.log("error:" + err.Error()) req.writer.WriteHeader(500) fmt.Fprintf(req.writer, err.Error()+"\n") for argI, argV := range req.cmdArgs { fmt.Fprintf(req.writer, "arg_%d:%s\n", argI, argV) } return } done := make(chan error) go func() { done <- cmd.Wait() }() cc := req.writer.(http.CloseNotifier).CloseNotify() isResonseOk := true killCmd := func(msg string) { if err := cmd.Process.Kill(); err != nil { log.Println("failed to kill: ", err) } req.log("killed:" + msg) // log.Println(logStr) isResonseOk = false } select { case <-cc: killCmd("client close") case <-time.After(time.Duration(conf.Timeout) * time.Second): killCmd("timeout") // w.WriteHeader(); case <-done: } if isResonseOk { cmdStatus := cmd.ProcessState.Sys().(syscall.WaitStatus) exitStatus := fmt.Sprintf(" [status:%d]", cmdStatus.ExitStatus()) req.log(exitStatus) } if !isResonseOk || !cmd.ProcessState.Success() { req.writer.WriteHeader(500) req.writer.Write([]byte("<h1>Error 500</h1><pre>")) req.writer.Write([]byte(strings.Join(req.logInfo, " "))) req.writer.Write([]byte("\n\nStdOut:\n")) req.writer.Write(out.Bytes()) req.writer.Write([]byte("\nErrOut:\n")) req.writer.Write(outErr.Bytes()) req.writer.Write([]byte("</pre>")) return } if out.Len() > 0 && conf.CacheLife > 3 { req.cmd2.Cache.Set(req.cacheKey, out.Bytes(), conf.CacheLife) } req.sendResponse(out.String()) }