2021-09-01 09:45:42 +00:00
|
|
|
//go:build !plan9
|
2014-05-13 22:04:04 +00:00
|
|
|
// +build !plan9
|
|
|
|
|
2020-04-28 06:10:23 +00:00
|
|
|
package grace
|
2014-05-13 22:04:04 +00:00
|
|
|
|
|
|
|
import (
|
2022-10-12 14:18:40 +00:00
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
2014-05-13 22:04:04 +00:00
|
|
|
"os"
|
|
|
|
"os/signal"
|
2022-10-12 14:18:40 +00:00
|
|
|
"reflect"
|
|
|
|
"runtime"
|
2018-10-09 07:41:57 +00:00
|
|
|
"sync"
|
2014-05-13 22:04:04 +00:00
|
|
|
"syscall"
|
|
|
|
)
|
|
|
|
|
2018-10-09 07:41:57 +00:00
|
|
|
var signalChan chan os.Signal
|
2022-09-28 19:44:13 +00:00
|
|
|
var interruptHooks = make([]func(), 0)
|
|
|
|
var interruptHookLock sync.RWMutex
|
|
|
|
var reloadHooks = make([]func(), 0)
|
|
|
|
var reloadHookLock sync.RWMutex
|
2018-10-09 07:41:57 +00:00
|
|
|
|
2022-10-12 14:18:40 +00:00
|
|
|
func GetFunctionName(i interface{}) string {
|
|
|
|
return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
|
|
|
|
}
|
|
|
|
|
2018-10-09 07:41:57 +00:00
|
|
|
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,
|
2022-09-28 19:44:13 +00:00
|
|
|
syscall.SIGHUP,
|
2014-05-13 22:04:04 +00:00
|
|
|
syscall.SIGINT,
|
|
|
|
syscall.SIGTERM,
|
2016-04-14 08:30:26 +00:00
|
|
|
// syscall.SIGQUIT,
|
|
|
|
)
|
2014-05-13 22:04:04 +00:00
|
|
|
go func() {
|
2022-09-28 19:44:13 +00:00
|
|
|
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 {
|
2022-10-12 14:18:40 +00:00
|
|
|
glog.V(4).Infof("exec interrupt hook func name:%s", GetFunctionName(hook))
|
2022-09-28 19:44:13 +00:00
|
|
|
hook()
|
|
|
|
}
|
|
|
|
interruptHookLock.RUnlock()
|
|
|
|
os.Exit(0)
|
2018-10-09 07:41:57 +00:00
|
|
|
}
|
2014-05-13 22:04:04 +00:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
2018-10-09 07:41:57 +00:00
|
|
|
|
2022-09-28 19:44:13 +00:00
|
|
|
func OnReload(fn func()) {
|
|
|
|
// prevent reentry
|
|
|
|
reloadHookLock.Lock()
|
|
|
|
defer reloadHookLock.Unlock()
|
|
|
|
reloadHooks = append(reloadHooks, fn)
|
|
|
|
}
|
|
|
|
|
2018-10-09 07:41:57 +00:00
|
|
|
func OnInterrupt(fn func()) {
|
|
|
|
// prevent reentry
|
2022-09-28 19:44:13 +00:00
|
|
|
interruptHookLock.Lock()
|
|
|
|
defer interruptHookLock.Unlock()
|
2018-10-09 07:41:57 +00:00
|
|
|
|
|
|
|
// deal with control+c,etc
|
|
|
|
// controlling terminal close, daemon not exit
|
2022-09-28 19:44:13 +00:00
|
|
|
interruptHooks = append(interruptHooks, fn)
|
2018-10-09 07:41:57 +00:00
|
|
|
}
|