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