Skip to content

Commit

Permalink
Merge pull request #9 from therealplato/handle-interrupt
Browse files Browse the repository at this point in the history
main: cancel commands on sigint/sigterm
  • Loading branch information
Mariano Gappa authored Jun 25, 2017
2 parents 23f2b97 + fb772b0 commit e171319
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@ package main

import (
"bufio"
"context"
"flag"
"fmt"
"io"
"log"
"os"
"os/exec"
"os/signal"
"strings"
"sync"
"syscall"
)

type database struct {
Expand Down Expand Up @@ -61,14 +64,17 @@ func main() {
out := make(chan string)
go println(out)

quitContext, cancel := context.WithCancel(context.Background())
go awaitSignal(cancel)

var wg sync.WaitGroup
wg.Add(len(targetDatabases))

returnCode := 0
for _, k := range targetDatabases {
go func(db database, k string) {
defer wg.Done()
if r := runSQL(db, sql, k, len(targetDatabases) > 1, out); !r {
if r := runSQL(quitContext, db, sql, k, len(targetDatabases) > 1, out); !r {
returnCode = 1
}
}(databases[k], k)
Expand All @@ -78,7 +84,7 @@ func main() {
os.Exit(returnCode)
}

func runSQL(db database, sql string, key string, prependKey bool, out chan string) bool {
func runSQL(quitContext context.Context, db database, sql string, key string, prependKey bool, out chan string) bool {
userOption := ""
if db.User != "" {
userOption = fmt.Sprintf("-u %v ", db.User)
Expand All @@ -105,10 +111,10 @@ func runSQL(db database, sql string, key string, prependKey bool, out chan strin
var cmd *exec.Cmd
if db.AppServer != "" {
query := fmt.Sprintf(`'%v'`, strings.Replace(sql, `'`, `'"'"'`, -1))
cmd = exec.Command("ssh", db.AppServer, mysql+options+query)
cmd = exec.CommandContext(quitContext, "ssh", db.AppServer, mysql+options+query)
} else {
args := append(trimEmpty(strings.Split(options, " ")), sql)
cmd = exec.Command("mysql", args...)
cmd = exec.CommandContext(quitContext, "mysql", args...)
}

stdout, err := cmd.StdoutPipe()
Expand Down Expand Up @@ -187,3 +193,10 @@ func trimEmpty(s []string) []string {
}
return r
}

func awaitSignal(cancel context.CancelFunc) {
signals := make(chan os.Signal)
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
<-signals
cancel()
}

0 comments on commit e171319

Please sign in to comment.