Debian Codegraph @

pkg/server/signal.go

raw
1 /*
2 Copyright 2017 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package server
18
19 import (
20 "context"
21 "os"
22 "os/signal"
23 )
24
25 var onlyOneSignalHandler = make(chan struct{})
26 var shutdownHandler chan os.Signal
27
28 // SetupSignalHandler registered for SIGTERM and SIGINT. A stop channel is returned
29 // which is closed on one of these signals. If a second signal is caught, the program
30 // is terminated with exit code 1.
31 // Only one of SetupSignalContext and SetupSignalHandler should be called, and only can
32 // be called once.
33 func SetupSignalHandler() <-chan struct{} {
34 return SetupSignalContext().Done()
35 }
36
37 // SetupSignalContext is same as SetupSignalHandler, but a context.Context is returned.
38 // Only one of SetupSignalContext and SetupSignalHandler should be called, and only can
39 // be called once.
40 func SetupSignalContext() context.Context {
41 close(onlyOneSignalHandler) // panics when called twice
42
43 shutdownHandler = make(chan os.Signal, 2)
44
45 ctx, cancel := context.WithCancel(context.Background())
46 signal.Notify(shutdownHandler, shutdownSignals...)
47 go func() {
48 <-shutdownHandler
49 cancel()
50 <-shutdownHandler
51 os.Exit(1) // second signal. Exit directly.
52 }()
53
54 return ctx
55 }
56
57 // RequestShutdown emulates a received event that is considered as shutdown signal (SIGTERM/SIGINT)
58 // This returns whether a handler was notified
59 func RequestShutdown() bool {
60 if shutdownHandler != nil {
61 select {
62 case shutdownHandler <- shutdownSignals[0]:
63 return true
64 default:
65 }
66 }
67
68 return false
69 }