Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

main: cancel commands on sigint/sigterm #9

Merged
merged 2 commits into from
Jun 25, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
}