daemon: Start monitor process, not daemon process, in new session.
[cascardo/ovs.git] / lib / daemon.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 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
17 #include <config.h>
18 #include "daemon.h"
19 #include <assert.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <signal.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/resource.h>
26 #include <sys/wait.h>
27 #include <sys/stat.h>
28 #include <unistd.h>
29 #include "command-line.h"
30 #include "fatal-signal.h"
31 #include "dirs.h"
32 #include "lockfile.h"
33 #include "process.h"
34 #include "socket-util.h"
35 #include "timeval.h"
36 #include "util.h"
37 #include "vlog.h"
38
39 VLOG_DEFINE_THIS_MODULE(daemon);
40
41 /* --detach: Should we run in the background? */
42 static bool detach;             /* Was --detach specified? */
43 static bool detached;           /* Have we already detached? */
44
45 /* --pidfile: Name of pidfile (null if none). */
46 static char *pidfile;
47
48 /* Device and inode of pidfile, so we can avoid reopening it. */
49 static dev_t pidfile_dev;
50 static ino_t pidfile_ino;
51
52 /* --overwrite-pidfile: Create pidfile even if one already exists and is
53    locked? */
54 static bool overwrite_pidfile;
55
56 /* --no-chdir: Should we chdir to "/"? */
57 static bool chdir_ = true;
58
59 /* File descriptor used by daemonize_start() and daemonize_complete(). */
60 static int daemonize_fd = -1;
61
62 /* --monitor: Should a supervisory process monitor the daemon and restart it if
63  * it dies due to an error signal? */
64 static bool monitor;
65
66 /* For each of the standard file descriptors, whether to replace it by
67  * /dev/null (if false) or keep it for the daemon to use (if true). */
68 static bool save_fds[3];
69
70 static void check_already_running(void);
71 static int lock_pidfile(FILE *, int command);
72
73 /* Returns the file name that would be used for a pidfile if 'name' were
74  * provided to set_pidfile().  The caller must free the returned string. */
75 char *
76 make_pidfile_name(const char *name)
77 {
78     return (!name
79             ? xasprintf("%s/%s.pid", ovs_rundir(), program_name)
80             : abs_file_name(ovs_rundir(), name));
81 }
82
83 /* Sets up a following call to daemonize() to create a pidfile named 'name'.
84  * If 'name' begins with '/', then it is treated as an absolute path.
85  * Otherwise, it is taken relative to RUNDIR, which is $(prefix)/var/run by
86  * default.
87  *
88  * If 'name' is null, then program_name followed by ".pid" is used. */
89 void
90 set_pidfile(const char *name)
91 {
92     free(pidfile);
93     pidfile = make_pidfile_name(name);
94 }
95
96 /* Returns an absolute path to the configured pidfile, or a null pointer if no
97  * pidfile is configured.  The caller must not modify or free the returned
98  * string. */
99 const char *
100 get_pidfile(void)
101 {
102     return pidfile;
103 }
104
105 /* Sets that we do not chdir to "/". */
106 void
107 set_no_chdir(void)
108 {
109     chdir_ = false;
110 }
111
112 /* Will we chdir to "/" as part of daemonizing? */
113 bool
114 is_chdir_enabled(void)
115 {
116     return chdir_;
117 }
118
119 /* Normally, daemonize() or damonize_start() will terminate the program with a
120  * message if a locked pidfile already exists.  If this function is called, an
121  * existing pidfile will be replaced, with a warning. */
122 void
123 ignore_existing_pidfile(void)
124 {
125     overwrite_pidfile = true;
126 }
127
128 /* Sets up a following call to daemonize() to detach from the foreground
129  * session, running this process in the background.  */
130 void
131 set_detach(void)
132 {
133     detach = true;
134 }
135
136 /* Will daemonize() really detach? */
137 bool
138 get_detach(void)
139 {
140     return detach;
141 }
142
143 /* Sets up a following call to daemonize() to fork a supervisory process to
144  * monitor the daemon and restart it if it dies due to an error signal.  */
145 void
146 daemon_set_monitor(void)
147 {
148     monitor = true;
149 }
150
151 /* A daemon doesn't normally have any use for the file descriptors for stdin,
152  * stdout, and stderr after it detaches.  To keep these file descriptors from
153  * e.g. holding an SSH session open, by default detaching replaces each of
154  * these file descriptors by /dev/null.  But a few daemons expect the user to
155  * redirect stdout or stderr to a file, in which case it is desirable to keep
156  * these file descriptors.  This function, therefore, disables replacing 'fd'
157  * by /dev/null when the daemon detaches. */
158 void
159 daemon_save_fd(int fd)
160 {
161     assert(fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO);
162     save_fds[fd] = true;
163 }
164
165 /* If a pidfile has been configured, creates it and stores the running
166  * process's pid in it.  Ensures that the pidfile will be deleted when the
167  * process exits. */
168 static void
169 make_pidfile(void)
170 {
171     long int pid = getpid();
172     struct stat s;
173     char *tmpfile;
174     FILE *file;
175     int error;
176
177     /* Create a temporary pidfile. */
178     tmpfile = xasprintf("%s.tmp%ld", pidfile, pid);
179     fatal_signal_add_file_to_unlink(tmpfile);
180     file = fopen(tmpfile, "w+");
181     if (!file) {
182         VLOG_FATAL("%s: create failed (%s)", tmpfile, strerror(errno));
183     }
184
185     if (fstat(fileno(file), &s) == -1) {
186         VLOG_FATAL("%s: fstat failed (%s)", tmpfile, strerror(errno));
187     }
188
189     fprintf(file, "%ld\n", pid);
190     if (fflush(file) == EOF) {
191         VLOG_FATAL("%s: write failed (%s)", tmpfile, strerror(errno));
192     }
193
194     error = lock_pidfile(file, F_SETLK);
195     if (error) {
196         VLOG_FATAL("%s: fcntl(F_SETLK) failed (%s)", tmpfile, strerror(error));
197     }
198
199     /* Rename or link it to the correct name. */
200     if (overwrite_pidfile) {
201         if (rename(tmpfile, pidfile) < 0) {
202             VLOG_FATAL("failed to rename \"%s\" to \"%s\" (%s)",
203                        tmpfile, pidfile, strerror(errno));
204         }
205     } else {
206         do {
207             error = link(tmpfile, pidfile) == -1 ? errno : 0;
208             if (error == EEXIST) {
209                 check_already_running();
210             }
211         } while (error == EINTR || error == EEXIST);
212         if (error) {
213             VLOG_FATAL("failed to link \"%s\" as \"%s\" (%s)",
214                        tmpfile, pidfile, strerror(error));
215         }
216     }
217
218     /* Ensure that the pidfile will get deleted on exit. */
219     fatal_signal_add_file_to_unlink(pidfile);
220
221     /* Delete the temporary pidfile if it still exists. */
222     if (!overwrite_pidfile) {
223         error = fatal_signal_unlink_file_now(tmpfile);
224         if (error) {
225             VLOG_FATAL("%s: unlink failed (%s)", tmpfile, strerror(error));
226         }
227     }
228
229     /* Clean up.
230      *
231      * We don't close 'file' because its file descriptor must remain open to
232      * hold the lock. */
233     pidfile_dev = s.st_dev;
234     pidfile_ino = s.st_ino;
235     free(tmpfile);
236     free(pidfile);
237     pidfile = NULL;
238 }
239
240 /* If configured with set_pidfile() or set_detach(), creates the pid file and
241  * detaches from the foreground session.  */
242 void
243 daemonize(void)
244 {
245     daemonize_start();
246     daemonize_complete();
247 }
248
249 /* Calls fork() and on success returns its return value.  On failure, logs an
250  * error and exits unsuccessfully.
251  *
252  * Post-fork, but before returning, this function calls a few other functions
253  * that are generally useful if the child isn't planning to exec a new
254  * process. */
255 pid_t
256 fork_and_clean_up(void)
257 {
258     pid_t pid;
259
260     pid = fork();
261     if (pid > 0) {
262         /* Running in parent process. */
263         fatal_signal_fork();
264     } else if (!pid) {
265         /* Running in child process. */
266         time_postfork();
267         lockfile_postfork();
268     } else {
269         VLOG_FATAL("fork failed (%s)", strerror(errno));
270     }
271
272     return pid;
273 }
274
275 /* Forks, then:
276  *
277  *   - In the parent, waits for the child to signal that it has completed its
278  *     startup sequence.  Then stores -1 in '*fdp' and returns the child's pid.
279  *
280  *   - In the child, stores a fd in '*fdp' and returns 0.  The caller should
281  *     pass the fd to fork_notify_startup() after it finishes its startup
282  *     sequence.
283  *
284  * If something goes wrong with the fork, logs a critical error and aborts the
285  * process. */
286 static pid_t
287 fork_and_wait_for_startup(int *fdp)
288 {
289     int fds[2];
290     pid_t pid;
291
292     xpipe(fds);
293
294     pid = fork_and_clean_up();
295     if (pid > 0) {
296         /* Running in parent process. */
297         size_t bytes_read;
298         char c;
299
300         close(fds[1]);
301         if (read_fully(fds[0], &c, 1, &bytes_read) != 0) {
302             int retval;
303             int status;
304
305             do {
306                 retval = waitpid(pid, &status, 0);
307             } while (retval == -1 && errno == EINTR);
308
309             if (retval == pid) {
310                 if (WIFEXITED(status) && WEXITSTATUS(status)) {
311                     /* Child exited with an error.  Convey the same error
312                      * to our parent process as a courtesy. */
313                     exit(WEXITSTATUS(status));
314                 } else {
315                     char *status_msg = process_status_msg(status);
316                     VLOG_FATAL("fork child died before signaling startup (%s)",
317                                status_msg);
318                 }
319             } else if (retval < 0) {
320                 VLOG_FATAL("waitpid failed (%s)", strerror(errno));
321             } else {
322                 NOT_REACHED();
323             }
324         }
325         close(fds[0]);
326         *fdp = -1;
327     } else if (!pid) {
328         /* Running in child process. */
329         close(fds[0]);
330         *fdp = fds[1];
331     }
332
333     return pid;
334 }
335
336 static void
337 fork_notify_startup(int fd)
338 {
339     if (fd != -1) {
340         size_t bytes_written;
341         int error;
342
343         error = write_fully(fd, "", 1, &bytes_written);
344         if (error) {
345             VLOG_FATAL("pipe write failed (%s)", strerror(error));
346         }
347
348         close(fd);
349     }
350 }
351
352 static bool
353 should_restart(int status)
354 {
355     if (WIFSIGNALED(status)) {
356         static const int error_signals[] = {
357             SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGILL, SIGPIPE, SIGSEGV,
358             SIGXCPU, SIGXFSZ
359         };
360
361         size_t i;
362
363         for (i = 0; i < ARRAY_SIZE(error_signals); i++) {
364             if (error_signals[i] == WTERMSIG(status)) {
365                 return true;
366             }
367         }
368     }
369     return false;
370 }
371
372 static void
373 monitor_daemon(pid_t daemon_pid)
374 {
375     /* XXX Should log daemon's stderr output at startup time. */
376     time_t last_restart;
377     char *status_msg;
378     int crashes;
379
380     subprogram_name = "monitor";
381     status_msg = xstrdup("healthy");
382     last_restart = TIME_MIN;
383     crashes = 0;
384     for (;;) {
385         int retval;
386         int status;
387
388         proctitle_set("monitoring pid %lu (%s)",
389                       (unsigned long int) daemon_pid, status_msg);
390
391         do {
392             retval = waitpid(daemon_pid, &status, 0);
393         } while (retval == -1 && errno == EINTR);
394
395         if (retval == -1) {
396             VLOG_FATAL("waitpid failed (%s)", strerror(errno));
397         } else if (retval == daemon_pid) {
398             char *s = process_status_msg(status);
399             if (should_restart(status)) {
400                 free(status_msg);
401                 status_msg = xasprintf("%d crashes: pid %lu died, %s",
402                                        ++crashes,
403                                        (unsigned long int) daemon_pid, s);
404                 free(s);
405
406                 if (WCOREDUMP(status)) {
407                     /* Disable further core dumps to save disk space. */
408                     struct rlimit r;
409
410                     r.rlim_cur = 0;
411                     r.rlim_max = 0;
412                     if (setrlimit(RLIMIT_CORE, &r) == -1) {
413                         VLOG_WARN("failed to disable core dumps: %s",
414                                   strerror(errno));
415                     }
416                 }
417
418                 /* Throttle restarts to no more than once every 10 seconds. */
419                 if (time(NULL) < last_restart + 10) {
420                     VLOG_WARN("%s, waiting until 10 seconds since last "
421                               "restart", status_msg);
422                     for (;;) {
423                         time_t now = time(NULL);
424                         time_t wakeup = last_restart + 10;
425                         if (now >= wakeup) {
426                             break;
427                         }
428                         sleep(wakeup - now);
429                     }
430                 }
431                 last_restart = time(NULL);
432
433                 VLOG_ERR("%s, restarting", status_msg);
434                 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
435                 if (!daemon_pid) {
436                     break;
437                 }
438             } else {
439                 VLOG_INFO("pid %lu died, %s, exiting",
440                           (unsigned long int) daemon_pid, s);
441                 free(s);
442                 exit(0);
443             }
444         }
445     }
446     free(status_msg);
447
448     /* Running in new daemon process. */
449     proctitle_restore();
450     subprogram_name = "";
451 }
452
453 /* Close standard file descriptors (except any that the client has requested we
454  * leave open by calling daemon_save_fd()).  If we're started from e.g. an SSH
455  * session, then this keeps us from holding that session open artificially. */
456 static void
457 close_standard_fds(void)
458 {
459     int null_fd = get_null_fd();
460     if (null_fd >= 0) {
461         int fd;
462
463         for (fd = 0; fd < 3; fd++) {
464             if (!save_fds[fd]) {
465                 dup2(null_fd, fd);
466             }
467         }
468     }
469
470     /* Disable logging to stderr to avoid wasting CPU time. */
471     vlog_set_levels(NULL, VLF_CONSOLE, VLL_OFF);
472 }
473
474 /* If daemonization is configured, then starts daemonization, by forking and
475  * returning in the child process.  The parent process hangs around until the
476  * child lets it know either that it completed startup successfully (by calling
477  * daemon_complete()) or that it failed to start up (by exiting with a nonzero
478  * exit code). */
479 void
480 daemonize_start(void)
481 {
482     daemonize_fd = -1;
483
484     if (detach) {
485         if (fork_and_wait_for_startup(&daemonize_fd) > 0) {
486             /* Running in parent process. */
487             exit(0);
488         }
489
490         /* Running in daemon or monitor process. */
491         setsid();
492     }
493
494     if (monitor) {
495         int saved_daemonize_fd = daemonize_fd;
496         pid_t daemon_pid;
497
498         daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
499         if (daemon_pid > 0) {
500             /* Running in monitor process. */
501             fork_notify_startup(saved_daemonize_fd);
502             close_standard_fds();
503             monitor_daemon(daemon_pid);
504         }
505         /* Running in daemon process. */
506     }
507
508     if (pidfile) {
509         make_pidfile();
510     }
511
512     /* Make sure that the unixctl commands for vlog get registered in a
513      * daemon, even before the first log message. */
514     vlog_init();
515 }
516
517 /* If daemonization is configured, then this function notifies the parent
518  * process that the child process has completed startup successfully.  It also
519  * call daemonize_post_detach().
520  *
521  * Calling this function more than once has no additional effect. */
522 void
523 daemonize_complete(void)
524 {
525     if (!detached) {
526         detached = true;
527
528         fork_notify_startup(daemonize_fd);
529         daemonize_fd = -1;
530         daemonize_post_detach();
531     }
532 }
533
534 /* If daemonization is configured, then this function does traditional Unix
535  * daemonization behavior: join a new session, chdir to the root (if not
536  * disabled), and close the standard file descriptors.
537  *
538  * It only makes sense to call this function as part of an implementation of a
539  * special daemon subprocess.  A normal daemon should just call
540  * daemonize_complete(). */
541 void
542 daemonize_post_detach(void)
543 {
544     if (detach) {
545         if (chdir_) {
546             ignore(chdir("/"));
547         }
548         close_standard_fds();
549     }
550 }
551
552 void
553 daemon_usage(void)
554 {
555     printf(
556         "\nDaemon options:\n"
557         "  --detach                run in background as daemon\n"
558         "  --no-chdir              do not chdir to '/'\n"
559         "  --pidfile[=FILE]        create pidfile (default: %s/%s.pid)\n"
560         "  --overwrite-pidfile     with --pidfile, start even if already "
561                                    "running\n",
562         ovs_rundir(), program_name);
563 }
564
565 static int
566 lock_pidfile__(FILE *file, int command, struct flock *lck)
567 {
568     int error;
569
570     lck->l_type = F_WRLCK;
571     lck->l_whence = SEEK_SET;
572     lck->l_start = 0;
573     lck->l_len = 0;
574     lck->l_pid = 0;
575
576     do {
577         error = fcntl(fileno(file), command, lck) == -1 ? errno : 0;
578     } while (error == EINTR);
579     return error;
580 }
581
582 static int
583 lock_pidfile(FILE *file, int command)
584 {
585     struct flock lck;
586
587     return lock_pidfile__(file, command, &lck);
588 }
589
590 static pid_t
591 read_pidfile__(const char *pidfile, bool delete_if_stale)
592 {
593     struct stat s, s2;
594     struct flock lck;
595     char line[128];
596     FILE *file;
597     int error;
598
599     if ((pidfile_ino || pidfile_dev)
600         && !stat(pidfile, &s)
601         && s.st_ino == pidfile_ino && s.st_dev == pidfile_dev) {
602         /* It's our own pidfile.  We can't afford to open it, because closing
603          * *any* fd for a file that a process has locked also releases all the
604          * locks on that file.
605          *
606          * Fortunately, we know the associated pid anyhow: */
607         return getpid();
608     }
609
610     file = fopen(pidfile, "r+");
611     if (!file) {
612         if (errno == ENOENT && delete_if_stale) {
613             return 0;
614         }
615         error = errno;
616         VLOG_WARN("%s: open: %s", pidfile, strerror(error));
617         goto error;
618     }
619
620     error = lock_pidfile__(file, F_GETLK, &lck);
621     if (error) {
622         VLOG_WARN("%s: fcntl: %s", pidfile, strerror(error));
623         goto error;
624     }
625     if (lck.l_type == F_UNLCK) {
626         /* pidfile exists but it isn't locked by anyone.  We need to delete it
627          * so that a new pidfile can go in its place.  But just calling
628          * unlink(pidfile) makes a nasty race: what if someone else unlinks it
629          * before we do and then replaces it by a valid pidfile?  We'd unlink
630          * their valid pidfile.  We do a little dance to avoid the race, by
631          * locking the invalid pidfile.  Only one process can have the invalid
632          * pidfile locked, and only that process has the right to unlink it. */
633         if (!delete_if_stale) {
634             error = ESRCH;
635             VLOG_DBG("%s: pid file is stale", pidfile);
636             goto error;
637         }
638
639         /* Get the lock. */
640         error = lock_pidfile(file, F_SETLK);
641         if (error) {
642             /* We lost a race with someone else doing the same thing. */
643             VLOG_WARN("%s: lost race to lock pidfile", pidfile);
644             goto error;
645         }
646
647         /* Is the file we have locked still named 'pidfile'? */
648         if (stat(pidfile, &s) || fstat(fileno(file), &s2)
649             || s.st_ino != s2.st_ino || s.st_dev != s2.st_dev) {
650             /* No.  We lost a race with someone else who got the lock before
651              * us, deleted the pidfile, and closed it (releasing the lock). */
652             error = EALREADY;
653             VLOG_WARN("%s: lost race to delete pidfile", pidfile);
654             goto error;
655         }
656
657         /* We won the right to delete the stale pidfile. */
658         if (unlink(pidfile)) {
659             error = errno;
660             VLOG_WARN("%s: failed to delete stale pidfile (%s)",
661                       pidfile, strerror(error));
662             goto error;
663         }
664         VLOG_DBG("%s: deleted stale pidfile", pidfile);
665         fclose(file);
666         return 0;
667     }
668
669     if (!fgets(line, sizeof line, file)) {
670         if (ferror(file)) {
671             error = errno;
672             VLOG_WARN("%s: read: %s", pidfile, strerror(error));
673         } else {
674             error = ESRCH;
675             VLOG_WARN("%s: read: unexpected end of file", pidfile);
676         }
677         goto error;
678     }
679
680     if (lck.l_pid != strtoul(line, NULL, 10)) {
681         /* The process that has the pidfile locked is not the process that
682          * created it.  It must be stale, with the process that has it locked
683          * preparing to delete it. */
684         error = ESRCH;
685         VLOG_WARN("%s: stale pidfile for pid %s being deleted by pid %ld",
686                   pidfile, line, (long int) lck.l_pid);
687         goto error;
688     }
689
690     fclose(file);
691     return lck.l_pid;
692
693 error:
694     if (file) {
695         fclose(file);
696     }
697     return -error;
698 }
699
700 /* Opens and reads a PID from 'pidfile'.  Returns the positive PID if
701  * successful, otherwise a negative errno value. */
702 pid_t
703 read_pidfile(const char *pidfile)
704 {
705     return read_pidfile__(pidfile, false);
706 }
707
708 /* Checks whether a process with the given 'pidfile' is already running and,
709  * if so, aborts.  If 'pidfile' is stale, deletes it. */
710 static void
711 check_already_running(void)
712 {
713     long int pid = read_pidfile__(pidfile, true);
714     if (pid > 0) {
715         VLOG_FATAL("%s: already running as pid %ld, aborting", pidfile, pid);
716     } else if (pid < 0) {
717         VLOG_FATAL("%s: pidfile check failed (%s), aborting",
718                    pidfile, strerror(-pid));
719     }
720 }