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.
19 #include "daemon-private.h"
25 #include <sys/resource.h>
29 #include "command-line.h"
30 #include "fatal-signal.h"
33 #include "ovs-thread.h"
35 #include "socket-util.h"
40 VLOG_DEFINE_THIS_MODULE(daemon_unix);
42 /* --detach: Should we run in the background? */
43 bool detach; /* Was --detach specified? */
44 static bool detached; /* Have we already detached? */
46 /* --pidfile: Name of pidfile (null if none). */
49 /* Device and inode of pidfile, so we can avoid reopening it. */
50 static dev_t pidfile_dev;
51 static ino_t pidfile_ino;
53 /* --overwrite-pidfile: Create pidfile even if one already exists and is
55 static bool overwrite_pidfile;
57 /* --no-chdir: Should we chdir to "/"? */
58 static bool chdir_ = true;
60 /* File descriptor used by daemonize_start() and daemonize_complete(). */
61 static int daemonize_fd = -1;
63 /* --monitor: Should a supervisory process monitor the daemon and restart it if
64 * it dies due to an error signal? */
67 static void check_already_running(void);
68 static int lock_pidfile(FILE *, int command);
69 static pid_t fork_and_clean_up(void);
70 static void daemonize_post_detach(void);
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. */
75 make_pidfile_name(const char *name)
78 ? xasprintf("%s/%s.pid", ovs_rundir(), program_name)
79 : abs_file_name(ovs_rundir(), name));
82 /* Sets that we do not chdir to "/". */
89 /* Normally, daemonize() or damonize_start() will terminate the program with a
90 * message if a locked pidfile already exists. If this function is called, an
91 * existing pidfile will be replaced, with a warning. */
93 ignore_existing_pidfile(void)
95 overwrite_pidfile = true;
98 /* Sets up a following call to daemonize() to detach from the foreground
99 * session, running this process in the background. */
106 /* Sets up a following call to daemonize() to fork a supervisory process to
107 * monitor the daemon and restart it if it dies due to an error signal. */
109 daemon_set_monitor(void)
114 /* If a pidfile has been configured, creates it and stores the running
115 * process's pid in it. Ensures that the pidfile will be deleted when the
120 long int pid = getpid();
126 /* Create a temporary pidfile. */
127 if (overwrite_pidfile) {
128 tmpfile = xasprintf("%s.tmp%ld", pidfile, pid);
129 fatal_signal_add_file_to_unlink(tmpfile);
131 /* Everyone shares the same file which will be treated as a lock. To
132 * avoid some uncomfortable race conditions, we can't set up the fatal
133 * signal unlink until we've acquired it. */
134 tmpfile = xasprintf("%s.tmp", pidfile);
137 file = fopen(tmpfile, "a+");
139 VLOG_FATAL("%s: create failed (%s)", tmpfile, ovs_strerror(errno));
142 error = lock_pidfile(file, F_SETLK);
144 /* Looks like we failed to acquire the lock. Note that, if we failed
145 * for some other reason (and '!overwrite_pidfile'), we will have
146 * left 'tmpfile' as garbage in the file system. */
147 VLOG_FATAL("%s: fcntl(F_SETLK) failed (%s)", tmpfile,
148 ovs_strerror(error));
151 if (!overwrite_pidfile) {
152 /* We acquired the lock. Make sure to clean up on exit, and verify
153 * that we're allowed to create the actual pidfile. */
154 fatal_signal_add_file_to_unlink(tmpfile);
155 check_already_running();
158 if (fstat(fileno(file), &s) == -1) {
159 VLOG_FATAL("%s: fstat failed (%s)", tmpfile, ovs_strerror(errno));
162 if (ftruncate(fileno(file), 0) == -1) {
163 VLOG_FATAL("%s: truncate failed (%s)", tmpfile, ovs_strerror(errno));
166 fprintf(file, "%ld\n", pid);
167 if (fflush(file) == EOF) {
168 VLOG_FATAL("%s: write failed (%s)", tmpfile, ovs_strerror(errno));
171 error = rename(tmpfile, pidfile);
173 /* Due to a race, 'tmpfile' may be owned by a different process, so we
174 * shouldn't delete it on exit. */
175 fatal_signal_remove_file_to_unlink(tmpfile);
178 VLOG_FATAL("failed to rename \"%s\" to \"%s\" (%s)",
179 tmpfile, pidfile, ovs_strerror(errno));
182 /* Ensure that the pidfile will get deleted on exit. */
183 fatal_signal_add_file_to_unlink(pidfile);
187 * We don't close 'file' because its file descriptor must remain open to
189 pidfile_dev = s.st_dev;
190 pidfile_ino = s.st_ino;
194 /* Calls fork() and on success returns its return value. On failure, logs an
195 * error and exits unsuccessfully.
197 * Post-fork, but before returning, this function calls a few other functions
198 * that are generally useful if the child isn't planning to exec a new
201 fork_and_clean_up(void)
205 /* Running in parent process. */
208 /* Running in child process. */
216 * - In the parent, waits for the child to signal that it has completed its
217 * startup sequence. Then stores -1 in '*fdp' and returns the child's
218 * pid in '*child_pid' argument.
220 * - In the child, stores a fd in '*fdp' and returns 0 through '*child_pid'
221 * argument. The caller should pass the fd to fork_notify_startup() after
222 * it finishes its startup sequence.
224 * Returns 0 on success. If something goes wrong and child process was not
225 * able to signal its readiness by calling fork_notify_startup(), then this
226 * function returns -1. However, even in case of failure it still sets child
227 * process id in '*child_pid'. */
229 fork_and_wait_for_startup(int *fdp, pid_t *child_pid)
237 pid = fork_and_clean_up();
239 /* Running in parent process. */
244 if (read_fully(fds[0], &c, 1, &bytes_read) != 0) {
249 retval = waitpid(pid, &status, 0);
250 } while (retval == -1 && errno == EINTR);
253 if (WIFEXITED(status) && WEXITSTATUS(status)) {
254 /* Child exited with an error. Convey the same error
255 * to our parent process as a courtesy. */
256 exit(WEXITSTATUS(status));
258 char *status_msg = process_status_msg(status);
259 VLOG_ERR("fork child died before signaling startup (%s)",
263 } else if (retval < 0) {
264 VLOG_FATAL("waitpid failed (%s)", ovs_strerror(errno));
272 /* Running in child process. */
281 fork_notify_startup(int fd)
284 size_t bytes_written;
287 error = write_fully(fd, "", 1, &bytes_written);
289 VLOG_FATAL("pipe write failed (%s)", ovs_strerror(error));
297 should_restart(int status)
299 if (WIFSIGNALED(status)) {
300 static const int error_signals[] = {
301 /* This list of signals is documented in daemon.man. If you
302 * change the list, update the documentation too. */
303 SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGILL, SIGPIPE, SIGSEGV,
309 for (i = 0; i < ARRAY_SIZE(error_signals); i++) {
310 if (error_signals[i] == WTERMSIG(status)) {
319 monitor_daemon(pid_t daemon_pid)
321 /* XXX Should log daemon's stderr output at startup time. */
325 bool child_ready = true;
327 set_subprogram_name("monitor");
328 status_msg = xstrdup("healthy");
329 last_restart = TIME_MIN;
335 proctitle_set("monitoring pid %lu (%s)",
336 (unsigned long int) daemon_pid, status_msg);
340 retval = waitpid(daemon_pid, &status, 0);
341 } while (retval == -1 && errno == EINTR);
343 VLOG_FATAL("waitpid failed (%s)", ovs_strerror(errno));
347 if (!child_ready || retval == daemon_pid) {
348 char *s = process_status_msg(status);
349 if (should_restart(status)) {
351 status_msg = xasprintf("%d crashes: pid %lu died, %s",
353 (unsigned long int) daemon_pid, s);
356 if (WCOREDUMP(status)) {
357 /* Disable further core dumps to save disk space. */
362 if (setrlimit(RLIMIT_CORE, &r) == -1) {
363 VLOG_WARN("failed to disable core dumps: %s",
364 ovs_strerror(errno));
368 /* Throttle restarts to no more than once every 10 seconds. */
369 if (time(NULL) < last_restart + 10) {
370 VLOG_WARN("%s, waiting until 10 seconds since last "
371 "restart", status_msg);
373 time_t now = time(NULL);
374 time_t wakeup = last_restart + 10;
378 xsleep(wakeup - now);
381 last_restart = time(NULL);
383 VLOG_ERR("%s, restarting", status_msg);
384 child_ready = !fork_and_wait_for_startup(&daemonize_fd,
386 if (child_ready && !daemon_pid) {
387 /* Child process needs to break out of monitoring
392 VLOG_INFO("pid %lu died, %s, exiting",
393 (unsigned long int) daemon_pid, s);
401 /* Running in new daemon process. */
403 set_subprogram_name("");
406 /* If daemonization is configured, then starts daemonization, by forking and
407 * returning in the child process. The parent process hangs around until the
408 * child lets it know either that it completed startup successfully (by calling
409 * daemon_complete()) or that it failed to start up (by exiting with a nonzero
412 daemonize_start(void)
414 assert_single_threaded();
420 if (fork_and_wait_for_startup(&daemonize_fd, &pid)) {
421 VLOG_FATAL("could not detach from foreground session");
424 /* Running in parent process. */
428 /* Running in daemon or monitor process. */
433 int saved_daemonize_fd = daemonize_fd;
436 if (fork_and_wait_for_startup(&daemonize_fd, &daemon_pid)) {
437 VLOG_FATAL("could not initiate process monitoring");
439 if (daemon_pid > 0) {
440 /* Running in monitor process. */
441 fork_notify_startup(saved_daemonize_fd);
442 close_standard_fds();
443 monitor_daemon(daemon_pid);
445 /* Running in daemon process. */
448 forbid_forking("running in daemon process");
454 /* Make sure that the unixctl commands for vlog get registered in a
455 * daemon, even before the first log message. */
459 /* If daemonization is configured, then this function notifies the parent
460 * process that the child process has completed startup successfully. It also
461 * call daemonize_post_detach().
463 * Calling this function more than once has no additional effect. */
465 daemonize_complete(void)
475 fork_notify_startup(daemonize_fd);
477 daemonize_post_detach();
481 /* If daemonization is configured, then this function does traditional Unix
482 * daemonization behavior: join a new session, chdir to the root (if not
483 * disabled), and close the standard file descriptors.
485 * It only makes sense to call this function as part of an implementation of a
486 * special daemon subprocess. A normal daemon should just call
487 * daemonize_complete(). */
489 daemonize_post_detach(void)
495 close_standard_fds();
503 "\nDaemon options:\n"
504 " --detach run in background as daemon\n"
505 " --no-chdir do not chdir to '/'\n"
506 " --pidfile[=FILE] create pidfile (default: %s/%s.pid)\n"
507 " --overwrite-pidfile with --pidfile, start even if already "
509 ovs_rundir(), program_name);
513 lock_pidfile__(FILE *file, int command, struct flock *lck)
517 lck->l_type = F_WRLCK;
518 lck->l_whence = SEEK_SET;
524 error = fcntl(fileno(file), command, lck) == -1 ? errno : 0;
525 } while (error == EINTR);
530 lock_pidfile(FILE *file, int command)
534 return lock_pidfile__(file, command, &lck);
538 read_pidfile__(const char *pidfile, bool delete_if_stale)
546 if ((pidfile_ino || pidfile_dev)
547 && !stat(pidfile, &s)
548 && s.st_ino == pidfile_ino && s.st_dev == pidfile_dev) {
549 /* It's our own pidfile. We can't afford to open it, because closing
550 * *any* fd for a file that a process has locked also releases all the
551 * locks on that file.
553 * Fortunately, we know the associated pid anyhow: */
557 file = fopen(pidfile, "r+");
559 if (errno == ENOENT && delete_if_stale) {
563 VLOG_WARN("%s: open: %s", pidfile, ovs_strerror(error));
567 error = lock_pidfile__(file, F_GETLK, &lck);
569 VLOG_WARN("%s: fcntl: %s", pidfile, ovs_strerror(error));
572 if (lck.l_type == F_UNLCK) {
573 /* pidfile exists but it isn't locked by anyone. We need to delete it
574 * so that a new pidfile can go in its place. But just calling
575 * unlink(pidfile) makes a nasty race: what if someone else unlinks it
576 * before we do and then replaces it by a valid pidfile? We'd unlink
577 * their valid pidfile. We do a little dance to avoid the race, by
578 * locking the invalid pidfile. Only one process can have the invalid
579 * pidfile locked, and only that process has the right to unlink it. */
580 if (!delete_if_stale) {
582 VLOG_DBG("%s: pid file is stale", pidfile);
587 error = lock_pidfile(file, F_SETLK);
589 /* We lost a race with someone else doing the same thing. */
590 VLOG_WARN("%s: lost race to lock pidfile", pidfile);
594 /* Is the file we have locked still named 'pidfile'? */
595 if (stat(pidfile, &s) || fstat(fileno(file), &s2)
596 || s.st_ino != s2.st_ino || s.st_dev != s2.st_dev) {
597 /* No. We lost a race with someone else who got the lock before
598 * us, deleted the pidfile, and closed it (releasing the lock). */
600 VLOG_WARN("%s: lost race to delete pidfile", pidfile);
604 /* We won the right to delete the stale pidfile. */
605 if (unlink(pidfile)) {
607 VLOG_WARN("%s: failed to delete stale pidfile (%s)",
608 pidfile, ovs_strerror(error));
611 VLOG_DBG("%s: deleted stale pidfile", pidfile);
616 if (!fgets(line, sizeof line, file)) {
619 VLOG_WARN("%s: read: %s", pidfile, ovs_strerror(error));
622 VLOG_WARN("%s: read: unexpected end of file", pidfile);
627 if (lck.l_pid != strtoul(line, NULL, 10)) {
628 /* The process that has the pidfile locked is not the process that
629 * created it. It must be stale, with the process that has it locked
630 * preparing to delete it. */
632 VLOG_WARN("%s: stale pidfile for pid %s being deleted by pid %ld",
633 pidfile, line, (long int) lck.l_pid);
647 /* Opens and reads a PID from 'pidfile'. Returns the positive PID if
648 * successful, otherwise a negative errno value. */
650 read_pidfile(const char *pidfile)
652 return read_pidfile__(pidfile, false);
655 /* Checks whether a process with the given 'pidfile' is already running and,
656 * if so, aborts. If 'pidfile' is stale, deletes it. */
658 check_already_running(void)
660 long int pid = read_pidfile__(pidfile, true);
662 VLOG_FATAL("%s: already running as pid %ld, aborting", pidfile, pid);
663 } else if (pid < 0) {
664 VLOG_FATAL("%s: pidfile check failed (%s), aborting",
665 pidfile, ovs_strerror(-pid));
670 /* stub functions for non-windows platform. */
673 service_start(int *argc OVS_UNUSED, char **argv[] OVS_UNUSED)
683 should_service_stop(void)