2014-08-05 16:32:24 +00:00
|
|
|
package signal
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
gosignal "os/signal"
|
|
|
|
"sync/atomic"
|
|
|
|
"syscall"
|
2014-09-25 16:55:53 +00:00
|
|
|
|
2014-10-24 17:12:35 +00:00
|
|
|
log "github.com/Sirupsen/logrus"
|
2014-08-05 16:32:24 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Trap sets up a simplified signal "trap", appropriate for common
|
|
|
|
// behavior expected from a vanilla unix command-line tool in general
|
|
|
|
// (and the Docker engine in particular).
|
|
|
|
//
|
|
|
|
// * If SIGINT or SIGTERM are received, `cleanup` is called, then the process is terminated.
|
|
|
|
// * If SIGINT or SIGTERM are repeated 3 times before cleanup is complete, then cleanup is
|
|
|
|
// skipped and the process terminated directly.
|
|
|
|
// * If "DEBUG" is set in the environment, SIGQUIT causes an exit without cleanup.
|
|
|
|
//
|
|
|
|
func Trap(cleanup func()) {
|
|
|
|
c := make(chan os.Signal, 1)
|
|
|
|
signals := []os.Signal{os.Interrupt, syscall.SIGTERM}
|
|
|
|
if os.Getenv("DEBUG") == "" {
|
|
|
|
signals = append(signals, syscall.SIGQUIT)
|
|
|
|
}
|
|
|
|
gosignal.Notify(c, signals...)
|
|
|
|
go func() {
|
|
|
|
interruptCount := uint32(0)
|
|
|
|
for sig := range c {
|
|
|
|
go func(sig os.Signal) {
|
2014-09-25 16:55:53 +00:00
|
|
|
log.Infof("Received signal '%v', starting shutdown of docker...", sig)
|
2014-08-05 16:32:24 +00:00
|
|
|
switch sig {
|
|
|
|
case os.Interrupt, syscall.SIGTERM:
|
|
|
|
// If the user really wants to interrupt, let him do so.
|
|
|
|
if atomic.LoadUint32(&interruptCount) < 3 {
|
|
|
|
// Initiate the cleanup only once
|
2014-12-06 14:42:32 +00:00
|
|
|
if atomic.AddUint32(&interruptCount, 1) == 1 {
|
2014-08-05 16:32:24 +00:00
|
|
|
// Call cleanup handler
|
|
|
|
cleanup()
|
2014-08-13 19:18:23 +00:00
|
|
|
os.Exit(0)
|
2014-08-05 16:32:24 +00:00
|
|
|
} else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
} else {
|
2014-09-25 16:55:53 +00:00
|
|
|
log.Infof("Force shutdown of docker, interrupting cleanup")
|
2014-08-05 16:32:24 +00:00
|
|
|
}
|
|
|
|
case syscall.SIGQUIT:
|
|
|
|
}
|
|
|
|
os.Exit(128 + int(sig.(syscall.Signal)))
|
|
|
|
}(sig)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|