daemon: Allow monitored daemon to dump core no more than once.
[sliver-openvswitch.git] / lib / daemon.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
17 #include <config.h>
18 #include "daemon.h"
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <sys/wait.h>
24 #include <unistd.h>
25 #include "command-line.h"
26 #include "fatal-signal.h"
27 #include "dirs.h"
28 #include "lockfile.h"
29 #include "process.h"
30 #include "socket-util.h"
31 #include "timeval.h"
32 #include "util.h"
33
34 #define THIS_MODULE VLM_daemon
35 #include "vlog.h"
36
37 /* Should we run in the background? */
38 static bool detach;
39
40 /* Name of pidfile (null if none). */
41 static char *pidfile;
42
43 /* Create pidfile even if one already exists and is locked? */
44 static bool overwrite_pidfile;
45
46 /* Should we chdir to "/"? */
47 static bool chdir_ = true;
48
49 /* File descriptor used by daemonize_start() and daemonize_complete(). */
50 static int daemonize_fd = -1;
51
52 /* --monitor: Should a supervisory process monitor the daemon and restart it if
53  * it dies due to an error signal? */
54 static bool monitor;
55
56 /* Returns the file name that would be used for a pidfile if 'name' were
57  * provided to set_pidfile().  The caller must free the returned string. */
58 char *
59 make_pidfile_name(const char *name) 
60 {
61     return (!name
62             ? xasprintf("%s/%s.pid", ovs_rundir, program_name)
63             : abs_file_name(ovs_rundir, name));
64 }
65
66 /* Sets up a following call to daemonize() to create a pidfile named 'name'.
67  * If 'name' begins with '/', then it is treated as an absolute path.
68  * Otherwise, it is taken relative to RUNDIR, which is $(prefix)/var/run by
69  * default.
70  *
71  * If 'name' is null, then program_name followed by ".pid" is used. */
72 void
73 set_pidfile(const char *name)
74 {
75     free(pidfile);
76     pidfile = make_pidfile_name(name);
77 }
78
79 /* Returns an absolute path to the configured pidfile, or a null pointer if no
80  * pidfile is configured.  The caller must not modify or free the returned
81  * string. */
82 const char *
83 get_pidfile(void)
84 {
85     return pidfile;
86 }
87
88 /* Sets that we do not chdir to "/". */
89 void
90 set_no_chdir(void)
91 {
92     chdir_ = false;
93 }
94
95 /* Will we chdir to "/" as part of daemonizing? */
96 bool
97 is_chdir_enabled(void)
98 {
99     return chdir_;
100 }
101
102 /* Normally, die_if_already_running() will terminate the program with a message
103  * if a locked pidfile already exists.  If this function is called,
104  * die_if_already_running() will merely log a warning. */
105 void
106 ignore_existing_pidfile(void)
107 {
108     overwrite_pidfile = true;
109 }
110
111 /* Sets up a following call to daemonize() to detach from the foreground
112  * session, running this process in the background.  */
113 void
114 set_detach(void)
115 {
116     detach = true;
117 }
118
119 /* Will daemonize() really detach? */
120 bool
121 get_detach(void)
122 {
123     return detach;
124 }
125
126 /* Sets up a following call to daemonize() to fork a supervisory process to
127  * monitor the daemon and restart it if it dies due to an error signal.  */
128 void
129 daemon_set_monitor(void)
130 {
131     monitor = true;
132 }
133
134 /* If a pidfile has been configured and that pidfile already exists and is
135  * locked by a running process, returns the pid of the running process.
136  * Otherwise, returns 0. */
137 static pid_t
138 already_running(void)
139 {
140     pid_t pid = 0;
141     if (pidfile) {
142         int fd = open(pidfile, O_RDWR);
143         if (fd >= 0) {
144             struct flock lck;
145             lck.l_type = F_WRLCK;
146             lck.l_whence = SEEK_SET;
147             lck.l_start = 0;
148             lck.l_len = 0;
149             if (fcntl(fd, F_GETLK, &lck) != -1 && lck.l_type != F_UNLCK) {
150                 pid = lck.l_pid;
151             }
152             close(fd);
153         }
154     }
155     return pid;
156 }
157
158 /* If a locked pidfile exists, issue a warning message and, unless
159  * ignore_existing_pidfile() has been called, terminate the program. */
160 void
161 die_if_already_running(void)
162 {
163     pid_t pid = already_running();
164     if (pid) {
165         if (!overwrite_pidfile) {
166             ovs_fatal(0, "%s: already running as pid %ld",
167                       get_pidfile(), (long int) pid);
168         } else {
169             VLOG_WARN("%s: %s already running as pid %ld",
170                       get_pidfile(), program_name, (long int) pid);
171         }
172     }
173 }
174
175 /* If a pidfile has been configured, creates it and stores the running process'
176  * pid init.  Ensures that the pidfile will be deleted when the process
177  * exits. */
178 static void
179 make_pidfile(void)
180 {
181     if (pidfile) {
182         /* Create pidfile via temporary file, so that observers never see an
183          * empty pidfile or an unlocked pidfile. */
184         long int pid = getpid();
185         char *tmpfile;
186         int fd;
187
188         tmpfile = xasprintf("%s.tmp%ld", pidfile, pid);
189         fatal_signal_add_file_to_unlink(tmpfile);
190         fd = open(tmpfile, O_CREAT | O_WRONLY | O_TRUNC, 0666);
191         if (fd >= 0) {
192             struct flock lck;
193             lck.l_type = F_WRLCK;
194             lck.l_whence = SEEK_SET;
195             lck.l_start = 0;
196             lck.l_len = 0;
197             if (fcntl(fd, F_SETLK, &lck) != -1) {
198                 char *text = xasprintf("%ld\n", pid);
199                 if (write(fd, text, strlen(text)) == strlen(text)) {
200                     fatal_signal_add_file_to_unlink(pidfile);
201                     if (rename(tmpfile, pidfile) < 0) {
202                         VLOG_ERR("failed to rename \"%s\" to \"%s\": %s",
203                                  tmpfile, pidfile, strerror(errno));
204                         fatal_signal_remove_file_to_unlink(pidfile);
205                         close(fd);
206                     } else {
207                         /* Keep 'fd' open to retain the lock. */
208                     }
209                     free(text);
210                 } else {
211                     VLOG_ERR("%s: write failed: %s", tmpfile, strerror(errno));
212                     close(fd);
213                 }
214             } else {
215                 VLOG_ERR("%s: fcntl failed: %s", tmpfile, strerror(errno));
216                 close(fd);
217             }
218         } else {
219             VLOG_ERR("%s: create failed: %s", tmpfile, strerror(errno));
220         }
221         fatal_signal_remove_file_to_unlink(tmpfile);
222         free(tmpfile);
223     }
224     free(pidfile);
225     pidfile = NULL;
226 }
227
228 /* If configured with set_pidfile() or set_detach(), creates the pid file and
229  * detaches from the foreground session.  */
230 void
231 daemonize(void)
232 {
233     daemonize_start();
234     daemonize_complete();
235 }
236
237 static pid_t
238 fork_and_wait_for_startup(int *fdp)
239 {
240     int fds[2];
241     pid_t pid;
242
243     if (pipe(fds) < 0) {
244         ovs_fatal(errno, "pipe failed");
245     }
246
247     pid = fork();
248     if (pid > 0) {
249         /* Running in parent process. */
250         char c;
251
252         close(fds[1]);
253         fatal_signal_fork();
254         if (read(fds[0], &c, 1) != 1) {
255             int retval;
256             int status;
257
258             do {
259                 retval = waitpid(pid, &status, 0);
260             } while (retval == -1 && errno == EINTR);
261
262             if (retval == pid
263                 && WIFEXITED(status)
264                 && WEXITSTATUS(status)) {
265                 /* Child exited with an error.  Convey the same error to
266                  * our parent process as a courtesy. */
267                 exit(WEXITSTATUS(status));
268             }
269
270             ovs_fatal(errno, "fork child failed to signal startup");
271         }
272         close(fds[0]);
273         *fdp = -1;
274     } else if (!pid) {
275         /* Running in child process. */
276         close(fds[0]);
277         time_postfork();
278         lockfile_postfork();
279         *fdp = fds[1];
280     } else {
281         ovs_fatal(errno, "could not fork");
282     }
283
284     return pid;
285 }
286
287 static void
288 fork_notify_startup(int fd)
289 {
290     if (fd != -1) {
291         size_t bytes_written;
292         int error;
293
294         error = write_fully(fd, "", 1, &bytes_written);
295         if (error) {
296             ovs_fatal(error, "could not write to pipe");
297         }
298
299         close(fd);
300     }
301 }
302
303 static bool
304 should_restart(int status)
305 {
306     if (WIFSIGNALED(status)) {
307         static const int error_signals[] = {
308             SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGILL, SIGPIPE, SIGSEGV,
309             SIGXCPU, SIGXFSZ
310         };
311
312         size_t i;
313
314         for (i = 0; i < ARRAY_SIZE(error_signals); i++) {
315             if (error_signals[i] == WTERMSIG(status)) {
316                 return true;
317             }
318         }
319     }
320     return false;
321 }
322
323 static void
324 monitor_daemon(pid_t daemon_pid)
325 {
326     /* XXX Should limit the rate at which we restart the daemon. */
327     /* XXX Should log daemon's stderr output at startup time. */
328     const char *saved_program_name;
329     char *status_msg;
330
331     saved_program_name = program_name;
332     program_name = xasprintf("monitor(%s)", program_name);
333     status_msg = xstrdup("healthy");
334     for (;;) {
335         int retval;
336         int status;
337
338         proctitle_set("%s: monitoring pid %lu (%s)",
339                       saved_program_name, (unsigned long int) daemon_pid,
340                       status_msg);
341
342         do {
343             retval = waitpid(daemon_pid, &status, 0);
344         } while (retval == -1 && errno == EINTR);
345
346         if (retval == -1) {
347             ovs_fatal(errno, "waitpid failed");
348         } else if (retval == daemon_pid) {
349             char *s = process_status_msg(status);
350             free(status_msg);
351             status_msg = xasprintf("pid %lu died, %s",
352                                    (unsigned long int) daemon_pid, s);
353             free(s);
354
355             if (should_restart(status)) {
356                 if (WCOREDUMP(status)) {
357                     /* Disable further core dumps to save disk space. */
358                     struct rlimit r;
359
360                     r.rlim_cur = 0;
361                     r.rlim_max = 0;
362                     if (setrlimit(RLIMIT_CORE, &r) == -1) {
363                         VLOG_WARN("failed to disable core dumps: %s",
364                                   strerror(errno));
365                     }
366                 }
367
368                 VLOG_ERR("%s, restarting", status_msg);
369                 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
370                 if (!daemon_pid) {
371                     break;
372                 }
373             } else {
374                 VLOG_INFO("%s, exiting", status_msg);
375                 exit(0);
376             }
377         }
378     }
379     free(status_msg);
380
381     /* Running in new daemon process. */
382     proctitle_restore();
383     free((char *) program_name);
384     program_name = saved_program_name;
385 }
386
387 /* Close stdin, stdout, stderr.  If we're started from e.g. an SSH session,
388  * then this keeps us from holding that session open artificially. */
389 static void
390 close_standard_fds(void)
391 {
392     int null_fd = get_null_fd();
393     if (null_fd >= 0) {
394         dup2(null_fd, STDIN_FILENO);
395         dup2(null_fd, STDOUT_FILENO);
396         dup2(null_fd, STDERR_FILENO);
397     }
398 }
399
400 /* If daemonization is configured, then starts daemonization, by forking and
401  * returning in the child process.  The parent process hangs around until the
402  * child lets it know either that it completed startup successfully (by calling
403  * daemon_complete()) or that it failed to start up (by exiting with a nonzero
404  * exit code). */
405 void
406 daemonize_start(void)
407 {
408     daemonize_fd = -1;
409
410     if (detach) {
411         if (fork_and_wait_for_startup(&daemonize_fd) > 0) {
412             /* Running in parent process. */
413             exit(0);
414         }
415         /* Running in daemon or monitor process. */
416     }
417
418     if (monitor) {
419         int saved_daemonize_fd = daemonize_fd;
420         pid_t daemon_pid;
421
422         daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
423         if (daemon_pid > 0) {
424             /* Running in monitor process. */
425             fork_notify_startup(saved_daemonize_fd);
426             close_standard_fds();
427             monitor_daemon(daemon_pid);
428         }
429         /* Running in daemon process. */
430     }
431
432     make_pidfile();
433 }
434
435 /* If daemonization is configured, then this function notifies the parent
436  * process that the child process has completed startup successfully. */
437 void
438 daemonize_complete(void)
439 {
440     fork_notify_startup(daemonize_fd);
441
442     if (detach) {
443         setsid();
444         if (chdir_) {
445             ignore(chdir("/"));
446         }
447         close_standard_fds();
448     }
449 }
450
451 void
452 daemon_usage(void)
453 {
454     printf(
455         "\nDaemon options:\n"
456         "  --detach                run in background as daemon\n"
457         "  --no-chdir              do not chdir to '/'\n"
458         "  --pidfile[=FILE]        create pidfile (default: %s/%s.pid)\n"
459         "  --overwrite-pidfile     with --pidfile, start even if already "
460                                    "running\n",
461         ovs_rundir, program_name);
462 }
463
464 /* Opens and reads a PID from 'pidfile'.  Returns the nonnegative PID if
465  * successful, otherwise a negative errno value. */
466 pid_t
467 read_pidfile(const char *pidfile)
468 {
469     char line[128];
470     struct flock lck;
471     FILE *file;
472     int error;
473
474     file = fopen(pidfile, "r");
475     if (!file) {
476         error = errno;
477         VLOG_WARN("%s: open: %s", pidfile, strerror(error));
478         goto error;
479     }
480
481     lck.l_type = F_WRLCK;
482     lck.l_whence = SEEK_SET;
483     lck.l_start = 0;
484     lck.l_len = 0;
485     if (fcntl(fileno(file), F_GETLK, &lck)) {
486         error = errno;
487         VLOG_WARN("%s: fcntl: %s", pidfile, strerror(error));
488         goto error;
489     }
490     if (lck.l_type == F_UNLCK) {
491         error = ESRCH;
492         VLOG_WARN("%s: pid file is not locked", pidfile);
493         goto error;
494     }
495
496     if (!fgets(line, sizeof line, file)) {
497         if (ferror(file)) {
498             error = errno;
499             VLOG_WARN("%s: read: %s", pidfile, strerror(error));
500         } else {
501             error = ESRCH;
502             VLOG_WARN("%s: read: unexpected end of file", pidfile);
503         }
504         goto error;
505     }
506
507     if (lck.l_pid != strtoul(line, NULL, 10)) {
508         error = ESRCH;
509         VLOG_WARN("l_pid (%ld) != %s pid (%s)",
510                    (long int) lck.l_pid, pidfile, line);
511         goto error;
512     }
513
514     fclose(file);
515     return lck.l_pid;
516
517 error:
518     if (file) {
519         fclose(file);
520     }
521     return -error;
522 }