2015-02-14 16:34:31 +00:00
|
|
|
package respawn
|
|
|
|
|
|
|
|
import (
|
2015-02-20 03:05:43 +00:00
|
|
|
"io"
|
2015-02-14 16:34:31 +00:00
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
log "github.com/Sirupsen/logrus"
|
2015-02-20 03:05:43 +00:00
|
|
|
"github.com/codegangsta/cli"
|
2015-02-14 16:34:31 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func Main() {
|
2015-02-20 03:05:43 +00:00
|
|
|
app := cli.NewApp()
|
|
|
|
|
|
|
|
app.Flags = []cli.Flag{
|
|
|
|
cli.StringFlag{
|
|
|
|
Name: "file, f",
|
|
|
|
Usage: "Optional config file to load",
|
|
|
|
},
|
|
|
|
}
|
|
|
|
app.Action = run
|
|
|
|
|
|
|
|
app.Run(os.Args)
|
|
|
|
}
|
|
|
|
|
|
|
|
func run(c *cli.Context) {
|
|
|
|
var stream io.Reader = os.Stdin
|
|
|
|
var err error
|
|
|
|
|
|
|
|
inputFileName := c.String("file")
|
|
|
|
|
|
|
|
if inputFileName != "" {
|
|
|
|
stream, err = os.Open(inputFileName)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
input, err := ioutil.ReadAll(stream)
|
2015-02-14 16:34:31 +00:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
var wait sync.WaitGroup
|
|
|
|
|
|
|
|
for _, line := range strings.Split(string(input), "\n") {
|
2015-02-23 03:56:37 +00:00
|
|
|
if strings.TrimSpace(line) == "" {
|
|
|
|
continue
|
|
|
|
}
|
2015-02-14 16:34:31 +00:00
|
|
|
wait.Add(1)
|
|
|
|
go execute(line, wait)
|
|
|
|
}
|
|
|
|
|
|
|
|
wait.Wait()
|
|
|
|
}
|
|
|
|
|
|
|
|
func execute(line string, wait sync.WaitGroup) {
|
|
|
|
start := time.Now()
|
|
|
|
count := 0
|
|
|
|
|
|
|
|
for {
|
|
|
|
args := strings.Split(line, " ")
|
|
|
|
|
2015-02-23 03:56:37 +00:00
|
|
|
cmd := exec.Command("setsid", args...)
|
2015-02-14 16:34:31 +00:00
|
|
|
|
|
|
|
err := cmd.Start()
|
|
|
|
if err != nil {
|
|
|
|
log.Error("%s : %v", line, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
err = cmd.Wait()
|
|
|
|
if err != nil {
|
|
|
|
log.Error("%s : %v", line, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
count++
|
|
|
|
|
|
|
|
if count > 10 {
|
|
|
|
if start.Sub(time.Now()) <= (1 * time.Second) {
|
|
|
|
log.Errorf("%s : restarted too fast, not executing", line)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
count = 0
|
|
|
|
start = time.Now()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
wait.Done()
|
|
|
|
}
|