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