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 /* Should we run in the background? */
42 /* Name of pidfile (null if none). */
45 /* Create pidfile even if one already exists and is locked? */
46 static bool overwrite_pidfile;
48 /* Should we chdir to "/"? */
49 static bool chdir_ = true;
51 /* File descriptor used by daemonize_start() and daemonize_complete(). */
52 static int daemonize_fd = -1;
54 /* --monitor: Should a supervisory process monitor the daemon and restart it if
55 * it dies due to an error signal? */
58 /* Returns the file name that would be used for a pidfile if 'name' were
59 * provided to set_pidfile(). The caller must free the returned string. */
61 make_pidfile_name(const char *name)
64 ? xasprintf("%s/%s.pid", ovs_rundir, program_name)
65 : abs_file_name(ovs_rundir, name));
68 /* Sets up a following call to daemonize() to create a pidfile named 'name'.
69 * If 'name' begins with '/', then it is treated as an absolute path.
70 * Otherwise, it is taken relative to RUNDIR, which is $(prefix)/var/run by
73 * If 'name' is null, then program_name followed by ".pid" is used. */
75 set_pidfile(const char *name)
78 pidfile = make_pidfile_name(name);
81 /* Returns an absolute path to the configured pidfile, or a null pointer if no
82 * pidfile is configured. The caller must not modify or free the returned
90 /* Sets that we do not chdir to "/". */
97 /* Will we chdir to "/" as part of daemonizing? */
99 is_chdir_enabled(void)
104 /* Normally, die_if_already_running() will terminate the program with a message
105 * if a locked pidfile already exists. If this function is called,
106 * die_if_already_running() will merely log a warning. */
108 ignore_existing_pidfile(void)
110 overwrite_pidfile = true;
113 /* Sets up a following call to daemonize() to detach from the foreground
114 * session, running this process in the background. */
121 /* Will daemonize() really detach? */
128 /* Sets up a following call to daemonize() to fork a supervisory process to
129 * monitor the daemon and restart it if it dies due to an error signal. */
131 daemon_set_monitor(void)
136 /* If a pidfile has been configured and that pidfile already exists and is
137 * locked by a running process, returns the pid of the running process.
138 * Otherwise, returns 0. */
140 already_running(void)
144 int fd = open(pidfile, O_RDWR);
147 lck.l_type = F_WRLCK;
148 lck.l_whence = SEEK_SET;
151 if (fcntl(fd, F_GETLK, &lck) != -1 && lck.l_type != F_UNLCK) {
160 /* If a locked pidfile exists, issue a warning message and, unless
161 * ignore_existing_pidfile() has been called, terminate the program. */
163 die_if_already_running(void)
165 pid_t pid = already_running();
167 if (!overwrite_pidfile) {
168 ovs_fatal(0, "%s: already running as pid %ld",
169 get_pidfile(), (long int) pid);
171 VLOG_WARN("%s: %s already running as pid %ld",
172 get_pidfile(), program_name, (long int) pid);
177 /* If a pidfile has been configured, creates it and stores the running process'
178 * pid init. Ensures that the pidfile will be deleted when the process
184 /* Create pidfile via temporary file, so that observers never see an
185 * empty pidfile or an unlocked pidfile. */
186 long int pid = getpid();
190 tmpfile = xasprintf("%s.tmp%ld", pidfile, pid);
191 fatal_signal_add_file_to_unlink(tmpfile);
192 fd = open(tmpfile, O_CREAT | O_WRONLY | O_TRUNC, 0666);
195 lck.l_type = F_WRLCK;
196 lck.l_whence = SEEK_SET;
199 if (fcntl(fd, F_SETLK, &lck) != -1) {
200 char *text = xasprintf("%ld\n", pid);
201 if (write(fd, text, strlen(text)) == strlen(text)) {
202 fatal_signal_add_file_to_unlink(pidfile);
203 if (rename(tmpfile, pidfile) < 0) {
204 VLOG_ERR("failed to rename \"%s\" to \"%s\": %s",
205 tmpfile, pidfile, strerror(errno));
206 fatal_signal_remove_file_to_unlink(pidfile);
209 /* Keep 'fd' open to retain the lock. */
213 VLOG_ERR("%s: write failed: %s", tmpfile, strerror(errno));
217 VLOG_ERR("%s: fcntl failed: %s", tmpfile, strerror(errno));
221 VLOG_ERR("%s: create failed: %s", tmpfile, strerror(errno));
223 fatal_signal_remove_file_to_unlink(tmpfile);
230 /* If configured with set_pidfile() or set_detach(), creates the pid file and
231 * detaches from the foreground session. */
236 daemonize_complete();
240 fork_and_wait_for_startup(int *fdp)
246 ovs_fatal(errno, "pipe failed");
251 /* Running in parent process. */
256 if (read(fds[0], &c, 1) != 1) {
261 retval = waitpid(pid, &status, 0);
262 } while (retval == -1 && errno == EINTR);
266 && WEXITSTATUS(status)) {
267 /* Child exited with an error. Convey the same error to
268 * our parent process as a courtesy. */
269 exit(WEXITSTATUS(status));
272 ovs_fatal(errno, "fork child failed to signal startup");
277 /* Running in child process. */
283 ovs_fatal(errno, "could not fork");
290 fork_notify_startup(int fd)
293 size_t bytes_written;
296 error = write_fully(fd, "", 1, &bytes_written);
298 ovs_fatal(error, "could not write to pipe");
306 should_restart(int status)
308 if (WIFSIGNALED(status)) {
309 static const int error_signals[] = {
310 SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGILL, SIGPIPE, SIGSEGV,
316 for (i = 0; i < ARRAY_SIZE(error_signals); i++) {
317 if (error_signals[i] == WTERMSIG(status)) {
326 monitor_daemon(pid_t daemon_pid)
328 /* XXX Should log daemon's stderr output at startup time. */
329 const char *saved_program_name;
333 saved_program_name = program_name;
334 program_name = xasprintf("monitor(%s)", program_name);
335 status_msg = xstrdup("healthy");
336 last_restart = TIME_MIN;
341 proctitle_set("%s: monitoring pid %lu (%s)",
342 saved_program_name, (unsigned long int) daemon_pid,
346 retval = waitpid(daemon_pid, &status, 0);
347 } while (retval == -1 && errno == EINTR);
350 ovs_fatal(errno, "waitpid failed");
351 } else if (retval == daemon_pid) {
352 char *s = process_status_msg(status);
354 status_msg = xasprintf("pid %lu died, %s",
355 (unsigned long int) daemon_pid, s);
358 if (should_restart(status)) {
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("%s, exiting", status_msg);
399 /* Running in new daemon process. */
401 free((char *) program_name);
402 program_name = saved_program_name;
405 /* Close stdin, stdout, stderr. If we're started from e.g. an SSH session,
406 * then this keeps us from holding that session open artificially. */
408 close_standard_fds(void)
410 int null_fd = get_null_fd();
412 dup2(null_fd, STDIN_FILENO);
413 dup2(null_fd, STDOUT_FILENO);
414 dup2(null_fd, STDERR_FILENO);
418 /* If daemonization is configured, then starts daemonization, by forking and
419 * returning in the child process. The parent process hangs around until the
420 * child lets it know either that it completed startup successfully (by calling
421 * daemon_complete()) or that it failed to start up (by exiting with a nonzero
424 daemonize_start(void)
429 if (fork_and_wait_for_startup(&daemonize_fd) > 0) {
430 /* Running in parent process. */
433 /* Running in daemon or monitor process. */
437 int saved_daemonize_fd = daemonize_fd;
440 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
441 if (daemon_pid > 0) {
442 /* Running in monitor process. */
443 fork_notify_startup(saved_daemonize_fd);
444 close_standard_fds();
445 monitor_daemon(daemon_pid);
447 /* Running in daemon process. */
453 /* If daemonization is configured, then this function notifies the parent
454 * process that the child process has completed startup successfully. */
456 daemonize_complete(void)
458 fork_notify_startup(daemonize_fd);
465 close_standard_fds();
473 "\nDaemon options:\n"
474 " --detach run in background as daemon\n"
475 " --no-chdir do not chdir to '/'\n"
476 " --pidfile[=FILE] create pidfile (default: %s/%s.pid)\n"
477 " --overwrite-pidfile with --pidfile, start even if already "
479 ovs_rundir, program_name);
482 /* Opens and reads a PID from 'pidfile'. Returns the nonnegative PID if
483 * successful, otherwise a negative errno value. */
485 read_pidfile(const char *pidfile)
492 file = fopen(pidfile, "r");
495 VLOG_WARN("%s: open: %s", pidfile, strerror(error));
499 lck.l_type = F_WRLCK;
500 lck.l_whence = SEEK_SET;
503 if (fcntl(fileno(file), F_GETLK, &lck)) {
505 VLOG_WARN("%s: fcntl: %s", pidfile, strerror(error));
508 if (lck.l_type == F_UNLCK) {
510 VLOG_WARN("%s: pid file is not locked", pidfile);
514 if (!fgets(line, sizeof line, file)) {
517 VLOG_WARN("%s: read: %s", pidfile, strerror(error));
520 VLOG_WARN("%s: read: unexpected end of file", pidfile);
525 if (lck.l_pid != strtoul(line, NULL, 10)) {
527 VLOG_WARN("l_pid (%ld) != %s pid (%s)",
528 (long int) lck.l_pid, pidfile, line);