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