aboutsummaryrefslogtreecommitdiff
path: root/libpod/shutdown/handler.go
blob: 9add05c9c97cf1e2bc50c1f628cc62f4af4c04ec (plain)
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
package shutdown

import (
	"os"
	"os/signal"
	"sync"
	"syscall"
	"time"

	"github.com/pkg/errors"
	logrusImport "github.com/sirupsen/logrus"
)

var (
	ErrHandlerExists error = errors.New("handler with given name already exists")
)

var (
	stopped    bool
	sigChan    chan os.Signal
	cancelChan chan bool
	// Synchronize accesses to the map
	handlerLock sync.Mutex
	// Definitions of all on-shutdown handlers
	handlers map[string]func(os.Signal) error
	// Ordering that on-shutdown handlers will be invoked.
	handlerOrder    []string
	shutdownInhibit sync.RWMutex
	logrus          = logrusImport.WithField("PID", os.Getpid())
)

// Start begins handling SIGTERM and SIGINT and will run the given on-signal
// handlers when one is called. This can be cancelled by calling Stop().
func Start() error {
	if sigChan != nil {
		// Already running, do nothing.
		return nil
	}

	sigChan = make(chan os.Signal, 2)
	cancelChan = make(chan bool, 1)
	stopped = false

	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		select {
		case <-cancelChan:
			logrus.Infof("Received shutdown.Stop(), terminating!")
			signal.Stop(sigChan)
			close(sigChan)
			close(cancelChan)
			stopped = true
			return
		case sig := <-sigChan:
			logrus.Infof("Received shutdown signal %q, terminating!", sig.String())
			shutdownInhibit.Lock()
			handlerLock.Lock()

			for _, name := range handlerOrder {
				handler, ok := handlers[name]
				if !ok {
					logrus.Errorf("Shutdown handler %q definition not found!", name)
					continue
				}

				logrus.Infof("Invoking shutdown handler %q", name)
				start := time.Now()
				if err := handler(sig); err != nil {
					logrus.Errorf("Running shutdown handler %q: %v", name, err)
				}
				logrus.Debugf("Completed shutdown handler %q, duration %v", name,
					time.Since(start).Round(time.Second))
			}
			handlerLock.Unlock()
			shutdownInhibit.Unlock()
			return
		}
	}()

	return nil
}

// Stop the shutdown signal handler.
func Stop() error {
	if cancelChan == nil {
		return errors.New("shutdown signal handler has not yet been started")
	}
	if stopped {
		return nil
	}

	cancelChan <- true

	return nil
}

// Inhibit temporarily inhibit signals from shutting down Libpod.
func Inhibit() {
	shutdownInhibit.RLock()
}

// Uninhibit stop inhibiting signals from shutting down Libpod.
func Uninhibit() {
	shutdownInhibit.RUnlock()
}

// Register registers a function that will be executed when Podman is terminated
// by a signal. Handlers are invoked LIFO - the last handler registered is the
// first run.
func Register(name string, handler func(os.Signal) error) error {
	handlerLock.Lock()
	defer handlerLock.Unlock()

	if handlers == nil {
		handlers = make(map[string]func(os.Signal) error)
	}

	if _, ok := handlers[name]; ok {
		return ErrHandlerExists
	}

	handlers[name] = handler
	handlerOrder = append([]string{name}, handlerOrder...)

	return nil
}

// Unregister un-registers a given shutdown handler.
func Unregister(name string) error {
	handlerLock.Lock()
	defer handlerLock.Unlock()

	if handlers == nil {
		return nil
	}

	if _, ok := handlers[name]; !ok {
		return nil
	}

	delete(handlers, name)

	newOrder := []string{}
	for _, checkName := range handlerOrder {
		if checkName != name {
			newOrder = append(newOrder, checkName)
		}
	}
	handlerOrder = newOrder

	return nil
}