Rename UNUSED macro to OVS_UNUSED to avoid naming conflict.
[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 <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include "shash.h"
27 #include "util.h"
28
29 #define THIS_MODULE VLM_fatal_signal
30 #include "vlog.h"
31
32 /* Signals to catch. */
33 static const int fatal_signals[] = { SIGTERM, SIGINT, SIGHUP, SIGALRM };
34
35 /* Signals to catch as a sigset_t. */
36 static sigset_t fatal_signal_set;
37
38 /* Hooks to call upon catching a signal */
39 struct hook {
40     void (*func)(void *aux);
41     void *aux;
42     bool run_at_exit;
43 };
44 #define MAX_HOOKS 32
45 static struct hook hooks[MAX_HOOKS];
46 static size_t n_hooks;
47
48 /* Number of nesting signal blockers. */
49 static int block_level = 0;
50
51 /* Signal mask saved by outermost signal blocker. */
52 static sigset_t saved_signal_mask;
53
54 /* Disabled by fatal_signal_fork()? */
55 static bool disabled;
56
57 static void call_sigprocmask(int how, sigset_t* new_set, sigset_t* old_set);
58 static void atexit_handler(void);
59 static void call_hooks(int sig_nr);
60
61 /* Registers 'hook' to be called when a process termination signal is raised.
62  * If 'run_at_exit' is true, 'hook' is also called during normal process
63  * termination, e.g. when exit() is called or when main() returns.
64  *
65  * 'func' will be invoked from an asynchronous signal handler, so it must be
66  * written appropriately.  For example, it must not call most C library
67  * functions, including malloc() or free(). */
68 void
69 fatal_signal_add_hook(void (*func)(void *aux), void *aux, bool run_at_exit)
70 {
71     fatal_signal_block();
72     assert(n_hooks < MAX_HOOKS);
73     hooks[n_hooks].func = func;
74     hooks[n_hooks].aux = aux;
75     hooks[n_hooks].run_at_exit = run_at_exit;
76     n_hooks++;
77     fatal_signal_unblock();
78 }
79
80 /* Blocks program termination signals until fatal_signal_unblock() is called.
81  * May be called multiple times with nesting; if so, fatal_signal_unblock()
82  * must be called the same number of times to unblock signals.
83  *
84  * This is needed while adjusting a data structure that will be accessed by a
85  * fatal signal hook, so that the hook is not invoked while the data structure
86  * is in an inconsistent state. */
87 void
88 fatal_signal_block(void)
89 {
90     static bool inited = false;
91     if (!inited) {
92         size_t i;
93
94         inited = true;
95         sigemptyset(&fatal_signal_set);
96         for (i = 0; i < ARRAY_SIZE(fatal_signals); i++) {
97             int sig_nr = fatal_signals[i];
98             struct sigaction old_sa;
99
100             sigaddset(&fatal_signal_set, sig_nr);
101             if (sigaction(sig_nr, NULL, &old_sa)) {
102                 ovs_fatal(errno, "sigaction");
103             }
104             if (old_sa.sa_handler == SIG_DFL
105                 && signal(sig_nr, fatal_signal_handler) == SIG_ERR) {
106                 ovs_fatal(errno, "signal");
107             }
108         }
109         atexit(atexit_handler);
110     }
111
112     if (++block_level == 1) {
113         call_sigprocmask(SIG_BLOCK, &fatal_signal_set, &saved_signal_mask);
114     }
115 }
116
117 /* Unblocks program termination signals blocked by fatal_signal_block() is
118  * called.  If multiple calls to fatal_signal_block() are nested,
119  * fatal_signal_unblock() must be called the same number of times to unblock
120  * signals. */
121 void
122 fatal_signal_unblock(void)
123 {
124     assert(block_level > 0);
125     if (--block_level == 0) {
126         call_sigprocmask(SIG_SETMASK, &saved_signal_mask, NULL);
127     }
128 }
129
130 /* Handles fatal signal number 'sig_nr'.
131  *
132  * Ordinarily this is the actual signal handler.  When other code needs to
133  * handle one of our signals, however, it can register for that signal and, if
134  * and when necessary, call this function to do fatal signal processing for it
135  * and terminate the process.  Currently only timeval.c does this, for SIGALRM.
136  * (It is not important whether the other code sets up its signal handler
137  * before or after this file, because this file will only set up a signal
138  * handler in the case where the signal has its default handling.)  */
139 void
140 fatal_signal_handler(int sig_nr)
141 {
142     call_hooks(sig_nr);
143
144     /* Re-raise the signal with the default handling so that the program
145      * termination status reflects that we were killed by this signal */
146     signal(sig_nr, SIG_DFL);
147     raise(sig_nr);
148 }
149
150 static void
151 atexit_handler(void)
152 {
153     if (!disabled) {
154         call_hooks(0);
155     }
156 }
157
158 static void
159 call_hooks(int sig_nr)
160 {
161     static volatile sig_atomic_t recurse = 0;
162     if (!recurse) {
163         size_t i;
164
165         recurse = 1;
166
167         for (i = 0; i < n_hooks; i++) {
168             struct hook *h = &hooks[i];
169             if (sig_nr || h->run_at_exit) {
170                 h->func(h->aux);
171             }
172         }
173     }
174 }
175 \f
176 static struct shash files = SHASH_INITIALIZER(&files);
177
178 static void unlink_files(void *aux);
179 static void do_unlink_files(void);
180
181 /* Registers 'file' to be unlinked when the program terminates via exit() or a
182  * fatal signal. */
183 void
184 fatal_signal_add_file_to_unlink(const char *file)
185 {
186     static bool added_hook = false;
187     if (!added_hook) {
188         added_hook = true;
189         fatal_signal_add_hook(unlink_files, NULL, true);
190     }
191
192     fatal_signal_block();
193     if (!shash_find(&files, file)) {
194         shash_add(&files, file, NULL);
195     }
196     fatal_signal_unblock();
197 }
198
199 /* Unregisters 'file' from being unlinked when the program terminates via
200  * exit() or a fatal signal. */
201 void
202 fatal_signal_remove_file_to_unlink(const char *file)
203 {
204     struct shash_node *node;
205
206     fatal_signal_block();
207     node = shash_find(&files, file);
208     if (node) {
209         shash_delete(&files, node);
210     }
211     fatal_signal_unblock();
212 }
213
214 /* Like fatal_signal_remove_file_to_unlink(), but also unlinks 'file'.
215  * Returns 0 if successful, otherwise a positive errno value. */
216 int
217 fatal_signal_unlink_file_now(const char *file)
218 {
219     int error = unlink(file) ? errno : 0;
220     if (error) {
221         VLOG_WARN("could not unlink \"%s\" (%s)", file, strerror(error));
222     }
223
224     fatal_signal_remove_file_to_unlink(file);
225
226     return error;
227 }
228
229 static void
230 unlink_files(void *aux OVS_UNUSED)
231 {
232     do_unlink_files(); 
233 }
234
235 /* This is a fatal_signal_add_hook() callback (via unlink_files()).  It will be
236  * invoked from an asynchronous signal handler, so it cannot call most C
237  * library functions (unlink() is an explicit exception, see
238  * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html).
239  * That includes free(), so it doesn't try to free the 'files' data
240  * structure. */
241 static void
242 do_unlink_files(void)
243 {
244     struct shash_node *node;
245
246     SHASH_FOR_EACH (node, &files) {
247         unlink(node->name);
248     }
249 }
250 \f
251 /* Disables the fatal signal hook mechanism.  Following a fork, one of the
252  * resulting processes can call this function to allow it to terminate without
253  * triggering fatal signal processing or removing files.  Fatal signal
254  * processing is still enabled in the other process. */
255 void
256 fatal_signal_fork(void)
257 {
258     size_t i;
259
260     disabled = true;
261
262     for (i = 0; i < ARRAY_SIZE(fatal_signals); i++) {
263         int sig_nr = fatal_signals[i];
264         if (signal(sig_nr, SIG_DFL) == SIG_IGN) {
265             signal(sig_nr, SIG_IGN);
266         }
267     }
268 }
269 \f
270 static void
271 call_sigprocmask(int how, sigset_t* new_set, sigset_t* old_set)
272 {
273     int error = sigprocmask(how, new_set, old_set);
274     if (error) {
275         fprintf(stderr, "sigprocmask: %s\n", strerror(errno));
276     }
277 }