1/*
2Copyright 2016 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 interrupt
18
19import (
20	"os"
21	"os/signal"
22	"sync"
23	"syscall"
24)
25
26// terminationSignals are signals that cause the program to exit in the
27// supported platforms (linux, darwin, windows).
28var terminationSignals = []os.Signal{syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT}
29
30// Handler guarantees execution of notifications after a critical section (the function passed
31// to a Run method), even in the presence of process termination. It guarantees exactly once
32// invocation of the provided notify functions.
33type Handler struct {
34	notify []func()
35	final  func(os.Signal)
36	once   sync.Once
37}
38
39// Chain creates a new handler that invokes all notify functions when the critical section exits
40// and then invokes the optional handler's notifications. This allows critical sections to be
41// nested without losing exactly once invocations. Notify functions can invoke any cleanup needed
42// but should not exit (which is the responsibility of the parent handler).
43func Chain(handler *Handler, notify ...func()) *Handler {
44	if handler == nil {
45		return New(nil, notify...)
46	}
47	return New(handler.Signal, append(notify, handler.Close)...)
48}
49
50// New creates a new handler that guarantees all notify functions are run after the critical
51// section exits (or is interrupted by the OS), then invokes the final handler. If no final
52// handler is specified, the default final is `os.Exit(1)`. A handler can only be used for
53// one critical section.
54func New(final func(os.Signal), notify ...func()) *Handler {
55	return &Handler{
56		final:  final,
57		notify: notify,
58	}
59}
60
61// Close executes all the notification handlers if they have not yet been executed.
62func (h *Handler) Close() {
63	h.once.Do(func() {
64		for _, fn := range h.notify {
65			fn()
66		}
67	})
68}
69
70// Signal is called when an os.Signal is received, and guarantees that all notifications
71// are executed, then the final handler is executed. This function should only be called once
72// per Handler instance.
73func (h *Handler) Signal(s os.Signal) {
74	h.once.Do(func() {
75		for _, fn := range h.notify {
76			fn()
77		}
78		if h.final == nil {
79			os.Exit(1)
80		}
81		h.final(s)
82	})
83}
84
85// Run ensures that any notifications are invoked after the provided fn exits (even if the
86// process is interrupted by an OS termination signal). Notifications are only invoked once
87// per Handler instance, so calling Run more than once will not behave as the user expects.
88func (h *Handler) Run(fn func() error) error {
89	ch := make(chan os.Signal, 1)
90	signal.Notify(ch, terminationSignals...)
91	defer func() {
92		signal.Stop(ch)
93		close(ch)
94	}()
95	go func() {
96		sig, ok := <-ch
97		if !ok {
98			return
99		}
100		h.Signal(sig)
101	}()
102	defer h.Close()
103	return fn()
104}
105