]>
git.proxmox.com Git - mirror_ovs.git/blob - lib/daemon.c
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;
419 xsleep(wakeup
- now
);
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 /* Returns a readable and writable fd for /dev/null, if successful, otherwise
445 * a negative errno value. The caller must not close the returned fd (because
446 * the same fd will be handed out to subsequent callers). */
453 null_fd
= open("/dev/null", O_RDWR
);
456 VLOG_ERR("could not open /dev/null: %s", ovs_strerror(error
));
464 /* Close standard file descriptors (except any that the client has requested we
465 * leave open by calling daemon_save_fd()). If we're started from e.g. an SSH
466 * session, then this keeps us from holding that session open artificially. */
468 close_standard_fds(void)
470 int null_fd
= get_null_fd();
474 for (fd
= 0; fd
< 3; fd
++) {
481 /* Disable logging to stderr to avoid wasting CPU time. */
482 vlog_set_levels(NULL
, VLF_CONSOLE
, VLL_OFF
);
485 /* If daemonization is configured, then starts daemonization, by forking and
486 * returning in the child process. The parent process hangs around until the
487 * child lets it know either that it completed startup successfully (by calling
488 * daemon_complete()) or that it failed to start up (by exiting with a nonzero
491 daemonize_start(void)
493 assert_single_threaded();
497 if (fork_and_wait_for_startup(&daemonize_fd
) > 0) {
498 /* Running in parent process. */
502 /* Running in daemon or monitor process. */
507 int saved_daemonize_fd
= daemonize_fd
;
510 daemon_pid
= fork_and_wait_for_startup(&daemonize_fd
);
511 if (daemon_pid
> 0) {
512 /* Running in monitor process. */
513 fork_notify_startup(saved_daemonize_fd
);
514 close_standard_fds();
515 monitor_daemon(daemon_pid
);
517 /* Running in daemon process. */
520 forbid_forking("running in daemon process");
526 /* Make sure that the unixctl commands for vlog get registered in a
527 * daemon, even before the first log message. */
531 /* If daemonization is configured, then this function notifies the parent
532 * process that the child process has completed startup successfully. It also
533 * call daemonize_post_detach().
535 * Calling this function more than once has no additional effect. */
537 daemonize_complete(void)
547 fork_notify_startup(daemonize_fd
);
549 daemonize_post_detach();
553 /* If daemonization is configured, then this function does traditional Unix
554 * daemonization behavior: join a new session, chdir to the root (if not
555 * disabled), and close the standard file descriptors.
557 * It only makes sense to call this function as part of an implementation of a
558 * special daemon subprocess. A normal daemon should just call
559 * daemonize_complete(). */
561 daemonize_post_detach(void)
567 close_standard_fds();
575 "\nDaemon options:\n"
576 " --detach run in background as daemon\n"
577 " --no-chdir do not chdir to '/'\n"
578 " --pidfile[=FILE] create pidfile (default: %s/%s.pid)\n"
579 " --overwrite-pidfile with --pidfile, start even if already "
581 ovs_rundir(), program_name
);
585 lock_pidfile__(FILE *file
, int command
, struct flock
*lck
)
589 lck
->l_type
= F_WRLCK
;
590 lck
->l_whence
= SEEK_SET
;
596 error
= fcntl(fileno(file
), command
, lck
) == -1 ? errno
: 0;
597 } while (error
== EINTR
);
602 lock_pidfile(FILE *file
, int command
)
606 return lock_pidfile__(file
, command
, &lck
);
610 read_pidfile__(const char *pidfile
, bool delete_if_stale
)
618 if ((pidfile_ino
|| pidfile_dev
)
619 && !stat(pidfile
, &s
)
620 && s
.st_ino
== pidfile_ino
&& s
.st_dev
== pidfile_dev
) {
621 /* It's our own pidfile. We can't afford to open it, because closing
622 * *any* fd for a file that a process has locked also releases all the
623 * locks on that file.
625 * Fortunately, we know the associated pid anyhow: */
629 file
= fopen(pidfile
, "r+");
631 if (errno
== ENOENT
&& delete_if_stale
) {
635 VLOG_WARN("%s: open: %s", pidfile
, ovs_strerror(error
));
639 error
= lock_pidfile__(file
, F_GETLK
, &lck
);
641 VLOG_WARN("%s: fcntl: %s", pidfile
, ovs_strerror(error
));
644 if (lck
.l_type
== F_UNLCK
) {
645 /* pidfile exists but it isn't locked by anyone. We need to delete it
646 * so that a new pidfile can go in its place. But just calling
647 * unlink(pidfile) makes a nasty race: what if someone else unlinks it
648 * before we do and then replaces it by a valid pidfile? We'd unlink
649 * their valid pidfile. We do a little dance to avoid the race, by
650 * locking the invalid pidfile. Only one process can have the invalid
651 * pidfile locked, and only that process has the right to unlink it. */
652 if (!delete_if_stale
) {
654 VLOG_DBG("%s: pid file is stale", pidfile
);
659 error
= lock_pidfile(file
, F_SETLK
);
661 /* We lost a race with someone else doing the same thing. */
662 VLOG_WARN("%s: lost race to lock pidfile", pidfile
);
666 /* Is the file we have locked still named 'pidfile'? */
667 if (stat(pidfile
, &s
) || fstat(fileno(file
), &s2
)
668 || s
.st_ino
!= s2
.st_ino
|| s
.st_dev
!= s2
.st_dev
) {
669 /* No. We lost a race with someone else who got the lock before
670 * us, deleted the pidfile, and closed it (releasing the lock). */
672 VLOG_WARN("%s: lost race to delete pidfile", pidfile
);
676 /* We won the right to delete the stale pidfile. */
677 if (unlink(pidfile
)) {
679 VLOG_WARN("%s: failed to delete stale pidfile (%s)",
680 pidfile
, ovs_strerror(error
));
683 VLOG_DBG("%s: deleted stale pidfile", pidfile
);
688 if (!fgets(line
, sizeof line
, file
)) {
691 VLOG_WARN("%s: read: %s", pidfile
, ovs_strerror(error
));
694 VLOG_WARN("%s: read: unexpected end of file", pidfile
);
699 if (lck
.l_pid
!= strtoul(line
, NULL
, 10)) {
700 /* The process that has the pidfile locked is not the process that
701 * created it. It must be stale, with the process that has it locked
702 * preparing to delete it. */
704 VLOG_WARN("%s: stale pidfile for pid %s being deleted by pid %ld",
705 pidfile
, line
, (long int) lck
.l_pid
);
719 /* Opens and reads a PID from 'pidfile'. Returns the positive PID if
720 * successful, otherwise a negative errno value. */
722 read_pidfile(const char *pidfile
)
724 return read_pidfile__(pidfile
, false);
727 /* Checks whether a process with the given 'pidfile' is already running and,
728 * if so, aborts. If 'pidfile' is stale, deletes it. */
730 check_already_running(void)
732 long int pid
= read_pidfile__(pidfile
, true);
734 VLOG_FATAL("%s: already running as pid %ld, aborting", pidfile
, pid
);
735 } else if (pid
< 0) {
736 VLOG_FATAL("%s: pidfile check failed (%s), aborting",
737 pidfile
, ovs_strerror(-pid
));
742 /* stub functions for non-windows platform. */
745 service_start(int *argc OVS_UNUSED
, char **argv
[] OVS_UNUSED
)
755 should_service_stop(void)