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);
72 static char *make_pidfile_name(const char *name);
73 static pid_t fork_and_clean_up(void);
74 static void daemonize_post_detach(void);
76 /* Returns the file name that would be used for a pidfile if 'name' were
77 * provided to set_pidfile(). The caller must free the returned string. */
79 make_pidfile_name(const char *name)
82 ? xasprintf("%s/%s.pid", ovs_rundir(), program_name)
83 : abs_file_name(ovs_rundir(), name));
86 /* Sets up a following call to daemonize() to create a pidfile named 'name'.
87 * If 'name' begins with '/', then it is treated as an absolute path.
88 * Otherwise, it is taken relative to RUNDIR, which is $(prefix)/var/run by
91 * If 'name' is null, then program_name followed by ".pid" is used. */
93 set_pidfile(const char *name)
95 assert_single_threaded();
97 pidfile = make_pidfile_name(name);
100 /* Sets that we do not chdir to "/". */
107 /* Normally, daemonize() or damonize_start() will terminate the program with a
108 * message if a locked pidfile already exists. If this function is called, an
109 * existing pidfile will be replaced, with a warning. */
111 ignore_existing_pidfile(void)
113 overwrite_pidfile = true;
116 /* Sets up a following call to daemonize() to detach from the foreground
117 * session, running this process in the background. */
124 /* Will daemonize() really detach? */
131 /* Sets up a following call to daemonize() to fork a supervisory process to
132 * monitor the daemon and restart it if it dies due to an error signal. */
134 daemon_set_monitor(void)
139 /* A daemon doesn't normally have any use for the file descriptors for stdin,
140 * stdout, and stderr after it detaches. To keep these file descriptors from
141 * e.g. holding an SSH session open, by default detaching replaces each of
142 * these file descriptors by /dev/null. But a few daemons expect the user to
143 * redirect stdout or stderr to a file, in which case it is desirable to keep
144 * these file descriptors. This function, therefore, disables replacing 'fd'
145 * by /dev/null when the daemon detaches. */
147 daemon_save_fd(int fd)
149 ovs_assert(fd == STDIN_FILENO ||
150 fd == STDOUT_FILENO ||
151 fd == STDERR_FILENO);
155 /* If a pidfile has been configured, creates it and stores the running
156 * process's pid in it. Ensures that the pidfile will be deleted when the
161 long int pid = getpid();
167 /* Create a temporary pidfile. */
168 if (overwrite_pidfile) {
169 tmpfile = xasprintf("%s.tmp%ld", pidfile, pid);
170 fatal_signal_add_file_to_unlink(tmpfile);
172 /* Everyone shares the same file which will be treated as a lock. To
173 * avoid some uncomfortable race conditions, we can't set up the fatal
174 * signal unlink until we've acquired it. */
175 tmpfile = xasprintf("%s.tmp", pidfile);
178 file = fopen(tmpfile, "a+");
180 VLOG_FATAL("%s: create failed (%s)", tmpfile, ovs_strerror(errno));
183 error = lock_pidfile(file, F_SETLK);
185 /* Looks like we failed to acquire the lock. Note that, if we failed
186 * for some other reason (and '!overwrite_pidfile'), we will have
187 * left 'tmpfile' as garbage in the file system. */
188 VLOG_FATAL("%s: fcntl(F_SETLK) failed (%s)", tmpfile,
189 ovs_strerror(error));
192 if (!overwrite_pidfile) {
193 /* We acquired the lock. Make sure to clean up on exit, and verify
194 * that we're allowed to create the actual pidfile. */
195 fatal_signal_add_file_to_unlink(tmpfile);
196 check_already_running();
199 if (fstat(fileno(file), &s) == -1) {
200 VLOG_FATAL("%s: fstat failed (%s)", tmpfile, ovs_strerror(errno));
203 if (ftruncate(fileno(file), 0) == -1) {
204 VLOG_FATAL("%s: truncate failed (%s)", tmpfile, ovs_strerror(errno));
207 fprintf(file, "%ld\n", pid);
208 if (fflush(file) == EOF) {
209 VLOG_FATAL("%s: write failed (%s)", tmpfile, ovs_strerror(errno));
212 error = rename(tmpfile, pidfile);
214 /* Due to a race, 'tmpfile' may be owned by a different process, so we
215 * shouldn't delete it on exit. */
216 fatal_signal_remove_file_to_unlink(tmpfile);
219 VLOG_FATAL("failed to rename \"%s\" to \"%s\" (%s)",
220 tmpfile, pidfile, ovs_strerror(errno));
223 /* Ensure that the pidfile will get deleted on exit. */
224 fatal_signal_add_file_to_unlink(pidfile);
228 * We don't close 'file' because its file descriptor must remain open to
230 pidfile_dev = s.st_dev;
231 pidfile_ino = s.st_ino;
235 /* If configured with set_pidfile() or set_detach(), creates the pid file and
236 * detaches from the foreground session. */
241 daemonize_complete();
244 /* Calls fork() and on success returns its return value. On failure, logs an
245 * error and exits unsuccessfully.
247 * Post-fork, but before returning, this function calls a few other functions
248 * that are generally useful if the child isn't planning to exec a new
251 fork_and_clean_up(void)
255 /* Running in parent process. */
258 /* Running in child process. */
266 * - In the parent, waits for the child to signal that it has completed its
267 * startup sequence. Then stores -1 in '*fdp' and returns the child's pid.
269 * - In the child, stores a fd in '*fdp' and returns 0. The caller should
270 * pass the fd to fork_notify_startup() after it finishes its startup
273 * If something goes wrong with the fork, logs a critical error and aborts the
276 fork_and_wait_for_startup(int *fdp)
283 pid = fork_and_clean_up();
285 /* Running in parent process. */
290 if (read_fully(fds[0], &c, 1, &bytes_read) != 0) {
295 retval = waitpid(pid, &status, 0);
296 } while (retval == -1 && errno == EINTR);
299 if (WIFEXITED(status) && WEXITSTATUS(status)) {
300 /* Child exited with an error. Convey the same error
301 * to our parent process as a courtesy. */
302 exit(WEXITSTATUS(status));
304 char *status_msg = process_status_msg(status);
305 VLOG_FATAL("fork child died before signaling startup (%s)",
308 } else if (retval < 0) {
309 VLOG_FATAL("waitpid failed (%s)", ovs_strerror(errno));
317 /* Running in child process. */
326 fork_notify_startup(int fd)
329 size_t bytes_written;
332 error = write_fully(fd, "", 1, &bytes_written);
334 VLOG_FATAL("pipe write failed (%s)", ovs_strerror(error));
342 should_restart(int status)
344 if (WIFSIGNALED(status)) {
345 static const int error_signals[] = {
346 /* This list of signals is documented in daemon.man. If you
347 * change the list, update the documentation too. */
348 SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGILL, SIGPIPE, SIGSEGV,
354 for (i = 0; i < ARRAY_SIZE(error_signals); i++) {
355 if (error_signals[i] == WTERMSIG(status)) {
364 monitor_daemon(pid_t daemon_pid)
366 /* XXX Should log daemon's stderr output at startup time. */
371 set_subprogram_name("monitor");
372 status_msg = xstrdup("healthy");
373 last_restart = TIME_MIN;
379 proctitle_set("monitoring pid %lu (%s)",
380 (unsigned long int) daemon_pid, status_msg);
383 retval = waitpid(daemon_pid, &status, 0);
384 } while (retval == -1 && errno == EINTR);
387 VLOG_FATAL("waitpid failed (%s)", ovs_strerror(errno));
388 } else if (retval == daemon_pid) {
389 char *s = process_status_msg(status);
390 if (should_restart(status)) {
392 status_msg = xasprintf("%d crashes: pid %lu died, %s",
394 (unsigned long int) daemon_pid, s);
397 if (WCOREDUMP(status)) {
398 /* Disable further core dumps to save disk space. */
403 if (setrlimit(RLIMIT_CORE, &r) == -1) {
404 VLOG_WARN("failed to disable core dumps: %s",
405 ovs_strerror(errno));
409 /* Throttle restarts to no more than once every 10 seconds. */
410 if (time(NULL) < last_restart + 10) {
411 VLOG_WARN("%s, waiting until 10 seconds since last "
412 "restart", status_msg);
414 time_t now = time(NULL);
415 time_t wakeup = last_restart + 10;
422 last_restart = time(NULL);
424 VLOG_ERR("%s, restarting", status_msg);
425 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
430 VLOG_INFO("pid %lu died, %s, exiting",
431 (unsigned long int) daemon_pid, s);
439 /* Running in new daemon process. */
441 set_subprogram_name("");
444 /* Close standard file descriptors (except any that the client has requested we
445 * leave open by calling daemon_save_fd()). If we're started from e.g. an SSH
446 * session, then this keeps us from holding that session open artificially. */
448 close_standard_fds(void)
450 int null_fd = get_null_fd();
454 for (fd = 0; fd < 3; fd++) {
461 /* Disable logging to stderr to avoid wasting CPU time. */
462 vlog_set_levels(NULL, VLF_CONSOLE, VLL_OFF);
465 /* If daemonization is configured, then starts daemonization, by forking and
466 * returning in the child process. The parent process hangs around until the
467 * child lets it know either that it completed startup successfully (by calling
468 * daemon_complete()) or that it failed to start up (by exiting with a nonzero
471 daemonize_start(void)
473 assert_single_threaded();
477 if (fork_and_wait_for_startup(&daemonize_fd) > 0) {
478 /* Running in parent process. */
482 /* Running in daemon or monitor process. */
487 int saved_daemonize_fd = daemonize_fd;
490 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
491 if (daemon_pid > 0) {
492 /* Running in monitor process. */
493 fork_notify_startup(saved_daemonize_fd);
494 close_standard_fds();
495 monitor_daemon(daemon_pid);
497 /* Running in daemon process. */
500 forbid_forking("running in daemon process");
506 /* Make sure that the unixctl commands for vlog get registered in a
507 * daemon, even before the first log message. */
511 /* If daemonization is configured, then this function notifies the parent
512 * process that the child process has completed startup successfully. It also
513 * call daemonize_post_detach().
515 * Calling this function more than once has no additional effect. */
517 daemonize_complete(void)
527 fork_notify_startup(daemonize_fd);
529 daemonize_post_detach();
533 /* If daemonization is configured, then this function does traditional Unix
534 * daemonization behavior: join a new session, chdir to the root (if not
535 * disabled), and close the standard file descriptors.
537 * It only makes sense to call this function as part of an implementation of a
538 * special daemon subprocess. A normal daemon should just call
539 * daemonize_complete(). */
541 daemonize_post_detach(void)
547 close_standard_fds();
555 "\nDaemon options:\n"
556 " --detach run in background as daemon\n"
557 " --no-chdir do not chdir to '/'\n"
558 " --pidfile[=FILE] create pidfile (default: %s/%s.pid)\n"
559 " --overwrite-pidfile with --pidfile, start even if already "
561 ovs_rundir(), program_name);
565 lock_pidfile__(FILE *file, int command, struct flock *lck)
569 lck->l_type = F_WRLCK;
570 lck->l_whence = SEEK_SET;
576 error = fcntl(fileno(file), command, lck) == -1 ? errno : 0;
577 } while (error == EINTR);
582 lock_pidfile(FILE *file, int command)
586 return lock_pidfile__(file, command, &lck);
590 read_pidfile__(const char *pidfile, bool delete_if_stale)
598 if ((pidfile_ino || pidfile_dev)
599 && !stat(pidfile, &s)
600 && s.st_ino == pidfile_ino && s.st_dev == pidfile_dev) {
601 /* It's our own pidfile. We can't afford to open it, because closing
602 * *any* fd for a file that a process has locked also releases all the
603 * locks on that file.
605 * Fortunately, we know the associated pid anyhow: */
609 file = fopen(pidfile, "r+");
611 if (errno == ENOENT && delete_if_stale) {
615 VLOG_WARN("%s: open: %s", pidfile, ovs_strerror(error));
619 error = lock_pidfile__(file, F_GETLK, &lck);
621 VLOG_WARN("%s: fcntl: %s", pidfile, ovs_strerror(error));
624 if (lck.l_type == F_UNLCK) {
625 /* pidfile exists but it isn't locked by anyone. We need to delete it
626 * so that a new pidfile can go in its place. But just calling
627 * unlink(pidfile) makes a nasty race: what if someone else unlinks it
628 * before we do and then replaces it by a valid pidfile? We'd unlink
629 * their valid pidfile. We do a little dance to avoid the race, by
630 * locking the invalid pidfile. Only one process can have the invalid
631 * pidfile locked, and only that process has the right to unlink it. */
632 if (!delete_if_stale) {
634 VLOG_DBG("%s: pid file is stale", pidfile);
639 error = lock_pidfile(file, F_SETLK);
641 /* We lost a race with someone else doing the same thing. */
642 VLOG_WARN("%s: lost race to lock pidfile", pidfile);
646 /* Is the file we have locked still named 'pidfile'? */
647 if (stat(pidfile, &s) || fstat(fileno(file), &s2)
648 || s.st_ino != s2.st_ino || s.st_dev != s2.st_dev) {
649 /* No. We lost a race with someone else who got the lock before
650 * us, deleted the pidfile, and closed it (releasing the lock). */
652 VLOG_WARN("%s: lost race to delete pidfile", pidfile);
656 /* We won the right to delete the stale pidfile. */
657 if (unlink(pidfile)) {
659 VLOG_WARN("%s: failed to delete stale pidfile (%s)",
660 pidfile, ovs_strerror(error));
663 VLOG_DBG("%s: deleted stale pidfile", pidfile);
668 if (!fgets(line, sizeof line, file)) {
671 VLOG_WARN("%s: read: %s", pidfile, ovs_strerror(error));
674 VLOG_WARN("%s: read: unexpected end of file", pidfile);
679 if (lck.l_pid != strtoul(line, NULL, 10)) {
680 /* The process that has the pidfile locked is not the process that
681 * created it. It must be stale, with the process that has it locked
682 * preparing to delete it. */
684 VLOG_WARN("%s: stale pidfile for pid %s being deleted by pid %ld",
685 pidfile, line, (long int) lck.l_pid);
699 /* Opens and reads a PID from 'pidfile'. Returns the positive PID if
700 * successful, otherwise a negative errno value. */
702 read_pidfile(const char *pidfile)
704 return read_pidfile__(pidfile, false);
707 /* Checks whether a process with the given 'pidfile' is already running and,
708 * if so, aborts. If 'pidfile' is stale, deletes it. */
710 check_already_running(void)
712 long int pid = read_pidfile__(pidfile, true);
714 VLOG_FATAL("%s: already running as pid %ld, aborting", pidfile, pid);
715 } else if (pid < 0) {
716 VLOG_FATAL("%s: pidfile check failed (%s), aborting",
717 pidfile, ovs_strerror(-pid));
722 /* stub functions for non-windows platform. */
725 service_start(int *argc OVS_UNUSED, char **argv[] OVS_UNUSED)
735 should_service_stop(void)