1e63d48d6360cd35529740dbc02c891d94705838
[sliver-openvswitch.git] / lib / fatal-signal.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
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 <errno.h>
19 #include <signal.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 "ovs-thread.h"
27 #include "poll-loop.h"
28 #include "shash.h"
29 #include "sset.h"
30 #include "signals.h"
31 #include "socket-util.h"
32 #include "util.h"
33 #include "vlog.h"
34
35 #include "type-props.h"
36
37 #ifndef SIG_ATOMIC_MAX
38 #define SIG_ATOMIC_MAX TYPE_MAXIMUM(sig_atomic_t)
39 #endif
40
41 VLOG_DEFINE_THIS_MODULE(fatal_signal);
42
43 /* Signals to catch. */
44 #ifndef _WIN32
45 static const int fatal_signals[] = { SIGTERM, SIGINT, SIGHUP, SIGALRM };
46 #else
47 static const int fatal_signals[] = { SIGTERM };
48 #endif
49
50 /* Hooks to call upon catching a signal */
51 struct hook {
52     void (*hook_cb)(void *aux);
53     void (*cancel_cb)(void *aux);
54     void *aux;
55     bool run_at_exit;
56 };
57 #define MAX_HOOKS 32
58 static struct hook hooks[MAX_HOOKS];
59 static size_t n_hooks;
60
61 static int signal_fds[2];
62 HANDLE wevent;
63 static volatile sig_atomic_t stored_sig_nr = SIG_ATOMIC_MAX;
64
65 static struct ovs_mutex mutex;
66
67 static void atexit_handler(void);
68 static void call_hooks(int sig_nr);
69
70 /* Initializes the fatal signal handling module.  Calling this function is
71  * optional, because calling any other function in the module will also
72  * initialize it.  However, in a multithreaded program, the module must be
73  * initialized while the process is still single-threaded. */
74 void
75 fatal_signal_init(void)
76 {
77     static bool inited = false;
78
79     if (!inited) {
80         size_t i;
81
82         assert_single_threaded();
83         inited = true;
84
85         ovs_mutex_init_recursive(&mutex);
86 #ifndef _WIN32
87         xpipe_nonblocking(signal_fds);
88 #else
89         wevent = CreateEvent(NULL, TRUE, FALSE, NULL);
90         if (!wevent) {
91             char *msg_buf = ovs_lasterror_to_string();
92             VLOG_FATAL("Failed to create a event (%s).", msg_buf);
93         }
94 #endif
95
96         for (i = 0; i < ARRAY_SIZE(fatal_signals); i++) {
97             int sig_nr = fatal_signals[i];
98 #ifndef _WIN32
99             struct sigaction old_sa;
100
101             xsigaction(sig_nr, NULL, &old_sa);
102             if (old_sa.sa_handler == SIG_DFL
103                 && signal(sig_nr, fatal_signal_handler) == SIG_ERR) {
104                 VLOG_FATAL("signal failed (%s)", ovs_strerror(errno));
105             }
106 #else
107             if (signal(sig_nr, fatal_signal_handler) == SIG_ERR) {
108                 VLOG_FATAL("signal failed (%s)", ovs_strerror(errno));
109             }
110 #endif
111         }
112         atexit(atexit_handler);
113     }
114 }
115
116 /* Registers 'hook_cb' to be called from inside poll_block() following a fatal
117  * signal.  'hook_cb' does not need to be async-signal-safe.  In a
118  * multithreaded program 'hook_cb' might be called from any thread, with
119  * threads other than the one running 'hook_cb' in unknown states.
120  *
121  * If 'run_at_exit' is true, 'hook_cb' is also called during normal process
122  * termination, e.g. when exit() is called or when main() returns.
123  *
124  * If the current process forks, fatal_signal_fork() may be called to clear the
125  * parent process's fatal signal hooks, so that 'hook_cb' is only called when
126  * the child terminates, not when the parent does.  When fatal_signal_fork() is
127  * called, it calls the 'cancel_cb' function if it is nonnull, passing 'aux',
128  * to notify that the hook has been canceled.  This allows the hook to free
129  * memory, etc. */
130 void
131 fatal_signal_add_hook(void (*hook_cb)(void *aux), void (*cancel_cb)(void *aux),
132                       void *aux, bool run_at_exit)
133 {
134     fatal_signal_init();
135
136     ovs_mutex_lock(&mutex);
137     ovs_assert(n_hooks < MAX_HOOKS);
138     hooks[n_hooks].hook_cb = hook_cb;
139     hooks[n_hooks].cancel_cb = cancel_cb;
140     hooks[n_hooks].aux = aux;
141     hooks[n_hooks].run_at_exit = run_at_exit;
142     n_hooks++;
143     ovs_mutex_unlock(&mutex);
144 }
145
146 /* Handles fatal signal number 'sig_nr'.
147  *
148  * Ordinarily this is the actual signal handler.  When other code needs to
149  * handle one of our signals, however, it can register for that signal and, if
150  * and when necessary, call this function to do fatal signal processing for it
151  * and terminate the process.  Currently only timeval.c does this, for SIGALRM.
152  * (It is not important whether the other code sets up its signal handler
153  * before or after this file, because this file will only set up a signal
154  * handler in the case where the signal has its default handling.)  */
155 void
156 fatal_signal_handler(int sig_nr)
157 {
158 #ifndef _WIN32
159     ignore(write(signal_fds[1], "", 1));
160 #else
161     SetEvent(wevent);
162 #endif
163     stored_sig_nr = sig_nr;
164 }
165
166 /* Check whether a fatal signal has occurred and, if so, call the fatal signal
167  * hooks and exit.
168  *
169  * This function is called automatically by poll_block(), but specialized
170  * programs that may not always call poll_block() on a regular basis should
171  * also call it periodically.  (Therefore, any function with "block" in its
172  * name should call fatal_signal_run() each time it is called, either directly
173  * or through poll_block(), because such functions can only used by specialized
174  * programs that can afford to block outside their main loop around
175  * poll_block().)
176  */
177 void
178 fatal_signal_run(void)
179 {
180     sig_atomic_t sig_nr;
181
182     fatal_signal_init();
183
184     sig_nr = stored_sig_nr;
185     if (sig_nr != SIG_ATOMIC_MAX) {
186         char namebuf[SIGNAL_NAME_BUFSIZE];
187
188         ovs_mutex_lock(&mutex);
189
190 #ifndef _WIN32
191         VLOG_WARN("terminating with signal %d (%s)",
192                   (int)sig_nr, signal_name(sig_nr, namebuf, sizeof namebuf));
193 #else
194         VLOG_WARN("terminating with signal %d", (int)sig_nr);
195 #endif
196         call_hooks(sig_nr);
197
198         /* Re-raise the signal with the default handling so that the program
199          * termination status reflects that we were killed by this signal */
200         signal(sig_nr, SIG_DFL);
201         raise(sig_nr);
202
203         ovs_mutex_unlock(&mutex);
204         OVS_NOT_REACHED();
205     }
206 }
207
208 void
209 fatal_signal_wait(void)
210 {
211     fatal_signal_init();
212     poll_fd_wait_event(signal_fds[0], wevent, POLLIN);
213 }
214
215 static void
216 atexit_handler(void)
217 {
218     call_hooks(0);
219 }
220
221 static void
222 call_hooks(int sig_nr)
223 {
224     static volatile sig_atomic_t recurse = 0;
225     if (!recurse) {
226         size_t i;
227
228         recurse = 1;
229
230         for (i = 0; i < n_hooks; i++) {
231             struct hook *h = &hooks[i];
232             if (sig_nr || h->run_at_exit) {
233                 h->hook_cb(h->aux);
234             }
235         }
236     }
237 }
238 \f
239 /* Files to delete on exit. */
240 static struct sset files = SSET_INITIALIZER(&files);
241
242 /* Has a hook function been registered with fatal_signal_add_hook() (and not
243  * cleared by fatal_signal_fork())? */
244 static bool added_hook;
245
246 static void unlink_files(void *aux);
247 static void cancel_files(void *aux);
248 static void do_unlink_files(void);
249
250 /* Registers 'file' to be unlinked when the program terminates via exit() or a
251  * fatal signal. */
252 void
253 fatal_signal_add_file_to_unlink(const char *file)
254 {
255     fatal_signal_init();
256
257     ovs_mutex_lock(&mutex);
258     if (!added_hook) {
259         added_hook = true;
260         fatal_signal_add_hook(unlink_files, cancel_files, NULL, true);
261     }
262
263     sset_add(&files, file);
264     ovs_mutex_unlock(&mutex);
265 }
266
267 /* Unregisters 'file' from being unlinked when the program terminates via
268  * exit() or a fatal signal. */
269 void
270 fatal_signal_remove_file_to_unlink(const char *file)
271 {
272     fatal_signal_init();
273
274     ovs_mutex_lock(&mutex);
275     sset_find_and_delete(&files, file);
276     ovs_mutex_unlock(&mutex);
277 }
278
279 /* Like fatal_signal_remove_file_to_unlink(), but also unlinks 'file'.
280  * Returns 0 if successful, otherwise a positive errno value. */
281 int
282 fatal_signal_unlink_file_now(const char *file)
283 {
284     int error;
285
286     fatal_signal_init();
287
288     ovs_mutex_lock(&mutex);
289
290     error = unlink(file) ? errno : 0;
291     if (error) {
292         VLOG_WARN("could not unlink \"%s\" (%s)", file, ovs_strerror(error));
293     }
294
295     fatal_signal_remove_file_to_unlink(file);
296
297     ovs_mutex_unlock(&mutex);
298
299     return error;
300 }
301
302 static void
303 unlink_files(void *aux OVS_UNUSED)
304 {
305     do_unlink_files();
306 }
307
308 static void
309 cancel_files(void *aux OVS_UNUSED)
310 {
311     sset_clear(&files);
312     added_hook = false;
313 }
314
315 static void
316 do_unlink_files(void)
317 {
318     const char *file;
319
320     SSET_FOR_EACH (file, &files) {
321         unlink(file);
322     }
323 }
324 \f
325 /* Clears all of the fatal signal hooks without executing them.  If any of the
326  * hooks passed a 'cancel_cb' function to fatal_signal_add_hook(), then those
327  * functions will be called, allowing them to free resources, etc.
328  *
329  * Following a fork, one of the resulting processes can call this function to
330  * allow it to terminate without calling the hooks registered before calling
331  * this function.  New hooks registered after calling this function will take
332  * effect normally. */
333 void
334 fatal_signal_fork(void)
335 {
336     size_t i;
337
338     assert_single_threaded();
339
340     for (i = 0; i < n_hooks; i++) {
341         struct hook *h = &hooks[i];
342         if (h->cancel_cb) {
343             h->cancel_cb(h->aux);
344         }
345     }
346     n_hooks = 0;
347
348     /* Raise any signals that we have already received with the default
349      * handler. */
350     if (stored_sig_nr != SIG_ATOMIC_MAX) {
351         raise(stored_sig_nr);
352     }
353 }