2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
24 #include <sys/resource.h>
28 #include "command-line.h"
29 #include "fatal-signal.h"
32 #include "ovs-thread.h"
34 #include "socket-util.h"
39 VLOG_DEFINE_THIS_MODULE(daemon);
41 /* --detach: Should we run in the background? */
42 static bool detach; /* Was --detach specified? */
43 static bool detached; /* Have we already detached? */
45 /* --pidfile: Name of pidfile (null if none). */
48 /* Device and inode of pidfile, so we can avoid reopening it. */
49 static dev_t pidfile_dev;
50 static ino_t pidfile_ino;
52 /* --overwrite-pidfile: Create pidfile even if one already exists and is
54 static bool overwrite_pidfile;
56 /* --no-chdir: Should we chdir to "/"? */
57 static bool chdir_ = true;
59 /* File descriptor used by daemonize_start() and daemonize_complete(). */
60 static int daemonize_fd = -1;
62 /* --monitor: Should a supervisory process monitor the daemon and restart it if
63 * it dies due to an error signal? */
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];
70 static void check_already_running(void);
71 static int lock_pidfile(FILE *, int command);
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. */
76 make_pidfile_name(const char *name)
79 ? xasprintf("%s/%s.pid", ovs_rundir(), program_name)
80 : abs_file_name(ovs_rundir(), name));
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
88 * If 'name' is null, then program_name followed by ".pid" is used. */
90 set_pidfile(const char *name)
92 assert_single_threaded();
94 pidfile = make_pidfile_name(name);
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
106 /* Sets that we do not chdir to "/". */
113 /* Will we chdir to "/" as part of daemonizing? */
115 is_chdir_enabled(void)
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. */
124 ignore_existing_pidfile(void)
126 overwrite_pidfile = true;
129 /* Sets up a following call to daemonize() to detach from the foreground
130 * session, running this process in the background. */
137 /* Will daemonize() really detach? */
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. */
147 daemon_set_monitor(void)
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. */
160 daemon_save_fd(int fd)
162 ovs_assert(fd == STDIN_FILENO ||
163 fd == STDOUT_FILENO ||
164 fd == STDERR_FILENO);
168 /* Unregisters pidfile from being unlinked when the program terminates via
169 * exit() or a fatal signal. */
171 remove_pidfile_from_unlink(void)
174 fatal_signal_remove_file_to_unlink(pidfile);
178 /* Registers pidfile to be unlinked when the program terminates via exit() or a
181 add_pidfile_to_unlink(void)
184 fatal_signal_add_file_to_unlink(pidfile);
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
194 long int pid = getpid();
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);
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);
211 file = fopen(tmpfile, "a+");
213 VLOG_FATAL("%s: create failed (%s)", tmpfile, ovs_strerror(errno));
216 error = lock_pidfile(file, F_SETLK);
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));
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();
232 if (fstat(fileno(file), &s) == -1) {
233 VLOG_FATAL("%s: fstat failed (%s)", tmpfile, ovs_strerror(errno));
236 if (ftruncate(fileno(file), 0) == -1) {
237 VLOG_FATAL("%s: truncate failed (%s)", tmpfile, ovs_strerror(errno));
240 fprintf(file, "%ld\n", pid);
241 if (fflush(file) == EOF) {
242 VLOG_FATAL("%s: write failed (%s)", tmpfile, ovs_strerror(errno));
245 error = rename(tmpfile, pidfile);
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);
252 VLOG_FATAL("failed to rename \"%s\" to \"%s\" (%s)",
253 tmpfile, pidfile, ovs_strerror(errno));
256 /* Ensure that the pidfile will get deleted on exit. */
257 fatal_signal_add_file_to_unlink(pidfile);
261 * We don't close 'file' because its file descriptor must remain open to
263 pidfile_dev = s.st_dev;
264 pidfile_ino = s.st_ino;
268 /* If configured with set_pidfile() or set_detach(), creates the pid file and
269 * detaches from the foreground session. */
274 daemonize_complete();
277 /* Calls fork() and on success returns its return value. On failure, logs an
278 * error and exits unsuccessfully.
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
284 fork_and_clean_up(void)
288 /* Running in parent process. */
291 /* Running in child process. */
300 * - In the parent, waits for the child to signal that it has completed its
301 * startup sequence. Then stores -1 in '*fdp' and returns the child's pid.
303 * - In the child, stores a fd in '*fdp' and returns 0. The caller should
304 * pass the fd to fork_notify_startup() after it finishes its startup
307 * If something goes wrong with the fork, logs a critical error and aborts the
310 fork_and_wait_for_startup(int *fdp)
317 pid = fork_and_clean_up();
319 /* Running in parent process. */
324 if (read_fully(fds[0], &c, 1, &bytes_read) != 0) {
329 retval = waitpid(pid, &status, 0);
330 } while (retval == -1 && errno == EINTR);
333 if (WIFEXITED(status) && WEXITSTATUS(status)) {
334 /* Child exited with an error. Convey the same error
335 * to our parent process as a courtesy. */
336 exit(WEXITSTATUS(status));
338 char *status_msg = process_status_msg(status);
339 VLOG_FATAL("fork child died before signaling startup (%s)",
342 } else if (retval < 0) {
343 VLOG_FATAL("waitpid failed (%s)", ovs_strerror(errno));
351 /* Running in child process. */
360 fork_notify_startup(int fd)
363 size_t bytes_written;
366 error = write_fully(fd, "", 1, &bytes_written);
368 VLOG_FATAL("pipe write failed (%s)", ovs_strerror(error));
376 should_restart(int status)
378 if (WIFSIGNALED(status)) {
379 static const int error_signals[] = {
380 SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGILL, SIGPIPE, SIGSEGV,
386 for (i = 0; i < ARRAY_SIZE(error_signals); i++) {
387 if (error_signals[i] == WTERMSIG(status)) {
396 monitor_daemon(pid_t daemon_pid)
398 /* XXX Should log daemon's stderr output at startup time. */
403 subprogram_name = "monitor";
404 status_msg = xstrdup("healthy");
405 last_restart = TIME_MIN;
411 proctitle_set("monitoring pid %lu (%s)",
412 (unsigned long int) daemon_pid, status_msg);
415 retval = waitpid(daemon_pid, &status, 0);
416 } while (retval == -1 && errno == EINTR);
419 VLOG_FATAL("waitpid failed (%s)", ovs_strerror(errno));
420 } else if (retval == daemon_pid) {
421 char *s = process_status_msg(status);
422 if (should_restart(status)) {
424 status_msg = xasprintf("%d crashes: pid %lu died, %s",
426 (unsigned long int) daemon_pid, s);
429 if (WCOREDUMP(status)) {
430 /* Disable further core dumps to save disk space. */
435 if (setrlimit(RLIMIT_CORE, &r) == -1) {
436 VLOG_WARN("failed to disable core dumps: %s",
437 ovs_strerror(errno));
441 /* Throttle restarts to no more than once every 10 seconds. */
442 if (time(NULL) < last_restart + 10) {
443 VLOG_WARN("%s, waiting until 10 seconds since last "
444 "restart", status_msg);
446 time_t now = time(NULL);
447 time_t wakeup = last_restart + 10;
454 last_restart = time(NULL);
456 VLOG_ERR("%s, restarting", status_msg);
457 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
462 VLOG_INFO("pid %lu died, %s, exiting",
463 (unsigned long int) daemon_pid, s);
471 /* Running in new daemon process. */
473 subprogram_name = "";
476 /* Close standard file descriptors (except any that the client has requested we
477 * leave open by calling daemon_save_fd()). If we're started from e.g. an SSH
478 * session, then this keeps us from holding that session open artificially. */
480 close_standard_fds(void)
482 int null_fd = get_null_fd();
486 for (fd = 0; fd < 3; fd++) {
493 /* Disable logging to stderr to avoid wasting CPU time. */
494 vlog_set_levels(NULL, VLF_CONSOLE, VLL_OFF);
497 /* If daemonization is configured, then starts daemonization, by forking and
498 * returning in the child process. The parent process hangs around until the
499 * child lets it know either that it completed startup successfully (by calling
500 * daemon_complete()) or that it failed to start up (by exiting with a nonzero
503 daemonize_start(void)
505 assert_single_threaded();
509 if (fork_and_wait_for_startup(&daemonize_fd) > 0) {
510 /* Running in parent process. */
514 /* Running in daemon or monitor process. */
519 int saved_daemonize_fd = daemonize_fd;
522 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
523 if (daemon_pid > 0) {
524 /* Running in monitor process. */
525 fork_notify_startup(saved_daemonize_fd);
526 close_standard_fds();
527 monitor_daemon(daemon_pid);
529 /* Running in daemon process. */
536 /* Make sure that the unixctl commands for vlog get registered in a
537 * daemon, even before the first log message. */
541 /* If daemonization is configured, then this function notifies the parent
542 * process that the child process has completed startup successfully. It also
543 * call daemonize_post_detach().
545 * Calling this function more than once has no additional effect. */
547 daemonize_complete(void)
557 fork_notify_startup(daemonize_fd);
559 daemonize_post_detach();
563 /* If daemonization is configured, then this function does traditional Unix
564 * daemonization behavior: join a new session, chdir to the root (if not
565 * disabled), and close the standard file descriptors.
567 * It only makes sense to call this function as part of an implementation of a
568 * special daemon subprocess. A normal daemon should just call
569 * daemonize_complete(). */
571 daemonize_post_detach(void)
577 close_standard_fds();
585 "\nDaemon options:\n"
586 " --detach run in background as daemon\n"
587 " --no-chdir do not chdir to '/'\n"
588 " --pidfile[=FILE] create pidfile (default: %s/%s.pid)\n"
589 " --overwrite-pidfile with --pidfile, start even if already "
591 ovs_rundir(), program_name);
595 lock_pidfile__(FILE *file, int command, struct flock *lck)
599 lck->l_type = F_WRLCK;
600 lck->l_whence = SEEK_SET;
606 error = fcntl(fileno(file), command, lck) == -1 ? errno : 0;
607 } while (error == EINTR);
612 lock_pidfile(FILE *file, int command)
616 return lock_pidfile__(file, command, &lck);
620 read_pidfile__(const char *pidfile, bool delete_if_stale)
628 if ((pidfile_ino || pidfile_dev)
629 && !stat(pidfile, &s)
630 && s.st_ino == pidfile_ino && s.st_dev == pidfile_dev) {
631 /* It's our own pidfile. We can't afford to open it, because closing
632 * *any* fd for a file that a process has locked also releases all the
633 * locks on that file.
635 * Fortunately, we know the associated pid anyhow: */
639 file = fopen(pidfile, "r+");
641 if (errno == ENOENT && delete_if_stale) {
645 VLOG_WARN("%s: open: %s", pidfile, ovs_strerror(error));
649 error = lock_pidfile__(file, F_GETLK, &lck);
651 VLOG_WARN("%s: fcntl: %s", pidfile, ovs_strerror(error));
654 if (lck.l_type == F_UNLCK) {
655 /* pidfile exists but it isn't locked by anyone. We need to delete it
656 * so that a new pidfile can go in its place. But just calling
657 * unlink(pidfile) makes a nasty race: what if someone else unlinks it
658 * before we do and then replaces it by a valid pidfile? We'd unlink
659 * their valid pidfile. We do a little dance to avoid the race, by
660 * locking the invalid pidfile. Only one process can have the invalid
661 * pidfile locked, and only that process has the right to unlink it. */
662 if (!delete_if_stale) {
664 VLOG_DBG("%s: pid file is stale", pidfile);
669 error = lock_pidfile(file, F_SETLK);
671 /* We lost a race with someone else doing the same thing. */
672 VLOG_WARN("%s: lost race to lock pidfile", pidfile);
676 /* Is the file we have locked still named 'pidfile'? */
677 if (stat(pidfile, &s) || fstat(fileno(file), &s2)
678 || s.st_ino != s2.st_ino || s.st_dev != s2.st_dev) {
679 /* No. We lost a race with someone else who got the lock before
680 * us, deleted the pidfile, and closed it (releasing the lock). */
682 VLOG_WARN("%s: lost race to delete pidfile", pidfile);
686 /* We won the right to delete the stale pidfile. */
687 if (unlink(pidfile)) {
689 VLOG_WARN("%s: failed to delete stale pidfile (%s)",
690 pidfile, ovs_strerror(error));
693 VLOG_DBG("%s: deleted stale pidfile", pidfile);
698 if (!fgets(line, sizeof line, file)) {
701 VLOG_WARN("%s: read: %s", pidfile, ovs_strerror(error));
704 VLOG_WARN("%s: read: unexpected end of file", pidfile);
709 if (lck.l_pid != strtoul(line, NULL, 10)) {
710 /* The process that has the pidfile locked is not the process that
711 * created it. It must be stale, with the process that has it locked
712 * preparing to delete it. */
714 VLOG_WARN("%s: stale pidfile for pid %s being deleted by pid %ld",
715 pidfile, line, (long int) lck.l_pid);
729 /* Opens and reads a PID from 'pidfile'. Returns the positive PID if
730 * successful, otherwise a negative errno value. */
732 read_pidfile(const char *pidfile)
734 return read_pidfile__(pidfile, false);
737 /* Checks whether a process with the given 'pidfile' is already running and,
738 * if so, aborts. If 'pidfile' is stale, deletes it. */
740 check_already_running(void)
742 long int pid = read_pidfile__(pidfile, true);
744 VLOG_FATAL("%s: already running as pid %ld, aborting", pidfile, pid);
745 } else if (pid < 0) {
746 VLOG_FATAL("%s: pidfile check failed (%s), aborting",
747 pidfile, ovs_strerror(-pid));