2 * Copyright (c) 2008, 2009, 2010 Nicira Networks.
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>
27 #include "command-line.h"
28 #include "fatal-signal.h"
32 #include "socket-util.h"
37 VLOG_DEFINE_THIS_MODULE(daemon)
39 /* --detach: Should we run in the background? */
42 /* --pidfile: Name of pidfile (null if none). */
45 /* Device and inode of pidfile, so we can avoid reopening it. */
46 static dev_t pidfile_dev;
47 static ino_t pidfile_ino;
49 /* --overwrite-pidfile: Create pidfile even if one already exists and is
51 static bool overwrite_pidfile;
53 /* --no-chdir: Should we chdir to "/"? */
54 static bool chdir_ = true;
56 /* File descriptor used by daemonize_start() and daemonize_complete(). */
57 static int daemonize_fd = -1;
59 /* --monitor: Should a supervisory process monitor the daemon and restart it if
60 * it dies due to an error signal? */
63 /* Returns the file name that would be used for a pidfile if 'name' were
64 * provided to set_pidfile(). The caller must free the returned string. */
66 make_pidfile_name(const char *name)
69 ? xasprintf("%s/%s.pid", ovs_rundir, program_name)
70 : abs_file_name(ovs_rundir, name));
73 /* Sets up a following call to daemonize() to create a pidfile named 'name'.
74 * If 'name' begins with '/', then it is treated as an absolute path.
75 * Otherwise, it is taken relative to RUNDIR, which is $(prefix)/var/run by
78 * If 'name' is null, then program_name followed by ".pid" is used. */
80 set_pidfile(const char *name)
83 pidfile = make_pidfile_name(name);
86 /* Returns an absolute path to the configured pidfile, or a null pointer if no
87 * pidfile is configured. The caller must not modify or free the returned
95 /* Sets that we do not chdir to "/". */
102 /* Will we chdir to "/" as part of daemonizing? */
104 is_chdir_enabled(void)
109 /* Normally, die_if_already_running() will terminate the program with a message
110 * if a locked pidfile already exists. If this function is called,
111 * die_if_already_running() will merely log a warning. */
113 ignore_existing_pidfile(void)
115 overwrite_pidfile = true;
118 /* Sets up a following call to daemonize() to detach from the foreground
119 * session, running this process in the background. */
126 /* Will daemonize() really detach? */
133 /* Sets up a following call to daemonize() to fork a supervisory process to
134 * monitor the daemon and restart it if it dies due to an error signal. */
136 daemon_set_monitor(void)
141 /* If a pidfile has been configured and that pidfile already exists and is
142 * locked by a running process, returns the pid of the running process.
143 * Otherwise, returns 0. */
145 already_running(void)
149 int fd = open(pidfile, O_RDWR);
152 lck.l_type = F_WRLCK;
153 lck.l_whence = SEEK_SET;
156 if (fcntl(fd, F_GETLK, &lck) != -1 && lck.l_type != F_UNLCK) {
165 /* If a locked pidfile exists, issue a warning message and, unless
166 * ignore_existing_pidfile() has been called, terminate the program. */
168 die_if_already_running(void)
170 pid_t pid = already_running();
172 if (!overwrite_pidfile) {
173 ovs_fatal(0, "%s: already running as pid %ld",
174 get_pidfile(), (long int) pid);
176 VLOG_WARN("%s: %s already running as pid %ld",
177 get_pidfile(), program_name, (long int) pid);
182 /* If a pidfile has been configured, creates it and stores the running
183 * process's pid in it. Ensures that the pidfile will be deleted when the
189 /* Create pidfile via temporary file, so that observers never see an
190 * empty pidfile or an unlocked pidfile. */
191 long int pid = getpid();
195 tmpfile = xasprintf("%s.tmp%ld", pidfile, pid);
196 fatal_signal_add_file_to_unlink(tmpfile);
197 fd = open(tmpfile, O_CREAT | O_WRONLY | O_TRUNC, 0666);
200 lck.l_type = F_WRLCK;
201 lck.l_whence = SEEK_SET;
204 if (fcntl(fd, F_SETLK, &lck) != -1) {
205 char *text = xasprintf("%ld\n", pid);
206 if (write(fd, text, strlen(text)) == strlen(text)) {
207 fatal_signal_add_file_to_unlink(pidfile);
208 if (rename(tmpfile, pidfile) < 0) {
209 VLOG_ERR("failed to rename \"%s\" to \"%s\": %s",
210 tmpfile, pidfile, strerror(errno));
211 fatal_signal_remove_file_to_unlink(pidfile);
214 /* Keep 'fd' open to retain the lock. */
217 if (!fstat(fd, &s)) {
218 pidfile_dev = s.st_dev;
219 pidfile_ino = s.st_ino;
221 VLOG_ERR("%s: fstat failed: %s",
222 pidfile, strerror(errno));
227 VLOG_ERR("%s: write failed: %s", tmpfile, strerror(errno));
231 VLOG_ERR("%s: fcntl failed: %s", tmpfile, strerror(errno));
235 VLOG_ERR("%s: create failed: %s", tmpfile, strerror(errno));
237 fatal_signal_remove_file_to_unlink(tmpfile);
244 /* If configured with set_pidfile() or set_detach(), creates the pid file and
245 * detaches from the foreground session. */
250 daemonize_complete();
254 fork_and_wait_for_startup(int *fdp)
260 ovs_fatal(errno, "pipe failed");
265 /* Running in parent process. */
270 if (read(fds[0], &c, 1) != 1) {
275 retval = waitpid(pid, &status, 0);
276 } while (retval == -1 && errno == EINTR);
280 && WEXITSTATUS(status)) {
281 /* Child exited with an error. Convey the same error to
282 * our parent process as a courtesy. */
283 exit(WEXITSTATUS(status));
286 ovs_fatal(errno, "fork child failed to signal startup");
291 /* Running in child process. */
297 ovs_fatal(errno, "could not fork");
304 fork_notify_startup(int fd)
307 size_t bytes_written;
310 error = write_fully(fd, "", 1, &bytes_written);
312 ovs_fatal(error, "could not write to pipe");
320 should_restart(int status)
322 if (WIFSIGNALED(status)) {
323 static const int error_signals[] = {
324 SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGILL, SIGPIPE, SIGSEGV,
330 for (i = 0; i < ARRAY_SIZE(error_signals); i++) {
331 if (error_signals[i] == WTERMSIG(status)) {
340 monitor_daemon(pid_t daemon_pid)
342 /* XXX Should log daemon's stderr output at startup time. */
343 const char *saved_program_name;
348 saved_program_name = program_name;
349 program_name = xasprintf("monitor(%s)", program_name);
350 status_msg = xstrdup("healthy");
351 last_restart = TIME_MIN;
357 proctitle_set("%s: monitoring pid %lu (%s)",
358 saved_program_name, (unsigned long int) daemon_pid,
362 retval = waitpid(daemon_pid, &status, 0);
363 } while (retval == -1 && errno == EINTR);
366 ovs_fatal(errno, "waitpid failed");
367 } else if (retval == daemon_pid) {
368 char *s = process_status_msg(status);
370 status_msg = xasprintf("%d crashes: pid %lu died, %s",
372 (unsigned long int) daemon_pid, s);
375 if (should_restart(status)) {
376 if (WCOREDUMP(status)) {
377 /* Disable further core dumps to save disk space. */
382 if (setrlimit(RLIMIT_CORE, &r) == -1) {
383 VLOG_WARN("failed to disable core dumps: %s",
388 /* Throttle restarts to no more than once every 10 seconds. */
389 if (time(NULL) < last_restart + 10) {
390 VLOG_WARN("%s, waiting until 10 seconds since last "
391 "restart", status_msg);
393 time_t now = time(NULL);
394 time_t wakeup = last_restart + 10;
401 last_restart = time(NULL);
403 VLOG_ERR("%s, restarting", status_msg);
404 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
409 VLOG_INFO("%s, exiting", status_msg);
416 /* Running in new daemon process. */
418 free((char *) program_name);
419 program_name = saved_program_name;
422 /* Close stdin, stdout, stderr. If we're started from e.g. an SSH session,
423 * then this keeps us from holding that session open artificially. */
425 close_standard_fds(void)
427 int null_fd = get_null_fd();
429 dup2(null_fd, STDIN_FILENO);
430 dup2(null_fd, STDOUT_FILENO);
431 dup2(null_fd, STDERR_FILENO);
435 /* If daemonization is configured, then starts daemonization, by forking and
436 * returning in the child process. The parent process hangs around until the
437 * child lets it know either that it completed startup successfully (by calling
438 * daemon_complete()) or that it failed to start up (by exiting with a nonzero
441 daemonize_start(void)
446 if (fork_and_wait_for_startup(&daemonize_fd) > 0) {
447 /* Running in parent process. */
450 /* Running in daemon or monitor process. */
454 int saved_daemonize_fd = daemonize_fd;
457 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
458 if (daemon_pid > 0) {
459 /* Running in monitor process. */
460 fork_notify_startup(saved_daemonize_fd);
461 close_standard_fds();
462 monitor_daemon(daemon_pid);
464 /* Running in daemon process. */
469 /* Make sure that the unixctl commands for vlog get registered in a
470 * daemon, even before the first log message. */
474 /* If daemonization is configured, then this function notifies the parent
475 * process that the child process has completed startup successfully. */
477 daemonize_complete(void)
479 fork_notify_startup(daemonize_fd);
486 close_standard_fds();
494 "\nDaemon options:\n"
495 " --detach run in background as daemon\n"
496 " --no-chdir do not chdir to '/'\n"
497 " --pidfile[=FILE] create pidfile (default: %s/%s.pid)\n"
498 " --overwrite-pidfile with --pidfile, start even if already "
500 ovs_rundir, program_name);
503 /* Opens and reads a PID from 'pidfile'. Returns the nonnegative PID if
504 * successful, otherwise a negative errno value. */
506 read_pidfile(const char *pidfile)
514 if ((pidfile_ino || pidfile_dev)
515 && !stat(pidfile, &s)
516 && s.st_ino == pidfile_ino && s.st_dev == pidfile_dev) {
517 /* It's our own pidfile. We can't afford to open it, because closing
518 * *any* fd for a file that a process has locked also releases all the
519 * locks on that file.
521 * Fortunately, we know the associated pid anyhow: */
525 file = fopen(pidfile, "r");
528 VLOG_WARN("%s: open: %s", pidfile, strerror(error));
532 lck.l_type = F_WRLCK;
533 lck.l_whence = SEEK_SET;
536 if (fcntl(fileno(file), F_GETLK, &lck)) {
538 VLOG_WARN("%s: fcntl: %s", pidfile, strerror(error));
541 if (lck.l_type == F_UNLCK) {
543 VLOG_WARN("%s: pid file is not locked", pidfile);
547 if (!fgets(line, sizeof line, file)) {
550 VLOG_WARN("%s: read: %s", pidfile, strerror(error));
553 VLOG_WARN("%s: read: unexpected end of file", pidfile);
558 if (lck.l_pid != strtoul(line, NULL, 10)) {
560 VLOG_WARN("l_pid (%ld) != %s pid (%s)",
561 (long int) lck.l_pid, pidfile, line);