-
Notifications
You must be signed in to change notification settings - Fork 13
/
shutdown.go
49 lines (42 loc) · 1.14 KB
/
shutdown.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Copyright 2022-2024 Sauce Labs Inc., all rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package forwarder
import (
"context"
"os"
"os/signal"
"syscall"
"time"
)
type shutdownConfig struct {
ShutdownTimeout time.Duration
ShutdownSignals []os.Signal
}
func defaultShutdownConfig() shutdownConfig {
return shutdownConfig{
ShutdownTimeout: 30 * time.Second,
ShutdownSignals: []os.Signal{syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT},
}
}
func shutdownContext(cfg shutdownConfig) (context.Context, context.CancelFunc) {
ctx := context.Background()
var cancels []func()
if len(cfg.ShutdownSignals) > 0 {
var cancel context.CancelFunc
ctx, cancel = signal.NotifyContext(ctx, cfg.ShutdownSignals...)
cancels = append(cancels, cancel)
}
if cfg.ShutdownTimeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, cfg.ShutdownTimeout)
cancels = append(cancels, cancel)
}
return ctx, func() {
for _, f := range cancels {
f()
}
}
}