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 pid.
219 * - In the child, stores a fd in '*fdp' and returns 0. The caller should
220 * pass the fd to fork_notify_startup() after it finishes its startup
223 * If something goes wrong with the fork, logs a critical error and aborts the
226 fork_and_wait_for_startup(int *fdp)
233 pid = fork_and_clean_up();
235 /* Running in parent process. */
240 if (read_fully(fds[0], &c, 1, &bytes_read) != 0) {
245 retval = waitpid(pid, &status, 0);
246 } while (retval == -1 && errno == EINTR);
249 if (WIFEXITED(status) && WEXITSTATUS(status)) {
250 /* Child exited with an error. Convey the same error
251 * to our parent process as a courtesy. */
252 exit(WEXITSTATUS(status));
254 char *status_msg = process_status_msg(status);
255 VLOG_FATAL("fork child died before signaling startup (%s)",
258 } else if (retval < 0) {
259 VLOG_FATAL("waitpid failed (%s)", ovs_strerror(errno));
267 /* Running in child process. */
276 fork_notify_startup(int fd)
279 size_t bytes_written;
282 error = write_fully(fd, "", 1, &bytes_written);
284 VLOG_FATAL("pipe write failed (%s)", ovs_strerror(error));
292 should_restart(int status)
294 if (WIFSIGNALED(status)) {
295 static const int error_signals[] = {
296 /* This list of signals is documented in daemon.man. If you
297 * change the list, update the documentation too. */
298 SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGILL, SIGPIPE, SIGSEGV,
304 for (i = 0; i < ARRAY_SIZE(error_signals); i++) {
305 if (error_signals[i] == WTERMSIG(status)) {
314 monitor_daemon(pid_t daemon_pid)
316 /* XXX Should log daemon's stderr output at startup time. */
321 set_subprogram_name("monitor");
322 status_msg = xstrdup("healthy");
323 last_restart = TIME_MIN;
329 proctitle_set("monitoring pid %lu (%s)",
330 (unsigned long int) daemon_pid, status_msg);
333 retval = waitpid(daemon_pid, &status, 0);
334 } while (retval == -1 && errno == EINTR);
337 VLOG_FATAL("waitpid failed (%s)", ovs_strerror(errno));
338 } else if (retval == daemon_pid) {
339 char *s = process_status_msg(status);
340 if (should_restart(status)) {
342 status_msg = xasprintf("%d crashes: pid %lu died, %s",
344 (unsigned long int) daemon_pid, s);
347 if (WCOREDUMP(status)) {
348 /* Disable further core dumps to save disk space. */
353 if (setrlimit(RLIMIT_CORE, &r) == -1) {
354 VLOG_WARN("failed to disable core dumps: %s",
355 ovs_strerror(errno));
359 /* Throttle restarts to no more than once every 10 seconds. */
360 if (time(NULL) < last_restart + 10) {
361 VLOG_WARN("%s, waiting until 10 seconds since last "
362 "restart", status_msg);
364 time_t now = time(NULL);
365 time_t wakeup = last_restart + 10;
369 xsleep(wakeup - now);
372 last_restart = time(NULL);
374 VLOG_ERR("%s, restarting", status_msg);
375 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
380 VLOG_INFO("pid %lu died, %s, exiting",
381 (unsigned long int) daemon_pid, s);
389 /* Running in new daemon process. */
391 set_subprogram_name("");
394 /* If daemonization is configured, then starts daemonization, by forking and
395 * returning in the child process. The parent process hangs around until the
396 * child lets it know either that it completed startup successfully (by calling
397 * daemon_complete()) or that it failed to start up (by exiting with a nonzero
400 daemonize_start(void)
402 assert_single_threaded();
406 if (fork_and_wait_for_startup(&daemonize_fd) > 0) {
407 /* Running in parent process. */
411 /* Running in daemon or monitor process. */
416 int saved_daemonize_fd = daemonize_fd;
419 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
420 if (daemon_pid > 0) {
421 /* Running in monitor process. */
422 fork_notify_startup(saved_daemonize_fd);
423 close_standard_fds();
424 monitor_daemon(daemon_pid);
426 /* Running in daemon process. */
429 forbid_forking("running in daemon process");
435 /* Make sure that the unixctl commands for vlog get registered in a
436 * daemon, even before the first log message. */
440 /* If daemonization is configured, then this function notifies the parent
441 * process that the child process has completed startup successfully. It also
442 * call daemonize_post_detach().
444 * Calling this function more than once has no additional effect. */
446 daemonize_complete(void)
456 fork_notify_startup(daemonize_fd);
458 daemonize_post_detach();
462 /* If daemonization is configured, then this function does traditional Unix
463 * daemonization behavior: join a new session, chdir to the root (if not
464 * disabled), and close the standard file descriptors.
466 * It only makes sense to call this function as part of an implementation of a
467 * special daemon subprocess. A normal daemon should just call
468 * daemonize_complete(). */
470 daemonize_post_detach(void)
476 close_standard_fds();
484 "\nDaemon options:\n"
485 " --detach run in background as daemon\n"
486 " --no-chdir do not chdir to '/'\n"
487 " --pidfile[=FILE] create pidfile (default: %s/%s.pid)\n"
488 " --overwrite-pidfile with --pidfile, start even if already "
490 ovs_rundir(), program_name);
494 lock_pidfile__(FILE *file, int command, struct flock *lck)
498 lck->l_type = F_WRLCK;
499 lck->l_whence = SEEK_SET;
505 error = fcntl(fileno(file), command, lck) == -1 ? errno : 0;
506 } while (error == EINTR);
511 lock_pidfile(FILE *file, int command)
515 return lock_pidfile__(file, command, &lck);
519 read_pidfile__(const char *pidfile, bool delete_if_stale)
527 if ((pidfile_ino || pidfile_dev)
528 && !stat(pidfile, &s)
529 && s.st_ino == pidfile_ino && s.st_dev == pidfile_dev) {
530 /* It's our own pidfile. We can't afford to open it, because closing
531 * *any* fd for a file that a process has locked also releases all the
532 * locks on that file.
534 * Fortunately, we know the associated pid anyhow: */
538 file = fopen(pidfile, "r+");
540 if (errno == ENOENT && delete_if_stale) {
544 VLOG_WARN("%s: open: %s", pidfile, ovs_strerror(error));
548 error = lock_pidfile__(file, F_GETLK, &lck);
550 VLOG_WARN("%s: fcntl: %s", pidfile, ovs_strerror(error));
553 if (lck.l_type == F_UNLCK) {
554 /* pidfile exists but it isn't locked by anyone. We need to delete it
555 * so that a new pidfile can go in its place. But just calling
556 * unlink(pidfile) makes a nasty race: what if someone else unlinks it
557 * before we do and then replaces it by a valid pidfile? We'd unlink
558 * their valid pidfile. We do a little dance to avoid the race, by
559 * locking the invalid pidfile. Only one process can have the invalid
560 * pidfile locked, and only that process has the right to unlink it. */
561 if (!delete_if_stale) {
563 VLOG_DBG("%s: pid file is stale", pidfile);
568 error = lock_pidfile(file, F_SETLK);
570 /* We lost a race with someone else doing the same thing. */
571 VLOG_WARN("%s: lost race to lock pidfile", pidfile);
575 /* Is the file we have locked still named 'pidfile'? */
576 if (stat(pidfile, &s) || fstat(fileno(file), &s2)
577 || s.st_ino != s2.st_ino || s.st_dev != s2.st_dev) {
578 /* No. We lost a race with someone else who got the lock before
579 * us, deleted the pidfile, and closed it (releasing the lock). */
581 VLOG_WARN("%s: lost race to delete pidfile", pidfile);
585 /* We won the right to delete the stale pidfile. */
586 if (unlink(pidfile)) {
588 VLOG_WARN("%s: failed to delete stale pidfile (%s)",
589 pidfile, ovs_strerror(error));
592 VLOG_DBG("%s: deleted stale pidfile", pidfile);
597 if (!fgets(line, sizeof line, file)) {
600 VLOG_WARN("%s: read: %s", pidfile, ovs_strerror(error));
603 VLOG_WARN("%s: read: unexpected end of file", pidfile);
608 if (lck.l_pid != strtoul(line, NULL, 10)) {
609 /* The process that has the pidfile locked is not the process that
610 * created it. It must be stale, with the process that has it locked
611 * preparing to delete it. */
613 VLOG_WARN("%s: stale pidfile for pid %s being deleted by pid %ld",
614 pidfile, line, (long int) lck.l_pid);
628 /* Opens and reads a PID from 'pidfile'. Returns the positive PID if
629 * successful, otherwise a negative errno value. */
631 read_pidfile(const char *pidfile)
633 return read_pidfile__(pidfile, false);
636 /* Checks whether a process with the given 'pidfile' is already running and,
637 * if so, aborts. If 'pidfile' is stale, deletes it. */
639 check_already_running(void)
641 long int pid = read_pidfile__(pidfile, true);
643 VLOG_FATAL("%s: already running as pid %ld, aborting", pidfile, pid);
644 } else if (pid < 0) {
645 VLOG_FATAL("%s: pidfile check failed (%s), aborting",
646 pidfile, ovs_strerror(-pid));
651 /* stub functions for non-windows platform. */
654 service_start(int *argc OVS_UNUSED, char **argv[] OVS_UNUSED)
664 should_service_stop(void)