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