]>
git.proxmox.com Git - mirror_ovs.git/blob - lib/daemon.c
2 * Copyright (c) 2008, 2009, 2010, 2011, 2012 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.
25 #include <sys/resource.h>
29 #include "command-line.h"
30 #include "fatal-signal.h"
34 #include "socket-util.h"
39 VLOG_DEFINE_THIS_MODULE(daemon
);
41 /* --detach: Should we run in the background? */
44 /* --pidfile: Name of pidfile (null if none). */
47 /* Device and inode of pidfile, so we can avoid reopening it. */
48 static dev_t pidfile_dev
;
49 static ino_t pidfile_ino
;
51 /* --overwrite-pidfile: Create pidfile even if one already exists and is
53 static bool overwrite_pidfile
;
55 /* --no-chdir: Should we chdir to "/"? */
56 static bool chdir_
= true;
58 /* File descriptor used by daemonize_start() and daemonize_complete(). */
59 static int daemonize_fd
= -1;
61 /* --monitor: Should a supervisory process monitor the daemon and restart it if
62 * it dies due to an error signal? */
65 /* For each of the standard file descriptors, whether to replace it by
66 * /dev/null (if false) or keep it for the daemon to use (if true). */
67 static bool save_fds
[3];
69 static void check_already_running(void);
70 static int lock_pidfile(FILE *, int command
);
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
)
92 pidfile
= make_pidfile_name(name
);
95 /* Returns an absolute path to the configured pidfile, or a null pointer if no
96 * pidfile is configured. The caller must not modify or free the returned
104 /* Sets that we do not chdir to "/". */
111 /* Will we chdir to "/" as part of daemonizing? */
113 is_chdir_enabled(void)
118 /* Normally, daemonize() or damonize_start() will terminate the program with a
119 * message if a locked pidfile already exists. If this function is called, an
120 * existing pidfile will be replaced, with a warning. */
122 ignore_existing_pidfile(void)
124 overwrite_pidfile
= true;
127 /* Sets up a following call to daemonize() to detach from the foreground
128 * session, running this process in the background. */
135 /* Will daemonize() really detach? */
142 /* Sets up a following call to daemonize() to fork a supervisory process to
143 * monitor the daemon and restart it if it dies due to an error signal. */
145 daemon_set_monitor(void)
150 /* A daemon doesn't normally have any use for the file descriptors for stdin,
151 * stdout, and stderr after it detaches. To keep these file descriptors from
152 * e.g. holding an SSH session open, by default detaching replaces each of
153 * these file descriptors by /dev/null. But a few daemons expect the user to
154 * redirect stdout or stderr to a file, in which case it is desirable to keep
155 * these file descriptors. This function, therefore, disables replacing 'fd'
156 * by /dev/null when the daemon detaches. */
158 daemon_save_fd(int fd
)
160 assert(fd
== STDIN_FILENO
|| fd
== STDOUT_FILENO
|| fd
== STDERR_FILENO
);
164 /* If a pidfile has been configured, creates it and stores the running
165 * process's pid in it. Ensures that the pidfile will be deleted when the
170 long int pid
= getpid();
176 /* Create a temporary pidfile. */
177 tmpfile
= xasprintf("%s.tmp%ld", pidfile
, pid
);
178 fatal_signal_add_file_to_unlink(tmpfile
);
179 file
= fopen(tmpfile
, "w+");
181 VLOG_FATAL("%s: create failed (%s)", tmpfile
, strerror(errno
));
184 if (fstat(fileno(file
), &s
) == -1) {
185 VLOG_FATAL("%s: fstat failed (%s)", tmpfile
, strerror(errno
));
188 fprintf(file
, "%ld\n", pid
);
189 if (fflush(file
) == EOF
) {
190 VLOG_FATAL("%s: write failed (%s)", tmpfile
, strerror(errno
));
193 error
= lock_pidfile(file
, F_SETLK
);
195 VLOG_FATAL("%s: fcntl(F_SETLK) failed (%s)", tmpfile
, strerror(error
));
198 /* Rename or link it to the correct name. */
199 if (overwrite_pidfile
) {
200 if (rename(tmpfile
, pidfile
) < 0) {
201 VLOG_FATAL("failed to rename \"%s\" to \"%s\" (%s)",
202 tmpfile
, pidfile
, strerror(errno
));
206 error
= link(tmpfile
, pidfile
) == -1 ? errno
: 0;
207 if (error
== EEXIST
) {
208 check_already_running();
210 } while (error
== EINTR
|| error
== EEXIST
);
212 VLOG_FATAL("failed to link \"%s\" as \"%s\" (%s)",
213 tmpfile
, pidfile
, strerror(error
));
217 /* Ensure that the pidfile will get deleted on exit. */
218 fatal_signal_add_file_to_unlink(pidfile
);
220 /* Delete the temporary pidfile if it still exists. */
221 if (!overwrite_pidfile
) {
222 error
= fatal_signal_unlink_file_now(tmpfile
);
224 VLOG_FATAL("%s: unlink failed (%s)", tmpfile
, strerror(error
));
230 * We don't close 'file' because its file descriptor must remain open to
232 pidfile_dev
= s
.st_dev
;
233 pidfile_ino
= s
.st_ino
;
239 /* If configured with set_pidfile() or set_detach(), creates the pid file and
240 * detaches from the foreground session. */
245 daemonize_complete();
248 /* Calls fork() and on success returns its return value. On failure, logs an
249 * error and exits unsuccessfully.
251 * Post-fork, but before returning, this function calls a few other functions
252 * that are generally useful if the child isn't planning to exec a new
255 fork_and_clean_up(void)
261 /* Running in parent process. */
264 /* Running in child process. */
268 VLOG_FATAL("fork failed (%s)", strerror(errno
));
276 * - In the parent, waits for the child to signal that it has completed its
277 * startup sequence. Then stores -1 in '*fdp' and returns the child's pid.
279 * - In the child, stores a fd in '*fdp' and returns 0. The caller should
280 * pass the fd to fork_notify_startup() after it finishes its startup
283 * If something goes wrong with the fork, logs a critical error and aborts the
286 fork_and_wait_for_startup(int *fdp
)
293 pid
= fork_and_clean_up();
295 /* Running in parent process. */
300 if (read_fully(fds
[0], &c
, 1, &bytes_read
) != 0) {
305 retval
= waitpid(pid
, &status
, 0);
306 } while (retval
== -1 && errno
== EINTR
);
309 if (WIFEXITED(status
) && WEXITSTATUS(status
)) {
310 /* Child exited with an error. Convey the same error
311 * to our parent process as a courtesy. */
312 exit(WEXITSTATUS(status
));
314 char *status_msg
= process_status_msg(status
);
315 VLOG_FATAL("fork child died before signaling startup (%s)",
318 } else if (retval
< 0) {
319 VLOG_FATAL("waitpid failed (%s)", strerror(errno
));
327 /* Running in child process. */
336 fork_notify_startup(int fd
)
339 size_t bytes_written
;
342 error
= write_fully(fd
, "", 1, &bytes_written
);
344 VLOG_FATAL("pipe write failed (%s)", strerror(error
));
352 should_restart(int status
)
354 if (WIFSIGNALED(status
)) {
355 static const int error_signals
[] = {
356 SIGABRT
, SIGALRM
, SIGBUS
, SIGFPE
, SIGILL
, SIGPIPE
, SIGSEGV
,
362 for (i
= 0; i
< ARRAY_SIZE(error_signals
); i
++) {
363 if (error_signals
[i
] == WTERMSIG(status
)) {
372 monitor_daemon(pid_t daemon_pid
)
374 /* XXX Should log daemon's stderr output at startup time. */
379 subprogram_name
= "monitor";
380 status_msg
= xstrdup("healthy");
381 last_restart
= TIME_MIN
;
387 proctitle_set("%s: monitoring pid %lu (%s)",
388 program_name
, (unsigned long int) daemon_pid
,
392 retval
= waitpid(daemon_pid
, &status
, 0);
393 } while (retval
== -1 && errno
== EINTR
);
396 VLOG_FATAL("waitpid failed (%s)", strerror(errno
));
397 } else if (retval
== daemon_pid
) {
398 char *s
= process_status_msg(status
);
399 if (should_restart(status
)) {
401 status_msg
= xasprintf("%d crashes: pid %lu died, %s",
403 (unsigned long int) daemon_pid
, s
);
406 if (WCOREDUMP(status
)) {
407 /* Disable further core dumps to save disk space. */
412 if (setrlimit(RLIMIT_CORE
, &r
) == -1) {
413 VLOG_WARN("failed to disable core dumps: %s",
418 /* Throttle restarts to no more than once every 10 seconds. */
419 if (time(NULL
) < last_restart
+ 10) {
420 VLOG_WARN("%s, waiting until 10 seconds since last "
421 "restart", status_msg
);
423 time_t now
= time(NULL
);
424 time_t wakeup
= last_restart
+ 10;
431 last_restart
= time(NULL
);
433 VLOG_ERR("%s, restarting", status_msg
);
434 daemon_pid
= fork_and_wait_for_startup(&daemonize_fd
);
439 VLOG_INFO("pid %lu died, %s, exiting",
440 (unsigned long int) daemon_pid
, s
);
448 /* Running in new daemon process. */
450 subprogram_name
= "";
453 /* Close standard file descriptors (except any that the client has requested we
454 * leave open by calling daemon_save_fd()). If we're started from e.g. an SSH
455 * session, then this keeps us from holding that session open artificially. */
457 close_standard_fds(void)
459 int null_fd
= get_null_fd();
463 for (fd
= 0; fd
< 3; fd
++) {
470 /* Disable logging to stderr to avoid wasting CPU time. */
471 vlog_set_levels(NULL
, VLF_CONSOLE
, VLL_OFF
);
474 /* If daemonization is configured, then starts daemonization, by forking and
475 * returning in the child process. The parent process hangs around until the
476 * child lets it know either that it completed startup successfully (by calling
477 * daemon_complete()) or that it failed to start up (by exiting with a nonzero
480 daemonize_start(void)
485 if (fork_and_wait_for_startup(&daemonize_fd
) > 0) {
486 /* Running in parent process. */
489 /* Running in daemon or monitor process. */
493 int saved_daemonize_fd
= daemonize_fd
;
496 daemon_pid
= fork_and_wait_for_startup(&daemonize_fd
);
497 if (daemon_pid
> 0) {
498 /* Running in monitor process. */
499 fork_notify_startup(saved_daemonize_fd
);
500 close_standard_fds();
501 monitor_daemon(daemon_pid
);
503 /* Running in daemon process. */
510 /* Make sure that the unixctl commands for vlog get registered in a
511 * daemon, even before the first log message. */
515 /* If daemonization is configured, then this function notifies the parent
516 * process that the child process has completed startup successfully.
518 * Calling this function more than once has no additional effect. */
520 daemonize_complete(void)
522 fork_notify_startup(daemonize_fd
);
530 close_standard_fds();
539 "\nDaemon options:\n"
540 " --detach run in background as daemon\n"
541 " --no-chdir do not chdir to '/'\n"
542 " --pidfile[=FILE] create pidfile (default: %s/%s.pid)\n"
543 " --overwrite-pidfile with --pidfile, start even if already "
545 ovs_rundir(), program_name
);
549 lock_pidfile__(FILE *file
, int command
, struct flock
*lck
)
553 lck
->l_type
= F_WRLCK
;
554 lck
->l_whence
= SEEK_SET
;
560 error
= fcntl(fileno(file
), command
, lck
) == -1 ? errno
: 0;
561 } while (error
== EINTR
);
566 lock_pidfile(FILE *file
, int command
)
570 return lock_pidfile__(file
, command
, &lck
);
574 read_pidfile__(const char *pidfile
, bool delete_if_stale
)
582 if ((pidfile_ino
|| pidfile_dev
)
583 && !stat(pidfile
, &s
)
584 && s
.st_ino
== pidfile_ino
&& s
.st_dev
== pidfile_dev
) {
585 /* It's our own pidfile. We can't afford to open it, because closing
586 * *any* fd for a file that a process has locked also releases all the
587 * locks on that file.
589 * Fortunately, we know the associated pid anyhow: */
593 file
= fopen(pidfile
, "r+");
595 if (errno
== ENOENT
&& delete_if_stale
) {
599 VLOG_WARN("%s: open: %s", pidfile
, strerror(error
));
603 error
= lock_pidfile__(file
, F_GETLK
, &lck
);
605 VLOG_WARN("%s: fcntl: %s", pidfile
, strerror(error
));
608 if (lck
.l_type
== F_UNLCK
) {
609 /* pidfile exists but it isn't locked by anyone. We need to delete it
610 * so that a new pidfile can go in its place. But just calling
611 * unlink(pidfile) makes a nasty race: what if someone else unlinks it
612 * before we do and then replaces it by a valid pidfile? We'd unlink
613 * their valid pidfile. We do a little dance to avoid the race, by
614 * locking the invalid pidfile. Only one process can have the invalid
615 * pidfile locked, and only that process has the right to unlink it. */
616 if (!delete_if_stale
) {
618 VLOG_DBG("%s: pid file is stale", pidfile
);
623 error
= lock_pidfile(file
, F_SETLK
);
625 /* We lost a race with someone else doing the same thing. */
626 VLOG_WARN("%s: lost race to lock pidfile", pidfile
);
630 /* Is the file we have locked still named 'pidfile'? */
631 if (stat(pidfile
, &s
) || fstat(fileno(file
), &s2
)
632 || s
.st_ino
!= s2
.st_ino
|| s
.st_dev
!= s2
.st_dev
) {
633 /* No. We lost a race with someone else who got the lock before
634 * us, deleted the pidfile, and closed it (releasing the lock). */
636 VLOG_WARN("%s: lost race to delete pidfile", pidfile
);
640 /* We won the right to delete the stale pidfile. */
641 if (unlink(pidfile
)) {
643 VLOG_WARN("%s: failed to delete stale pidfile (%s)",
644 pidfile
, strerror(error
));
647 VLOG_DBG("%s: deleted stale pidfile", pidfile
);
652 if (!fgets(line
, sizeof line
, file
)) {
655 VLOG_WARN("%s: read: %s", pidfile
, strerror(error
));
658 VLOG_WARN("%s: read: unexpected end of file", pidfile
);
663 if (lck
.l_pid
!= strtoul(line
, NULL
, 10)) {
664 /* The process that has the pidfile locked is not the process that
665 * created it. It must be stale, with the process that has it locked
666 * preparing to delete it. */
668 VLOG_WARN("%s: stale pidfile for pid %s being deleted by pid %ld",
669 pidfile
, line
, (long int) lck
.l_pid
);
683 /* Opens and reads a PID from 'pidfile'. Returns the positive PID if
684 * successful, otherwise a negative errno value. */
686 read_pidfile(const char *pidfile
)
688 return read_pidfile__(pidfile
, false);
691 /* Checks whether a process with the given 'pidfile' is already running and,
692 * if so, aborts. If 'pidfile' is stale, deletes it. */
694 check_already_running(void)
696 long int pid
= read_pidfile__(pidfile
, true);
698 VLOG_FATAL("%s: already running as pid %ld, aborting", pidfile
, pid
);
699 } else if (pid
< 0) {
700 VLOG_FATAL("%s: pidfile check failed (%s), aborting",
701 pidfile
, strerror(-pid
));