mirror of
https://github.com/caddyserver/caddy.git
synced 2025-05-24 03:19:59 +08:00
core: OnExit hooks (#6128)
* core: OnExit callbacks * core: Process-global OnExit callbacks
This commit is contained in:
28
caddy.go
28
caddy.go
@ -715,6 +715,7 @@ func exitProcess(ctx context.Context, logger *zap.Logger) {
|
||||
logger.Warn("exiting; byeee!! 👋")
|
||||
|
||||
exitCode := ExitCodeSuccess
|
||||
lastContext := ActiveContext()
|
||||
|
||||
// stop all apps
|
||||
if err := Stop(); err != nil {
|
||||
@ -736,6 +737,16 @@ func exitProcess(ctx context.Context, logger *zap.Logger) {
|
||||
}
|
||||
}
|
||||
|
||||
// execute any process-exit callbacks
|
||||
for _, exitFunc := range lastContext.exitFuncs {
|
||||
exitFunc(ctx)
|
||||
}
|
||||
exitFuncsMu.Lock()
|
||||
for _, exitFunc := range exitFuncs {
|
||||
exitFunc(ctx)
|
||||
}
|
||||
exitFuncsMu.Unlock()
|
||||
|
||||
// shut down admin endpoint(s) in goroutines so that
|
||||
// if this function was called from an admin handler,
|
||||
// it has a chance to return gracefully
|
||||
@ -774,6 +785,23 @@ var exiting = new(int32) // accessed atomically
|
||||
// EXPERIMENTAL API: subject to change or removal.
|
||||
func Exiting() bool { return atomic.LoadInt32(exiting) == 1 }
|
||||
|
||||
// OnExit registers a callback to invoke during process exit.
|
||||
// This registration is PROCESS-GLOBAL, meaning that each
|
||||
// function should only be registered once forever, NOT once
|
||||
// per config load (etc).
|
||||
//
|
||||
// EXPERIMENTAL API: subject to change or removal.
|
||||
func OnExit(f func(context.Context)) {
|
||||
exitFuncsMu.Lock()
|
||||
exitFuncs = append(exitFuncs, f)
|
||||
exitFuncsMu.Unlock()
|
||||
}
|
||||
|
||||
var (
|
||||
exitFuncs []func(context.Context)
|
||||
exitFuncsMu sync.Mutex
|
||||
)
|
||||
|
||||
// Duration can be an integer or a string. An integer is
|
||||
// interpreted as nanoseconds. If a string, it is a Go
|
||||
// time.Duration value such as `300ms`, `1.5h`, or `2h45m`;
|
||||
|
Reference in New Issue
Block a user