Exemplo n.º 1
1
// Call in its own goroutine to rebuild docs when buildChan is sent events
func builder(path string, cmd []string, buildChan chan bool) {
	for {
		// Block waiting for a new event
		<-buildChan

		// Pause briefly as editors often emit multiple events at once
		time.Sleep(100 * time.Millisecond)

		// Now just throw away the newest build change event
		select {
		case <-buildChan:
		default:
		}

		// And finally actually build the thing
		var c *exec.Cmd
		if len(cmd) == 1 {
			c = exec.Command(cmd[0])
		} else {
			c = exec.Command(cmd[0], cmd[1:]...)
		}
		out, err := c.CombinedOutput()
		if err != nil {
			log.Fatalf("Error running `%v`: %v\n", cmd, err)
		}
		log.Printf("%v\n%s", cmd, out)
	}
}
Exemplo n.º 2
1
func execute(cmd *exec.Cmd) (string, error) {
	output, err := cmd.CombinedOutput()
	if err != nil {
		switch err.(type) {
		case *exec.ExitError:
			if len(output) > 0 {
				return string(output), fmt.Errorf(
					"executing %s failed: %s, output: %s",
					strings.Join(cmd.Args, " "), err, output,
				)
			}

			return string(output), fmt.Errorf(
				"executing %s failed: %s, output is empty",
				strings.Join(cmd.Args, " "), err,
			)
		default:
			return string(output), fmt.Errorf(
				"executing %s failed: %s",
				strings.Join(cmd.Args, " "), err,
			)
		}
	}

	return string(output), nil
}
Exemplo n.º 3
0
func runCommandWithOutput(cmd *exec.Cmd) (output string, exitCode int, err error) {
	exitCode = 0
	out, err := cmd.CombinedOutput()
	exitCode = processExitCode(err)
	output = string(out)
	return
}
Exemplo n.º 4
0
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
}
Exemplo n.º 5
0
func execute_python(pyStr string) ([]byte, error) {
	//Write python program to a file
	file, _ := os.Create("test.py")
	io.WriteString(file, pyStr)

	var out []byte
	var err error

	timeout := make(chan bool, 1)
	go func() {
		time.Sleep(3e9)
		timeout <- true
	}()

	ch := make(chan bool, 1)
	var cmd *exec.Cmd
	go func() {
		//Execute the program
		cmd = exec.Command("python", "test.py")
		out, err = cmd.CombinedOutput()
		ch <- true
	}()

	select {
	case <-ch:
		// Command finished in time.
		return out, err
	case <-timeout:
		// Stop forever loop command.
		cmd.Process.Kill()
		return []byte("人家被你玩坏了啦"), errors.New("人家被你玩坏了啦")
	}
}
Exemplo n.º 6
0
// DependencyTryCheckTool ...
func DependencyTryCheckTool(tool string) error {
	var cmd *exec.Cmd
	errMsg := ""

	switch tool {
	case "xcode":
		cmd = exec.Command("xcodebuild", "-version")
		errMsg = "The full Xcode app is not installed, required for this step. You can install it from the App Store."
		break
	default:
		cmdFields := strings.Fields(tool)
		if len(cmdFields) >= 2 {
			cmd = exec.Command(cmdFields[0], cmdFields[1:]...)
		} else if len(cmdFields) == 1 {
			cmd = exec.Command(cmdFields[0])
		} else {
			return fmt.Errorf("Invalid tool name (%s)", tool)
		}
	}

	outBytes, err := cmd.CombinedOutput()
	if err != nil {
		if errMsg != "" {
			return errors.New(errMsg)
		}
		log.Infof("Output was: %s", outBytes)
		return fmt.Errorf("Dependency check failed for: %s", tool)
	}

	return nil
}
Exemplo n.º 7
0
func (c Command) Run(s HookState) error {
	b, err := json.Marshal(s)
	if err != nil {
		return err
	}
	cmd := exec.Cmd{
		Path:  c.Path,
		Args:  c.Args,
		Env:   c.Env,
		Stdin: bytes.NewReader(b),
	}
	errC := make(chan error, 1)
	go func() {
		out, err := cmd.CombinedOutput()
		if err != nil {
			err = fmt.Errorf("%s: %s", err, out)
		}
		errC <- err
	}()
	if c.Timeout != nil {
		select {
		case err := <-errC:
			return err
		case <-time.After(*c.Timeout):
			cmd.Process.Kill()
			cmd.Wait()
			return fmt.Errorf("hook ran past specified timeout of %.1fs", c.Timeout.Seconds())
		}
	}
	return <-errC
}
Exemplo n.º 8
0
func cleanup(directory string) {
	temp, err := ioutil.TempDir("", "")
	isError(err, "")
	files, err := ioutil.ReadDir(directory)
	isError(err, "")
	if 1 == len(files) {
		folder := filepath.Join(directory, files[0].Name())
		// Move to a tmp directory
		files, err = ioutil.ReadDir(folder)
		isError(err, "")
		for _, file := range files {
			var cmd *exec.Cmd
			cmd = exec.Command("mv", file.Name(), temp)
			cmd.Dir = folder
			output, err := cmd.CombinedOutput()
			isError(err, string(output))
		}
		err = os.RemoveAll(folder)
		isError(err, "")
		// move to the directory
		files, err = ioutil.ReadDir(temp)
		isError(err, "")
		for _, file := range files {
			var cmd *exec.Cmd
			cmd = exec.Command("mv", file.Name(), directory)
			cmd.Dir = temp
			output, err := cmd.CombinedOutput()
			isError(err, string(output))
		}
	}
}
Exemplo n.º 9
0
func check_ibgp(version int) {
	var cmd *exec.Cmd
	if version == 4 {
		cmd = exec.Command(BIRDC, "show protocols")
	} else if version == 6 {
		cmd = exec.Command(BIRDC6, "show protocols")
	} else {
		return
	}
	output, err := cmd.CombinedOutput()
	check(err)

	lines := strings.Split(string(output), "\n")
	for i := 0; i < len(lines); i++ {
		if i < 2 {
			continue
		}

		matched, err := regexp.MatchString("^bb_[ab]", lines[i])
		check(err)
		if !matched {
			continue
		}

		columns := regexp.MustCompile(" +").Split(string(lines[i]), -1)
		if columns[BIRD_PROTOCOL_STATUS_COLUMN] != "Established" {
			fmt.Printf("IPv%d IBGP session %s is in status %s\n", version,
				columns[BIRD_PROTOCOL_NAME_COLUMN],
				columns[BIRD_PROTOCOL_STATUS_COLUMN])
		}
	}
}
Exemplo n.º 10
0
func run(cmd *exec.Cmd) (string, error) {
	data, err := cmd.CombinedOutput()
	if err != nil {
		return "", fmt.Errorf("%s", data)
	}
	return string(data), err
}
Exemplo n.º 11
0
func (c cmdAction) Run() StepOp {
	start := time.Now()

	var cmd *exec.Cmd
	command := evaluate(c.command, c.event)
	args := strings.Fields(command)
	if len(args) > 1 {
		cmd = exec.Command(args[0], args[1:]...)
	} else {
		cmd = exec.Command(args[0])
	}

	out, err := cmd.CombinedOutput()
	elapsed := time.Now().Sub(start)
	if err != nil {
		log.WithFields(log.Fields{
			"error":   err,
			"elapsed": elapsed,
		}).Error(highlight(fmt.Sprintf("Run: %s", command), "red+b"))
	} else {
		log.WithFields(log.Fields{
			"elapsed": time.Now().Sub(start),
		}).Info(highlight(fmt.Sprintf("Run: %s", command), "cyan+b"))
	}
	if len(out) > 0 {
		fmt.Print(string(out))
	}

	if err != nil {
		return Halt
	}
	return Continue
}
Exemplo n.º 12
0
func Md5sumCheck(runUser, workdir, tarfile, md5file string) error {
	var cmd *exec.Cmd
	var md5Actual string
	if "darwin" == runtime.GOOS {
		cmd = BuildCommand(runUser, "md5", "-q", path.Join(workdir, tarfile))
	} else {
		cmd = BuildCommand(runUser, "md5sum", path.Join(workdir, tarfile))
	}
	cmd.Dir = file.SelfDir()
	bs, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("cd %s; md5sum -c %s fail", workdir, md5file)
	}
	strMd5file, _ := file.ToString(path.Join(workdir, md5file))
	if "" == strMd5file {
		return fmt.Errorf("md5file is empty")
	}

	if "darwin" == runtime.GOOS {
		md5Actual = strings.Replace(string(bs), "\n", "", -1)
	} else {
		md5Actual = strings.Fields(string(bs))[0]
	}

	md5Except := strings.Fields(strMd5file)[0]

	if md5Actual == md5Except {
		return nil
	}
	return fmt.Errorf("md5Actual:%s, md5Except:%s<<<===end", md5Actual, md5Except)
}
Exemplo n.º 13
0
func RunCmd(command string) (output string, exitCode int, startedAt time.Time, finishedAt time.Time) {

	var cmd *exec.Cmd

	if runtime.GOOS == "windows" {
		log.Infof("Command: %s", command)
		cmd = exec.Command("cmd", "/C", command)
	} else {
		log.Infof("Command: %s %s", "/bin/sh -c", command)
		cmd = exec.Command("/bin/sh", "-c", command)
	}

	startedAt = time.Now()
	bytes, err := cmd.CombinedOutput()
	finishedAt = time.Now()
	output = strings.TrimSpace(string(bytes))
	exitCode = extractExitCode(err)

	log.Debugf("Starting Time: %s", startedAt.Format(TimeStampLayout))
	log.Debugf("End Time: %s", finishedAt.Format(TimeStampLayout))
	log.Debugf("Output")
	log.Debugf("")
	log.Debugf("%s", output)
	log.Debugf("")
	log.Infof("Exit Code: %d", exitCode)
	return
}
Exemplo n.º 14
0
func execCommand(_result map[string]int, _cmd []string) {
	var r ResultSlice

	for k, v := range _result {
		r.Results = append(r.Results, Result{Host: k, Count: v})
	}

	b, err := json.Marshal(r)
	HandleError(err)

	var cmd *exec.Cmd
	if len(_cmd) == 0 {
		cmd = exec.Command(_cmd[0])
	} else {
		cmd = exec.Command(_cmd[0], _cmd[1:]...)
	}

	stdin, err := cmd.StdinPipe()
	HandleError(err)

	io.WriteString(stdin, string(b))

	stdin.Close()

	out, err := cmd.CombinedOutput()
	HandleError(err)

	fmt.Println(string(out))
}
Exemplo n.º 15
0
func (me *App) execCmd(cmd *exec.Cmd) (string, error) {
	out, err := cmd.CombinedOutput()

	args := strings.Join(cmd.Args, " ")

	output := strings.Trim(string(out), "\n ")

	if output != "" {
		output = fmt.Sprintf("\n\n%s", output)
	}

	str := fmt.Sprintf(
		"$ %v%s\n\n",
		args,
		output,
	)

	fmt.Print(str)
	log.Print(str)

	if err != nil {
		log.Printf("Command %s returned error: %s", args, err)
	}

	return string(out), err
}
Exemplo n.º 16
0
Arquivo: builder.go Projeto: leyra/gin
func (b *builder) Build() error {
	var command *exec.Cmd

	if b.customBuild != "" {
		parts := strings.Split(b.customBuild, " ")
		args := []string{}
		for k, v := range parts {
			if k > 0 {
				args = append(args, v)
			}
		}
		command = exec.Command(parts[0], args...)
	} else 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 command.ProcessState.Success() {
		b.errors = ""
	} else {
		b.errors = string(output)
	}

	if len(b.errors) > 0 {
		return fmt.Errorf(b.errors)
	}

	return err
}
Exemplo n.º 17
0
func runCmdOptional(cmd *exec.Cmd, n string) string {
	var out, err = cmd.CombinedOutput()
	if err != nil {
		fmt.Printf("\n\n%v\noutput:%s\n\n", n, out)
	}
	return string(out)
}
Exemplo n.º 18
0
func updateLocalRepo(url, dir string) (bool, error) {
	var cmd *exec.Cmd

	_, err := os.Stat(dir)
	if os.IsNotExist(err) {
		cmd = exec.Command("git", "clone", url, dir)
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		return true, cmd.Run()
	} else {
		cmd = exec.Command("git", "pull", url)
		cmd.Dir = dir

		out, err := cmd.CombinedOutput()
		if err != nil {
			return false, err
		}

		res := string(out)
		fmt.Fprint(os.Stderr, res)

		updated := true
		if strings.Contains(res, "Already up-to-date.") {
			updated = false
		}

		return updated, nil
	}
}
Exemplo n.º 19
0
// Connect to an access point
// only certain versions of NetworkManager support this...
func (self NetworkManager) Connect(interfaceName string, ssid string,
	secProtocol string, secKey string) error {
	logger.Debug("NetworkManager: Connecting to an access point")

	result, errp := self.ProfileExistsById(interfaceName)
	if result == true && errp == nil {
		self.DeleteById(interfaceName)
	}

	var cmd *exec.Cmd
	if secProtocol == "none" {
		cmd = exec.Command("nmcli", "dev", "wifi", "con", ssid,
			"name", self.NetworkManagerID(interfaceName),
			"iface", interfaceName)
	} else {
		cmd = exec.Command("nmcli", "dev", "wifi", "con", ssid,
			"name", self.NetworkManagerID(interfaceName),
			"password", secKey, "iface", interfaceName)
	}
	logger.Debug("Command Start: %v", cmd.Args)
	out, err := cmd.CombinedOutput()
	if err != nil {
		logger.Error("Command Error: %v : %v", err, limitText(out))
		return err
	}
	logger.Debug("Command Return: %v", limitText(out))

	return nil
}
Exemplo n.º 20
0
func runCmdWithDetailedError(cmd *exec.Cmd) error {
	out, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf(string(out), err)
	}
	return nil
}
func (me CommandExecuter) Execute(cmd *exec.Cmd, body []byte) bool {
	me.infLogger.Println("Processing message...")
	me.infLogger.Printf("Cmd: %s  params: %s \n", cmd.Path, cmd.Args)
	out, err := cmd.CombinedOutput()

	//log output php script to info
	me.infLogger.Printf("Output php: %s\n", string(out[:]))

	if err != nil {
		me.infLogger.Println("Failed. Check error log for details.")
		me.errLogger.Printf("Failed: %s\n", string(out[:]))
		me.errLogger.Printf("Error: %s\n", err)

		if len(Cconf.Logs.Rpc) > 1 {
			me.infLogger.Printf("rpc parameters: %s", Cconf.Logs.Rpc)
			if err := me.netLogger.Send(out[:], body[:], true); err != nil {
				me.infLogger.Printf("failed sending provision error event -> error: %s", err)
			}
		}

		return false
	}

	me.infLogger.Println("Processed!")

	if len(Cconf.Logs.Rpc) > 1 {
		if err := me.netLogger.Send(out[:], body[:], false); err != nil {
			me.infLogger.Printf("failed sending provision success event -> error: %s", err)
		}
	}

	return true
}
Exemplo n.º 22
0
func run(cmd *exec.Cmd) error {
	if out, err := cmd.CombinedOutput(); err != nil {
		return fmt.Errorf("%s: %s: %s", cmd.Path, err, string(out))
	}

	return nil
}
Exemplo n.º 23
0
func runCommand(cmd *exec.Cmd) {
	stdout, err := cmd.CombinedOutput()
	if err != nil {
		log.Fatal(err.Error())
	}
	log.Printf("%s\n", string(stdout))
}
Exemplo n.º 24
0
func ExecuteCommandWithOutput(cmd *exec.Cmd) (string, error) {
	bs, err := cmd.CombinedOutput()
	if nil != err && strings.Contains(err.Error(), "exit status") {
		return "", fmt.Errorf(string(bs))
	}
	return string(bs), err
}
Exemplo n.º 25
0
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)
		}
	}
}
Exemplo n.º 26
0
func execute(path string, vcs string, vcs_verb string) {
	if vcs_verb == "" {
		return
	}
	a := func(wd string, vcs string, vcs_verb string, seq bool) {
		msg := "=== @{!" + vcs_color[vcs] + "} "
		msg += filepath.Base(path)
		msg += "@| (@!" + vcs + "@|) ==="
		var cmd exec.Cmd
		cmd.Dir = wd
		cmd.Args = strings.Split(vcs_verb, " ")
		path, err := exec.LookPath(cmd.Args[0])
		if err != nil {
			path = cmd.Args[0]
		}
		cmd.Path = path
		out, err := cmd.CombinedOutput()
		if err != nil {
			br := color.Colorize("!r")
			rst := color.Colorize("|")
			fmt.Printf(color.Sprint(msg)+"\n%s\n%s%s%s\n\n", out, br, err, rst)
		} else {
			fmt.Printf(color.Sprint(msg)+"\n%s\n", out)
		}
		if !seq {
			quit <- 0
		}
	}
	if *sequential {
		a(path, vcs, vcs_verb, *sequential)
	} else {
		count += 1
		go a(path, vcs, vcs_verb, *sequential)
	}
}
Exemplo n.º 27
0
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
}
Exemplo n.º 28
0
// compile compiles a generator tool using the user design package and the
// target generator code.
// It returns the name of the compiled tool on success
// (located under $GOPATH/bin), an error otherwise.
func (m *Generator) compile(srcDir string) (string, error) {
	gobin, err := exec.LookPath("go")
	if err != nil {
		return "", fmt.Errorf(`failed to find a go compiler, looked in "%s"`, os.Getenv("PATH"))
	}
	bin := "goagen"
	if runtime.GOOS == "windows" {
		bin += ".exe"
	}
	c := exec.Cmd{
		Path: gobin,
		Args: []string{gobin, "build", "-o", bin},
		Dir:  srcDir,
	}
	out, err := c.CombinedOutput()
	if codegen.Debug {
		fmt.Printf("[%s]$ %s build -o %s\n%s\n", srcDir, gobin, bin, out)
	}
	if err != nil {
		if len(out) > 0 {
			return "", fmt.Errorf(string(out))
		}
		return "", fmt.Errorf("failed to compile goagen: %s", err)
	}
	return filepath.Join(srcDir, "goagen"), nil
}
Exemplo n.º 29
0
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))
	}
}
Exemplo n.º 30
0
func main() {
	flag.Parse()

	stage1initcommon.InitDebug(debug)

	log, diag, _ = rktlog.NewLogSet("app-start", debug)
	if !debug {
		diag.SetOutput(ioutil.Discard)
	}

	appName, err := types.NewACName(flagApp)
	if err != nil {
		log.FatalE("invalid app name", err)
	}

	enterCmd := stage1common.PrepareEnterCmd(false)

	args := enterCmd
	args = append(args, "/usr/bin/systemctl")
	args = append(args, "start")
	args = append(args, appName.String())

	cmd := exec.Cmd{
		Path: args[0],
		Args: args,
	}

	if out, err := cmd.CombinedOutput(); err != nil {
		log.Fatalf("%q failed to start:\n%s", appName, out)
	}

	os.Exit(0)
}