seaweedfs/weed/util/grace/signal_handling.go

74 lines
1.4 KiB
Go
Raw Normal View History

2021-09-01 09:45:42 +00:00
//go:build !plan9
2014-05-13 22:04:04 +00:00
// +build !plan9
package grace
2014-05-13 22:04:04 +00:00
import (
"github.com/seaweedfs/seaweedfs/weed/glog"
2014-05-13 22:04:04 +00:00
"os"
"os/signal"
"reflect"
"runtime"
"sync"
2014-05-13 22:04:04 +00:00
"syscall"
)
var signalChan chan os.Signal
var interruptHooks = make([]func(), 0)
var interruptHookLock sync.RWMutex
var reloadHooks = make([]func(), 0)
var reloadHookLock sync.RWMutex
func GetFunctionName(i interface{}) string {
return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
}
func init() {
signalChan = make(chan os.Signal, 1)
2014-05-13 22:04:04 +00:00
signal.Notify(signalChan,
os.Interrupt,
os.Kill,
2014-05-14 02:26:05 +00:00
syscall.SIGALRM,
syscall.SIGHUP,
2014-05-13 22:04:04 +00:00
syscall.SIGINT,
syscall.SIGTERM,
// syscall.SIGQUIT,
)
2014-05-13 22:04:04 +00:00
go func() {
for s := range signalChan {
if s.String() == syscall.SIGHUP.String() {
reloadHookLock.RLock()
for _, hook := range reloadHooks {
hook()
}
reloadHookLock.RUnlock()
} else {
interruptHookLock.RLock()
for _, hook := range interruptHooks {
glog.V(4).Infof("exec interrupt hook func name:%s", GetFunctionName(hook))
hook()
}
interruptHookLock.RUnlock()
os.Exit(0)
}
2014-05-13 22:04:04 +00:00
}
}()
}
func OnReload(fn func()) {
// prevent reentry
reloadHookLock.Lock()
defer reloadHookLock.Unlock()
reloadHooks = append(reloadHooks, fn)
}
func OnInterrupt(fn func()) {
// prevent reentry
interruptHookLock.Lock()
defer interruptHookLock.Unlock()
// deal with control+c,etc
// controlling terminal close, daemon not exit
interruptHooks = append(interruptHooks, fn)
}