2 * Copyright (c) 2008, 2009, 2010, 2011 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>
28 #include "command-line.h"
29 #include "fatal-signal.h"
33 #include "socket-util.h"
38 VLOG_DEFINE_THIS_MODULE(daemon);
40 /* --detach: Should we run in the background? */
43 /* --pidfile: Name of pidfile (null if none). */
46 /* Device and inode of pidfile, so we can avoid reopening it. */
47 static dev_t pidfile_dev;
48 static ino_t pidfile_ino;
50 /* --overwrite-pidfile: Create pidfile even if one already exists and is
52 static bool overwrite_pidfile;
54 /* --no-chdir: Should we chdir to "/"? */
55 static bool chdir_ = true;
57 /* File descriptor used by daemonize_start() and daemonize_complete(). */
58 static int daemonize_fd = -1;
60 /* --monitor: Should a supervisory process monitor the daemon and restart it if
61 * it dies due to an error signal? */
64 /* Returns the file name that would be used for a pidfile if 'name' were
65 * provided to set_pidfile(). The caller must free the returned string. */
67 make_pidfile_name(const char *name)
70 ? xasprintf("%s/%s.pid", ovs_rundir(), program_name)
71 : abs_file_name(ovs_rundir(), name));
74 /* Sets up a following call to daemonize() to create a pidfile named 'name'.
75 * If 'name' begins with '/', then it is treated as an absolute path.
76 * Otherwise, it is taken relative to RUNDIR, which is $(prefix)/var/run by
79 * If 'name' is null, then program_name followed by ".pid" is used. */
81 set_pidfile(const char *name)
84 pidfile = make_pidfile_name(name);
87 /* Returns an absolute path to the configured pidfile, or a null pointer if no
88 * pidfile is configured. The caller must not modify or free the returned
96 /* Sets that we do not chdir to "/". */
103 /* Will we chdir to "/" as part of daemonizing? */
105 is_chdir_enabled(void)
110 /* Normally, die_if_already_running() will terminate the program with a message
111 * if a locked pidfile already exists. If this function is called,
112 * die_if_already_running() will merely log a warning. */
114 ignore_existing_pidfile(void)
116 overwrite_pidfile = true;
119 /* Sets up a following call to daemonize() to detach from the foreground
120 * session, running this process in the background. */
127 /* Will daemonize() really detach? */
134 /* Sets up a following call to daemonize() to fork a supervisory process to
135 * monitor the daemon and restart it if it dies due to an error signal. */
137 daemon_set_monitor(void)
142 /* If a locked pidfile exists, issue a warning message and, unless
143 * ignore_existing_pidfile() has been called, terminate the program. */
145 die_if_already_running(void)
151 pid = read_pidfile_if_exists(pidfile);
153 if (!overwrite_pidfile) {
154 VLOG_ERR("%s: %s already running as pid %ld, aborting",
155 get_pidfile(), program_name, (long int) pid);
156 ovs_fatal(0, "%s: already running as pid %ld",
157 get_pidfile(), (long int) pid);
159 VLOG_WARN("%s: %s already running as pid %ld",
160 get_pidfile(), program_name, (long int) pid);
165 /* If a pidfile has been configured, creates it and stores the running
166 * process's pid in it. Ensures that the pidfile will be deleted when the
172 /* Create pidfile via temporary file, so that observers never see an
173 * empty pidfile or an unlocked pidfile. */
174 long int pid = getpid();
178 tmpfile = xasprintf("%s.tmp%ld", pidfile, pid);
179 fatal_signal_add_file_to_unlink(tmpfile);
180 fd = open(tmpfile, O_CREAT | O_WRONLY | O_TRUNC, 0666);
183 lck.l_type = F_WRLCK;
184 lck.l_whence = SEEK_SET;
187 if (fcntl(fd, F_SETLK, &lck) != -1) {
188 char *text = xasprintf("%ld\n", pid);
189 if (write(fd, text, strlen(text)) == strlen(text)) {
190 fatal_signal_add_file_to_unlink(pidfile);
191 if (rename(tmpfile, pidfile) < 0) {
192 VLOG_ERR("failed to rename \"%s\" to \"%s\": %s",
193 tmpfile, pidfile, strerror(errno));
194 fatal_signal_remove_file_to_unlink(pidfile);
197 /* Keep 'fd' open to retain the lock. */
200 if (!fstat(fd, &s)) {
201 pidfile_dev = s.st_dev;
202 pidfile_ino = s.st_ino;
204 VLOG_ERR("%s: fstat failed: %s",
205 pidfile, strerror(errno));
209 VLOG_ERR("%s: write failed: %s", tmpfile, strerror(errno));
214 VLOG_ERR("%s: fcntl failed: %s", tmpfile, strerror(errno));
218 VLOG_ERR("%s: create failed: %s", tmpfile, strerror(errno));
220 fatal_signal_remove_file_to_unlink(tmpfile);
227 /* If configured with set_pidfile() or set_detach(), creates the pid file and
228 * detaches from the foreground session. */
233 daemonize_complete();
237 fork_and_wait_for_startup(int *fdp)
243 ovs_fatal(errno, "pipe failed");
248 /* Running in parent process. */
253 if (read(fds[0], &c, 1) != 1) {
258 retval = waitpid(pid, &status, 0);
259 } while (retval == -1 && errno == EINTR);
263 && WEXITSTATUS(status)) {
264 /* Child exited with an error. Convey the same error to
265 * our parent process as a courtesy. */
266 exit(WEXITSTATUS(status));
269 ovs_fatal(errno, "fork child failed to signal startup");
274 /* Running in child process. */
280 ovs_fatal(errno, "could not fork");
287 fork_notify_startup(int fd)
290 size_t bytes_written;
293 error = write_fully(fd, "", 1, &bytes_written);
295 ovs_fatal(error, "could not write to pipe");
303 should_restart(int status)
305 if (WIFSIGNALED(status)) {
306 static const int error_signals[] = {
307 SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGILL, SIGPIPE, SIGSEGV,
313 for (i = 0; i < ARRAY_SIZE(error_signals); i++) {
314 if (error_signals[i] == WTERMSIG(status)) {
323 monitor_daemon(pid_t daemon_pid)
325 /* XXX Should log daemon's stderr output at startup time. */
326 const char *saved_program_name;
331 saved_program_name = program_name;
332 program_name = xasprintf("monitor(%s)", program_name);
333 status_msg = xstrdup("healthy");
334 last_restart = TIME_MIN;
340 proctitle_set("%s: monitoring pid %lu (%s)",
341 saved_program_name, (unsigned long int) daemon_pid,
345 retval = waitpid(daemon_pid, &status, 0);
346 } while (retval == -1 && errno == EINTR);
349 ovs_fatal(errno, "waitpid failed");
350 } else if (retval == daemon_pid) {
351 char *s = process_status_msg(status);
352 if (should_restart(status)) {
354 status_msg = xasprintf("%d crashes: pid %lu died, %s",
356 (unsigned long int) daemon_pid, s);
359 if (WCOREDUMP(status)) {
360 /* Disable further core dumps to save disk space. */
365 if (setrlimit(RLIMIT_CORE, &r) == -1) {
366 VLOG_WARN("failed to disable core dumps: %s",
371 /* Throttle restarts to no more than once every 10 seconds. */
372 if (time(NULL) < last_restart + 10) {
373 VLOG_WARN("%s, waiting until 10 seconds since last "
374 "restart", status_msg);
376 time_t now = time(NULL);
377 time_t wakeup = last_restart + 10;
384 last_restart = time(NULL);
386 VLOG_ERR("%s, restarting", status_msg);
387 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
392 VLOG_INFO("pid %lu died, %s, exiting",
393 (unsigned long int) daemon_pid, s);
401 /* Running in new daemon process. */
403 free((char *) program_name);
404 program_name = saved_program_name;
407 /* Close stdin, stdout, stderr. If we're started from e.g. an SSH session,
408 * then this keeps us from holding that session open artificially. */
410 close_standard_fds(void)
412 int null_fd = get_null_fd();
414 dup2(null_fd, STDIN_FILENO);
415 dup2(null_fd, STDOUT_FILENO);
416 dup2(null_fd, STDERR_FILENO);
420 /* If daemonization is configured, then starts daemonization, by forking and
421 * returning in the child process. The parent process hangs around until the
422 * child lets it know either that it completed startup successfully (by calling
423 * daemon_complete()) or that it failed to start up (by exiting with a nonzero
426 daemonize_start(void)
431 if (fork_and_wait_for_startup(&daemonize_fd) > 0) {
432 /* Running in parent process. */
435 /* Running in daemon or monitor process. */
439 int saved_daemonize_fd = daemonize_fd;
442 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
443 if (daemon_pid > 0) {
444 /* Running in monitor process. */
445 fork_notify_startup(saved_daemonize_fd);
446 close_standard_fds();
447 monitor_daemon(daemon_pid);
449 /* Running in daemon process. */
454 /* Make sure that the unixctl commands for vlog get registered in a
455 * daemon, even before the first log message. */
459 /* If daemonization is configured, then this function notifies the parent
460 * process that the child process has completed startup successfully.
462 * Calling this function more than once has no additional effect. */
464 daemonize_complete(void)
466 fork_notify_startup(daemonize_fd);
474 close_standard_fds();
483 "\nDaemon options:\n"
484 " --detach run in background as daemon\n"
485 " --no-chdir do not chdir to '/'\n"
486 " --pidfile[=FILE] create pidfile (default: %s/%s.pid)\n"
487 " --overwrite-pidfile with --pidfile, start even if already "
489 ovs_rundir(), program_name);
493 read_pidfile__(const char *pidfile, bool must_exist)
501 if ((pidfile_ino || pidfile_dev)
502 && !stat(pidfile, &s)
503 && s.st_ino == pidfile_ino && s.st_dev == pidfile_dev) {
504 /* It's our own pidfile. We can't afford to open it, because closing
505 * *any* fd for a file that a process has locked also releases all the
506 * locks on that file.
508 * Fortunately, we know the associated pid anyhow: */
512 file = fopen(pidfile, "r");
514 if (errno == ENOENT && !must_exist) {
518 VLOG_WARN("%s: open: %s", pidfile, strerror(error));
522 lck.l_type = F_WRLCK;
523 lck.l_whence = SEEK_SET;
527 if (fcntl(fileno(file), F_GETLK, &lck)) {
529 VLOG_WARN("%s: fcntl: %s", pidfile, strerror(error));
532 if (lck.l_type == F_UNLCK) {
534 VLOG_WARN("%s: pid file is not locked", pidfile);
538 if (!fgets(line, sizeof line, file)) {
541 VLOG_WARN("%s: read: %s", pidfile, strerror(error));
544 VLOG_WARN("%s: read: unexpected end of file", pidfile);
549 if (lck.l_pid != strtoul(line, NULL, 10)) {
551 VLOG_WARN("l_pid (%ld) != %s pid (%s)",
552 (long int) lck.l_pid, pidfile, line);
566 /* Opens and reads a PID from 'pidfile'. Returns the positive PID if
567 * successful, otherwise a negative errno value. */
569 read_pidfile(const char *pidfile)
571 return read_pidfile__(pidfile, true);
575 /* Opens and reads a PID from 'pidfile', if it exists. Returns 0 if 'pidfile'
576 * doesn't exist, the positive PID if successful, otherwise a negative errno
579 read_pidfile_if_exists(const char *pidfile)
581 return read_pidfile__(pidfile, false);