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 /* --overwrite-pidfile: Create pidfile even if one already exists and is
47 static bool overwrite_pidfile;
49 /* --no-chdir: Should we chdir to "/"? */
50 static bool chdir_ = true;
52 /* File descriptor used by daemonize_start() and daemonize_complete(). */
53 static int daemonize_fd = -1;
55 /* --monitor: Should a supervisory process monitor the daemon and restart it if
56 * it dies due to an error signal? */
59 /* Returns the file name that would be used for a pidfile if 'name' were
60 * provided to set_pidfile(). The caller must free the returned string. */
62 make_pidfile_name(const char *name)
65 ? xasprintf("%s/%s.pid", ovs_rundir, program_name)
66 : abs_file_name(ovs_rundir, name));
69 /* Sets up a following call to daemonize() to create a pidfile named 'name'.
70 * If 'name' begins with '/', then it is treated as an absolute path.
71 * Otherwise, it is taken relative to RUNDIR, which is $(prefix)/var/run by
74 * If 'name' is null, then program_name followed by ".pid" is used. */
76 set_pidfile(const char *name)
79 pidfile = make_pidfile_name(name);
82 /* Returns an absolute path to the configured pidfile, or a null pointer if no
83 * pidfile is configured. The caller must not modify or free the returned
91 /* Sets that we do not chdir to "/". */
98 /* Will we chdir to "/" as part of daemonizing? */
100 is_chdir_enabled(void)
105 /* Normally, die_if_already_running() will terminate the program with a message
106 * if a locked pidfile already exists. If this function is called,
107 * die_if_already_running() will merely log a warning. */
109 ignore_existing_pidfile(void)
111 overwrite_pidfile = true;
114 /* Sets up a following call to daemonize() to detach from the foreground
115 * session, running this process in the background. */
122 /* Will daemonize() really detach? */
129 /* Sets up a following call to daemonize() to fork a supervisory process to
130 * monitor the daemon and restart it if it dies due to an error signal. */
132 daemon_set_monitor(void)
137 /* If a pidfile has been configured and that pidfile already exists and is
138 * locked by a running process, returns the pid of the running process.
139 * Otherwise, returns 0. */
141 already_running(void)
145 int fd = open(pidfile, O_RDWR);
148 lck.l_type = F_WRLCK;
149 lck.l_whence = SEEK_SET;
152 if (fcntl(fd, F_GETLK, &lck) != -1 && lck.l_type != F_UNLCK) {
161 /* If a locked pidfile exists, issue a warning message and, unless
162 * ignore_existing_pidfile() has been called, terminate the program. */
164 die_if_already_running(void)
166 pid_t pid = already_running();
168 if (!overwrite_pidfile) {
169 ovs_fatal(0, "%s: already running as pid %ld",
170 get_pidfile(), (long int) pid);
172 VLOG_WARN("%s: %s already running as pid %ld",
173 get_pidfile(), program_name, (long int) pid);
178 /* If a pidfile has been configured, creates it and stores the running
179 * process's pid in it. Ensures that the pidfile will be deleted when the
185 /* Create pidfile via temporary file, so that observers never see an
186 * empty pidfile or an unlocked pidfile. */
187 long int pid = getpid();
191 tmpfile = xasprintf("%s.tmp%ld", pidfile, pid);
192 fatal_signal_add_file_to_unlink(tmpfile);
193 fd = open(tmpfile, O_CREAT | O_WRONLY | O_TRUNC, 0666);
196 lck.l_type = F_WRLCK;
197 lck.l_whence = SEEK_SET;
200 if (fcntl(fd, F_SETLK, &lck) != -1) {
201 char *text = xasprintf("%ld\n", pid);
202 if (write(fd, text, strlen(text)) == strlen(text)) {
203 fatal_signal_add_file_to_unlink(pidfile);
204 if (rename(tmpfile, pidfile) < 0) {
205 VLOG_ERR("failed to rename \"%s\" to \"%s\": %s",
206 tmpfile, pidfile, strerror(errno));
207 fatal_signal_remove_file_to_unlink(pidfile);
210 /* Keep 'fd' open to retain the lock. */
214 VLOG_ERR("%s: write failed: %s", tmpfile, strerror(errno));
218 VLOG_ERR("%s: fcntl failed: %s", tmpfile, strerror(errno));
222 VLOG_ERR("%s: create failed: %s", tmpfile, strerror(errno));
224 fatal_signal_remove_file_to_unlink(tmpfile);
231 /* If configured with set_pidfile() or set_detach(), creates the pid file and
232 * detaches from the foreground session. */
237 daemonize_complete();
241 fork_and_wait_for_startup(int *fdp)
247 ovs_fatal(errno, "pipe failed");
252 /* Running in parent process. */
257 if (read(fds[0], &c, 1) != 1) {
262 retval = waitpid(pid, &status, 0);
263 } while (retval == -1 && errno == EINTR);
267 && WEXITSTATUS(status)) {
268 /* Child exited with an error. Convey the same error to
269 * our parent process as a courtesy. */
270 exit(WEXITSTATUS(status));
273 ovs_fatal(errno, "fork child failed to signal startup");
278 /* Running in child process. */
284 ovs_fatal(errno, "could not fork");
291 fork_notify_startup(int fd)
294 size_t bytes_written;
297 error = write_fully(fd, "", 1, &bytes_written);
299 ovs_fatal(error, "could not write to pipe");
307 should_restart(int status)
309 if (WIFSIGNALED(status)) {
310 static const int error_signals[] = {
311 SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGILL, SIGPIPE, SIGSEGV,
317 for (i = 0; i < ARRAY_SIZE(error_signals); i++) {
318 if (error_signals[i] == WTERMSIG(status)) {
327 monitor_daemon(pid_t daemon_pid)
329 /* XXX Should log daemon's stderr output at startup time. */
330 const char *saved_program_name;
334 saved_program_name = program_name;
335 program_name = xasprintf("monitor(%s)", program_name);
336 status_msg = xstrdup("healthy");
337 last_restart = TIME_MIN;
342 proctitle_set("%s: monitoring pid %lu (%s)",
343 saved_program_name, (unsigned long int) daemon_pid,
347 retval = waitpid(daemon_pid, &status, 0);
348 } while (retval == -1 && errno == EINTR);
351 ovs_fatal(errno, "waitpid failed");
352 } else if (retval == daemon_pid) {
353 char *s = process_status_msg(status);
355 status_msg = xasprintf("pid %lu died, %s",
356 (unsigned long int) daemon_pid, s);
359 if (should_restart(status)) {
360 if (WCOREDUMP(status)) {
361 /* Disable further core dumps to save disk space. */
366 if (setrlimit(RLIMIT_CORE, &r) == -1) {
367 VLOG_WARN("failed to disable core dumps: %s",
372 /* Throttle restarts to no more than once every 10 seconds. */
373 if (time(NULL) < last_restart + 10) {
374 VLOG_WARN("%s, waiting until 10 seconds since last "
375 "restart", status_msg);
377 time_t now = time(NULL);
378 time_t wakeup = last_restart + 10;
385 last_restart = time(NULL);
387 VLOG_ERR("%s, restarting", status_msg);
388 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
393 VLOG_INFO("%s, exiting", status_msg);
400 /* Running in new daemon process. */
402 free((char *) program_name);
403 program_name = saved_program_name;
406 /* Close stdin, stdout, stderr. If we're started from e.g. an SSH session,
407 * then this keeps us from holding that session open artificially. */
409 close_standard_fds(void)
411 int null_fd = get_null_fd();
413 dup2(null_fd, STDIN_FILENO);
414 dup2(null_fd, STDOUT_FILENO);
415 dup2(null_fd, STDERR_FILENO);
419 /* If daemonization is configured, then starts daemonization, by forking and
420 * returning in the child process. The parent process hangs around until the
421 * child lets it know either that it completed startup successfully (by calling
422 * daemon_complete()) or that it failed to start up (by exiting with a nonzero
425 daemonize_start(void)
430 if (fork_and_wait_for_startup(&daemonize_fd) > 0) {
431 /* Running in parent process. */
434 /* Running in daemon or monitor process. */
438 int saved_daemonize_fd = daemonize_fd;
441 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
442 if (daemon_pid > 0) {
443 /* Running in monitor process. */
444 fork_notify_startup(saved_daemonize_fd);
445 close_standard_fds();
446 monitor_daemon(daemon_pid);
448 /* Running in daemon process. */
453 /* Make sure that the unixctl commands for vlog get registered in a
454 * daemon, even before the first log message. */
458 /* If daemonization is configured, then this function notifies the parent
459 * process that the child process has completed startup successfully. */
461 daemonize_complete(void)
463 fork_notify_startup(daemonize_fd);
470 close_standard_fds();
478 "\nDaemon options:\n"
479 " --detach run in background as daemon\n"
480 " --no-chdir do not chdir to '/'\n"
481 " --pidfile[=FILE] create pidfile (default: %s/%s.pid)\n"
482 " --overwrite-pidfile with --pidfile, start even if already "
484 ovs_rundir, program_name);
487 /* Opens and reads a PID from 'pidfile'. Returns the nonnegative PID if
488 * successful, otherwise a negative errno value. */
490 read_pidfile(const char *pidfile)
497 file = fopen(pidfile, "r");
500 VLOG_WARN("%s: open: %s", pidfile, strerror(error));
504 lck.l_type = F_WRLCK;
505 lck.l_whence = SEEK_SET;
508 if (fcntl(fileno(file), F_GETLK, &lck)) {
510 VLOG_WARN("%s: fcntl: %s", pidfile, strerror(error));
513 if (lck.l_type == F_UNLCK) {
515 VLOG_WARN("%s: pid file is not locked", pidfile);
519 if (!fgets(line, sizeof line, file)) {
522 VLOG_WARN("%s: read: %s", pidfile, strerror(error));
525 VLOG_WARN("%s: read: unexpected end of file", pidfile);
530 if (lck.l_pid != strtoul(line, NULL, 10)) {
532 VLOG_WARN("l_pid (%ld) != %s pid (%s)",
533 (long int) lck.l_pid, pidfile, line);