Catalli's threaded switch
[sliver-openvswitch.git] / lib / fatal-signal.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 Nicira Networks.
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 #include <config.h>
17 #include "fatal-signal.h"
18 #include <assert.h>
19 #include <errno.h>
20 #include <stdbool.h>
21 #include <stdio.h>
22 #include <stdint.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include "poll-loop.h"
27 #include "shash.h"
28 #include "socket-util.h"
29 #include "util.h"
30 #include "vlog.h"
31
32 VLOG_DEFINE_THIS_MODULE(fatal_signal)
33
34 /* Signals to catch. */
35 static const int fatal_signals[] = { SIGTERM, SIGINT, SIGHUP, SIGALRM };
36
37 /* Signals to catch as a sigset_t. */
38 static sigset_t fatal_signal_set;
39
40 /* Hooks to call upon catching a signal */
41 struct hook {
42     void (*hook_cb)(void *aux);
43     void (*cancel_cb)(void *aux);
44     void *aux;
45     bool run_at_exit;
46 };
47 #define MAX_HOOKS 32
48 static struct hook hooks[MAX_HOOKS];
49 static size_t n_hooks;
50
51 static int signal_fds[2];
52 static volatile sig_atomic_t stored_sig_nr = SIG_ATOMIC_MAX;
53
54 static void fatal_signal_init(void);
55 static void atexit_handler(void);
56 static void call_hooks(int sig_nr);
57
58 static void
59 fatal_signal_init(void)
60 {
61     static bool inited = false;
62
63     if (!inited) {
64         size_t i;
65
66         inited = true;
67
68         if (pipe(signal_fds)) {
69             ovs_fatal(errno, "could not create pipe");
70         }
71         set_nonblocking(signal_fds[0]);
72         set_nonblocking(signal_fds[1]);
73
74         sigemptyset(&fatal_signal_set);
75         for (i = 0; i < ARRAY_SIZE(fatal_signals); i++) {
76             int sig_nr = fatal_signals[i];
77             struct sigaction old_sa;
78
79             sigaddset(&fatal_signal_set, sig_nr);
80             if (sigaction(sig_nr, NULL, &old_sa)) {
81                 ovs_fatal(errno, "sigaction");
82             }
83             if (old_sa.sa_handler == SIG_DFL
84                 && signal(sig_nr, fatal_signal_handler) == SIG_ERR) {
85                 ovs_fatal(errno, "signal");
86             }
87         }
88         atexit(atexit_handler);
89     }
90 }
91
92 /* Registers 'hook_cb' to be called when a process termination signal is
93  * raised.  If 'run_at_exit' is true, 'hook_cb' is also called during normal
94  * process termination, e.g. when exit() is called or when main() returns.
95  *
96  * 'hook_cb' is not called immediately from the signal handler but rather the
97  * next time the poll loop iterates, so it is freed from the usual restrictions
98  * on signal handler functions.
99  *
100  * If the current process forks, fatal_signal_fork() may be called to clear the
101  * parent process's fatal signal hooks, so that 'hook_cb' is only called when
102  * the child terminates, not when the parent does.  When fatal_signal_fork() is
103  * called, it calls the 'cancel_cb' function if it is nonnull, passing 'aux',
104  * to notify that the hook has been canceled.  This allows the hook to free
105  * memory, etc. */
106 void
107 fatal_signal_add_hook(void (*hook_cb)(void *aux), void (*cancel_cb)(void *aux),
108                       void *aux, bool run_at_exit)
109 {
110     fatal_signal_init();
111
112     assert(n_hooks < MAX_HOOKS);
113     hooks[n_hooks].hook_cb = hook_cb;
114     hooks[n_hooks].cancel_cb = cancel_cb;
115     hooks[n_hooks].aux = aux;
116     hooks[n_hooks].run_at_exit = run_at_exit;
117     n_hooks++;
118 }
119
120 /* Handles fatal signal number 'sig_nr'.
121  *
122  * Ordinarily this is the actual signal handler.  When other code needs to
123  * handle one of our signals, however, it can register for that signal and, if
124  * and when necessary, call this function to do fatal signal processing for it
125  * and terminate the process.  Currently only timeval.c does this, for SIGALRM.
126  * (It is not important whether the other code sets up its signal handler
127  * before or after this file, because this file will only set up a signal
128  * handler in the case where the signal has its default handling.)  */
129 void
130 fatal_signal_handler(int sig_nr)
131 {
132     ignore(write(signal_fds[1], "", 1));
133     stored_sig_nr = sig_nr;
134 }
135
136 /* Check whether a fatal signal has occurred and, if so, call the fatal signal
137  * hooks and exit.
138  *
139  * This function is called automatically by poll_block(), but specialized
140  * programs that may not always call poll_block() on a regular basis should
141  * also call it periodically.  (Therefore, any function with "block" in its
142  * name should call fatal_signal_run() each time it is called, either directly
143  * or through poll_block(), because such functions can only used by specialized
144  * programs that can afford to block outside their main loop around
145  * poll_block().)
146  */
147 void
148 fatal_signal_run(void)
149 {
150     int sig_nr;
151
152     fatal_signal_init();
153
154     sig_nr = stored_sig_nr;
155     if (sig_nr != SIG_ATOMIC_MAX) {
156         call_hooks(sig_nr);
157
158         /* Re-raise the signal with the default handling so that the program
159          * termination status reflects that we were killed by this signal */
160         signal(sig_nr, SIG_DFL);
161         raise(sig_nr);
162     }
163 }
164
165 void
166 fatal_signal_wait(void)
167 {
168     fatal_signal_init();
169     poll_fd_wait(signal_fds[0], POLLIN);
170 }
171
172 static void
173 atexit_handler(void)
174 {
175     call_hooks(0);
176 }
177
178 static void
179 call_hooks(int sig_nr)
180 {
181     static volatile sig_atomic_t recurse = 0;
182     if (!recurse) {
183         size_t i;
184
185         recurse = 1;
186
187         for (i = 0; i < n_hooks; i++) {
188             struct hook *h = &hooks[i];
189             if (sig_nr || h->run_at_exit) {
190                 h->hook_cb(h->aux);
191             }
192         }
193     }
194 }
195 \f
196 /* Files to delete on exit.  (The 'data' member of each node is unused.) */
197 static struct shash files = SHASH_INITIALIZER(&files);
198
199 /* Has a hook function been registered with fatal_signal_add_hook() (and not
200  * cleared by fatal_signal_fork())? */
201 static bool added_hook;
202
203 static void unlink_files(void *aux);
204 static void cancel_files(void *aux);
205 static void do_unlink_files(void);
206
207 /* Registers 'file' to be unlinked when the program terminates via exit() or a
208  * fatal signal. */
209 void
210 fatal_signal_add_file_to_unlink(const char *file)
211 {
212     if (!added_hook) {
213         added_hook = true;
214         fatal_signal_add_hook(unlink_files, cancel_files, NULL, true);
215     }
216
217     shash_add_once(&files, file, NULL);
218 }
219
220 /* Unregisters 'file' from being unlinked when the program terminates via
221  * exit() or a fatal signal. */
222 void
223 fatal_signal_remove_file_to_unlink(const char *file)
224 {
225     struct shash_node *node;
226
227     node = shash_find(&files, file);
228     if (node) {
229         shash_delete(&files, node);
230     }
231 }
232
233 /* Like fatal_signal_remove_file_to_unlink(), but also unlinks 'file'.
234  * Returns 0 if successful, otherwise a positive errno value. */
235 int
236 fatal_signal_unlink_file_now(const char *file)
237 {
238     int error = unlink(file) ? errno : 0;
239     if (error) {
240         VLOG_WARN("could not unlink \"%s\" (%s)", file, strerror(error));
241     }
242
243     fatal_signal_remove_file_to_unlink(file);
244
245     return error;
246 }
247
248 static void
249 unlink_files(void *aux OVS_UNUSED)
250 {
251     do_unlink_files();
252 }
253
254 static void
255 cancel_files(void *aux OVS_UNUSED)
256 {
257     shash_clear(&files);
258     added_hook = false;
259 }
260
261 static void
262 do_unlink_files(void)
263 {
264     struct shash_node *node;
265
266     SHASH_FOR_EACH (node, &files) {
267         unlink(node->name);
268     }
269 }
270 \f
271 /* Clears all of the fatal signal hooks without executing them.  If any of the
272  * hooks passed a 'cancel_cb' function to fatal_signal_add_hook(), then those
273  * functions will be called, allowing them to free resources, etc.
274  *
275  * Following a fork, one of the resulting processes can call this function to
276  * allow it to terminate without calling the hooks registered before calling
277  * this function.  New hooks registered after calling this function will take
278  * effect normally. */
279 void
280 fatal_signal_fork(void)
281 {
282     size_t i;
283
284     for (i = 0; i < n_hooks; i++) {
285         struct hook *h = &hooks[i];
286         if (h->cancel_cb) {
287             h->cancel_cb(h->aux);
288         }
289     }
290     n_hooks = 0;
291
292     /* Raise any signals that we have already received with the default
293      * handler. */
294     if (stored_sig_nr != SIG_ATOMIC_MAX) {
295         raise(stored_sig_nr);
296     }
297 }