1/*
2Copyright 2017 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package server
18
19import (
20	"context"
21	"os"
22	"os/signal"
23)
24
25var onlyOneSignalHandler = make(chan struct{})
26var 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.
33func 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.
40func 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
59func 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}
70