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_unix);
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 static void check_already_running(void);
67 static int lock_pidfile(FILE *, int command);
68 static char *make_pidfile_name(const char *name);
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 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
87 * If 'name' is null, then program_name followed by ".pid" is used. */
89 set_pidfile(const char *name)
91 assert_single_threaded();
93 pidfile = make_pidfile_name(name);
96 /* Sets that we do not chdir to "/". */
103 /* Normally, daemonize() or damonize_start() will terminate the program with a
104 * message if a locked pidfile already exists. If this function is called, an
105 * existing pidfile will be replaced, with a warning. */
107 ignore_existing_pidfile(void)
109 overwrite_pidfile = true;
112 /* Sets up a following call to daemonize() to detach from the foreground
113 * session, running this process in the background. */
120 /* Will daemonize() really detach? */
127 /* Sets up a following call to daemonize() to fork a supervisory process to
128 * monitor the daemon and restart it if it dies due to an error signal. */
130 daemon_set_monitor(void)
135 /* If a pidfile has been configured, creates it and stores the running
136 * process's pid in it. Ensures that the pidfile will be deleted when the
141 long int pid = getpid();
147 /* Create a temporary pidfile. */
148 if (overwrite_pidfile) {
149 tmpfile = xasprintf("%s.tmp%ld", pidfile, pid);
150 fatal_signal_add_file_to_unlink(tmpfile);
152 /* Everyone shares the same file which will be treated as a lock. To
153 * avoid some uncomfortable race conditions, we can't set up the fatal
154 * signal unlink until we've acquired it. */
155 tmpfile = xasprintf("%s.tmp", pidfile);
158 file = fopen(tmpfile, "a+");
160 VLOG_FATAL("%s: create failed (%s)", tmpfile, ovs_strerror(errno));
163 error = lock_pidfile(file, F_SETLK);
165 /* Looks like we failed to acquire the lock. Note that, if we failed
166 * for some other reason (and '!overwrite_pidfile'), we will have
167 * left 'tmpfile' as garbage in the file system. */
168 VLOG_FATAL("%s: fcntl(F_SETLK) failed (%s)", tmpfile,
169 ovs_strerror(error));
172 if (!overwrite_pidfile) {
173 /* We acquired the lock. Make sure to clean up on exit, and verify
174 * that we're allowed to create the actual pidfile. */
175 fatal_signal_add_file_to_unlink(tmpfile);
176 check_already_running();
179 if (fstat(fileno(file), &s) == -1) {
180 VLOG_FATAL("%s: fstat failed (%s)", tmpfile, ovs_strerror(errno));
183 if (ftruncate(fileno(file), 0) == -1) {
184 VLOG_FATAL("%s: truncate failed (%s)", tmpfile, ovs_strerror(errno));
187 fprintf(file, "%ld\n", pid);
188 if (fflush(file) == EOF) {
189 VLOG_FATAL("%s: write failed (%s)", tmpfile, ovs_strerror(errno));
192 error = rename(tmpfile, pidfile);
194 /* Due to a race, 'tmpfile' may be owned by a different process, so we
195 * shouldn't delete it on exit. */
196 fatal_signal_remove_file_to_unlink(tmpfile);
199 VLOG_FATAL("failed to rename \"%s\" to \"%s\" (%s)",
200 tmpfile, pidfile, ovs_strerror(errno));
203 /* Ensure that the pidfile will get deleted on exit. */
204 fatal_signal_add_file_to_unlink(pidfile);
208 * We don't close 'file' because its file descriptor must remain open to
210 pidfile_dev = s.st_dev;
211 pidfile_ino = s.st_ino;
215 /* If configured with set_pidfile() or set_detach(), creates the pid file and
216 * detaches from the foreground session. */
221 daemonize_complete();
224 /* Calls fork() and on success returns its return value. On failure, logs an
225 * error and exits unsuccessfully.
227 * Post-fork, but before returning, this function calls a few other functions
228 * that are generally useful if the child isn't planning to exec a new
231 fork_and_clean_up(void)
235 /* Running in parent process. */
238 /* Running in child process. */
246 * - In the parent, waits for the child to signal that it has completed its
247 * startup sequence. Then stores -1 in '*fdp' and returns the child's pid.
249 * - In the child, stores a fd in '*fdp' and returns 0. The caller should
250 * pass the fd to fork_notify_startup() after it finishes its startup
253 * If something goes wrong with the fork, logs a critical error and aborts the
256 fork_and_wait_for_startup(int *fdp)
263 pid = fork_and_clean_up();
265 /* Running in parent process. */
270 if (read_fully(fds[0], &c, 1, &bytes_read) != 0) {
275 retval = waitpid(pid, &status, 0);
276 } while (retval == -1 && errno == EINTR);
279 if (WIFEXITED(status) && WEXITSTATUS(status)) {
280 /* Child exited with an error. Convey the same error
281 * to our parent process as a courtesy. */
282 exit(WEXITSTATUS(status));
284 char *status_msg = process_status_msg(status);
285 VLOG_FATAL("fork child died before signaling startup (%s)",
288 } else if (retval < 0) {
289 VLOG_FATAL("waitpid failed (%s)", ovs_strerror(errno));
297 /* Running in child process. */
306 fork_notify_startup(int fd)
309 size_t bytes_written;
312 error = write_fully(fd, "", 1, &bytes_written);
314 VLOG_FATAL("pipe write failed (%s)", ovs_strerror(error));
322 should_restart(int status)
324 if (WIFSIGNALED(status)) {
325 static const int error_signals[] = {
326 /* This list of signals is documented in daemon.man. If you
327 * change the list, update the documentation too. */
328 SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGILL, SIGPIPE, SIGSEGV,
334 for (i = 0; i < ARRAY_SIZE(error_signals); i++) {
335 if (error_signals[i] == WTERMSIG(status)) {
344 monitor_daemon(pid_t daemon_pid)
346 /* XXX Should log daemon's stderr output at startup time. */
351 set_subprogram_name("monitor");
352 status_msg = xstrdup("healthy");
353 last_restart = TIME_MIN;
359 proctitle_set("monitoring pid %lu (%s)",
360 (unsigned long int) daemon_pid, status_msg);
363 retval = waitpid(daemon_pid, &status, 0);
364 } while (retval == -1 && errno == EINTR);
367 VLOG_FATAL("waitpid failed (%s)", ovs_strerror(errno));
368 } else if (retval == daemon_pid) {
369 char *s = process_status_msg(status);
370 if (should_restart(status)) {
372 status_msg = xasprintf("%d crashes: pid %lu died, %s",
374 (unsigned long int) daemon_pid, s);
377 if (WCOREDUMP(status)) {
378 /* Disable further core dumps to save disk space. */
383 if (setrlimit(RLIMIT_CORE, &r) == -1) {
384 VLOG_WARN("failed to disable core dumps: %s",
385 ovs_strerror(errno));
389 /* Throttle restarts to no more than once every 10 seconds. */
390 if (time(NULL) < last_restart + 10) {
391 VLOG_WARN("%s, waiting until 10 seconds since last "
392 "restart", status_msg);
394 time_t now = time(NULL);
395 time_t wakeup = last_restart + 10;
399 xsleep(wakeup - now);
402 last_restart = time(NULL);
404 VLOG_ERR("%s, restarting", status_msg);
405 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
410 VLOG_INFO("pid %lu died, %s, exiting",
411 (unsigned long int) daemon_pid, s);
419 /* Running in new daemon process. */
421 set_subprogram_name("");
424 /* If daemonization is configured, then starts daemonization, by forking and
425 * returning in the child process. The parent process hangs around until the
426 * child lets it know either that it completed startup successfully (by calling
427 * daemon_complete()) or that it failed to start up (by exiting with a nonzero
430 daemonize_start(void)
432 assert_single_threaded();
436 if (fork_and_wait_for_startup(&daemonize_fd) > 0) {
437 /* Running in parent process. */
441 /* Running in daemon or monitor process. */
446 int saved_daemonize_fd = daemonize_fd;
449 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
450 if (daemon_pid > 0) {
451 /* Running in monitor process. */
452 fork_notify_startup(saved_daemonize_fd);
453 close_standard_fds();
454 monitor_daemon(daemon_pid);
456 /* Running in daemon process. */
459 forbid_forking("running in daemon process");
465 /* Make sure that the unixctl commands for vlog get registered in a
466 * daemon, even before the first log message. */
470 /* If daemonization is configured, then this function notifies the parent
471 * process that the child process has completed startup successfully. It also
472 * call daemonize_post_detach().
474 * Calling this function more than once has no additional effect. */
476 daemonize_complete(void)
486 fork_notify_startup(daemonize_fd);
488 daemonize_post_detach();
492 /* If daemonization is configured, then this function does traditional Unix
493 * daemonization behavior: join a new session, chdir to the root (if not
494 * disabled), and close the standard file descriptors.
496 * It only makes sense to call this function as part of an implementation of a
497 * special daemon subprocess. A normal daemon should just call
498 * daemonize_complete(). */
500 daemonize_post_detach(void)
506 close_standard_fds();
514 "\nDaemon options:\n"
515 " --detach run in background as daemon\n"
516 " --no-chdir do not chdir to '/'\n"
517 " --pidfile[=FILE] create pidfile (default: %s/%s.pid)\n"
518 " --overwrite-pidfile with --pidfile, start even if already "
520 ovs_rundir(), program_name);
524 lock_pidfile__(FILE *file, int command, struct flock *lck)
528 lck->l_type = F_WRLCK;
529 lck->l_whence = SEEK_SET;
535 error = fcntl(fileno(file), command, lck) == -1 ? errno : 0;
536 } while (error == EINTR);
541 lock_pidfile(FILE *file, int command)
545 return lock_pidfile__(file, command, &lck);
549 read_pidfile__(const char *pidfile, bool delete_if_stale)
557 if ((pidfile_ino || pidfile_dev)
558 && !stat(pidfile, &s)
559 && s.st_ino == pidfile_ino && s.st_dev == pidfile_dev) {
560 /* It's our own pidfile. We can't afford to open it, because closing
561 * *any* fd for a file that a process has locked also releases all the
562 * locks on that file.
564 * Fortunately, we know the associated pid anyhow: */
568 file = fopen(pidfile, "r+");
570 if (errno == ENOENT && delete_if_stale) {
574 VLOG_WARN("%s: open: %s", pidfile, ovs_strerror(error));
578 error = lock_pidfile__(file, F_GETLK, &lck);
580 VLOG_WARN("%s: fcntl: %s", pidfile, ovs_strerror(error));
583 if (lck.l_type == F_UNLCK) {
584 /* pidfile exists but it isn't locked by anyone. We need to delete it
585 * so that a new pidfile can go in its place. But just calling
586 * unlink(pidfile) makes a nasty race: what if someone else unlinks it
587 * before we do and then replaces it by a valid pidfile? We'd unlink
588 * their valid pidfile. We do a little dance to avoid the race, by
589 * locking the invalid pidfile. Only one process can have the invalid
590 * pidfile locked, and only that process has the right to unlink it. */
591 if (!delete_if_stale) {
593 VLOG_DBG("%s: pid file is stale", pidfile);
598 error = lock_pidfile(file, F_SETLK);
600 /* We lost a race with someone else doing the same thing. */
601 VLOG_WARN("%s: lost race to lock pidfile", pidfile);
605 /* Is the file we have locked still named 'pidfile'? */
606 if (stat(pidfile, &s) || fstat(fileno(file), &s2)
607 || s.st_ino != s2.st_ino || s.st_dev != s2.st_dev) {
608 /* No. We lost a race with someone else who got the lock before
609 * us, deleted the pidfile, and closed it (releasing the lock). */
611 VLOG_WARN("%s: lost race to delete pidfile", pidfile);
615 /* We won the right to delete the stale pidfile. */
616 if (unlink(pidfile)) {
618 VLOG_WARN("%s: failed to delete stale pidfile (%s)",
619 pidfile, ovs_strerror(error));
622 VLOG_DBG("%s: deleted stale pidfile", pidfile);
627 if (!fgets(line, sizeof line, file)) {
630 VLOG_WARN("%s: read: %s", pidfile, ovs_strerror(error));
633 VLOG_WARN("%s: read: unexpected end of file", pidfile);
638 if (lck.l_pid != strtoul(line, NULL, 10)) {
639 /* The process that has the pidfile locked is not the process that
640 * created it. It must be stale, with the process that has it locked
641 * preparing to delete it. */
643 VLOG_WARN("%s: stale pidfile for pid %s being deleted by pid %ld",
644 pidfile, line, (long int) lck.l_pid);
658 /* Opens and reads a PID from 'pidfile'. Returns the positive PID if
659 * successful, otherwise a negative errno value. */
661 read_pidfile(const char *pidfile)
663 return read_pidfile__(pidfile, false);
666 /* Checks whether a process with the given 'pidfile' is already running and,
667 * if so, aborts. If 'pidfile' is stale, deletes it. */
669 check_already_running(void)
671 long int pid = read_pidfile__(pidfile, true);
673 VLOG_FATAL("%s: already running as pid %ld, aborting", pidfile, pid);
674 } else if (pid < 0) {
675 VLOG_FATAL("%s: pidfile check failed (%s), aborting",
676 pidfile, ovs_strerror(-pid));
681 /* stub functions for non-windows platform. */
684 service_start(int *argc OVS_UNUSED, char **argv[] OVS_UNUSED)
694 should_service_stop(void)