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.
25 #include "command-line.h"
26 #include "fatal-signal.h"
30 #include "socket-util.h"
34 #define THIS_MODULE VLM_daemon
37 /* Should we run in the background? */
40 /* Name of pidfile (null if none). */
43 /* Create pidfile even if one already exists and is locked? */
44 static bool overwrite_pidfile;
46 /* Should we chdir to "/"? */
47 static bool chdir_ = true;
49 /* File descriptor used by daemonize_start() and daemonize_complete(). */
50 static int daemonize_fd = -1;
52 /* --monitor: Should a supervisory process monitor the daemon and restart it if
53 * it dies due to an error signal? */
56 /* Returns the file name that would be used for a pidfile if 'name' were
57 * provided to set_pidfile(). The caller must free the returned string. */
59 make_pidfile_name(const char *name)
62 ? xasprintf("%s/%s.pid", ovs_rundir, program_name)
63 : abs_file_name(ovs_rundir, name));
66 /* Sets up a following call to daemonize() to create a pidfile named 'name'.
67 * If 'name' begins with '/', then it is treated as an absolute path.
68 * Otherwise, it is taken relative to RUNDIR, which is $(prefix)/var/run by
71 * If 'name' is null, then program_name followed by ".pid" is used. */
73 set_pidfile(const char *name)
76 pidfile = make_pidfile_name(name);
79 /* Returns an absolute path to the configured pidfile, or a null pointer if no
80 * pidfile is configured. The caller must not modify or free the returned
88 /* Sets that we do not chdir to "/". */
95 /* Will we chdir to "/" as part of daemonizing? */
97 is_chdir_enabled(void)
102 /* Normally, die_if_already_running() will terminate the program with a message
103 * if a locked pidfile already exists. If this function is called,
104 * die_if_already_running() will merely log a warning. */
106 ignore_existing_pidfile(void)
108 overwrite_pidfile = true;
111 /* Sets up a following call to daemonize() to detach from the foreground
112 * session, running this process in the background. */
119 /* Will daemonize() really detach? */
126 /* Sets up a following call to daemonize() to fork a supervisory process to
127 * monitor the daemon and restart it if it dies due to an error signal. */
129 daemon_set_monitor(void)
134 /* If a pidfile has been configured and that pidfile already exists and is
135 * locked by a running process, returns the pid of the running process.
136 * Otherwise, returns 0. */
138 already_running(void)
142 int fd = open(pidfile, O_RDWR);
145 lck.l_type = F_WRLCK;
146 lck.l_whence = SEEK_SET;
149 if (fcntl(fd, F_GETLK, &lck) != -1 && lck.l_type != F_UNLCK) {
158 /* If a locked pidfile exists, issue a warning message and, unless
159 * ignore_existing_pidfile() has been called, terminate the program. */
161 die_if_already_running(void)
163 pid_t pid = already_running();
165 if (!overwrite_pidfile) {
166 ovs_fatal(0, "%s: already running as pid %ld",
167 get_pidfile(), (long int) pid);
169 VLOG_WARN("%s: %s already running as pid %ld",
170 get_pidfile(), program_name, (long int) pid);
175 /* If a pidfile has been configured, creates it and stores the running process'
176 * pid init. Ensures that the pidfile will be deleted when the process
182 /* Create pidfile via temporary file, so that observers never see an
183 * empty pidfile or an unlocked pidfile. */
184 long int pid = getpid();
188 tmpfile = xasprintf("%s.tmp%ld", pidfile, pid);
189 fatal_signal_add_file_to_unlink(tmpfile);
190 fd = open(tmpfile, O_CREAT | O_WRONLY | O_TRUNC, 0666);
193 lck.l_type = F_WRLCK;
194 lck.l_whence = SEEK_SET;
197 if (fcntl(fd, F_SETLK, &lck) != -1) {
198 char *text = xasprintf("%ld\n", pid);
199 if (write(fd, text, strlen(text)) == strlen(text)) {
200 fatal_signal_add_file_to_unlink(pidfile);
201 if (rename(tmpfile, pidfile) < 0) {
202 VLOG_ERR("failed to rename \"%s\" to \"%s\": %s",
203 tmpfile, pidfile, strerror(errno));
204 fatal_signal_remove_file_to_unlink(pidfile);
207 /* Keep 'fd' open to retain the lock. */
211 VLOG_ERR("%s: write failed: %s", tmpfile, strerror(errno));
215 VLOG_ERR("%s: fcntl failed: %s", tmpfile, strerror(errno));
219 VLOG_ERR("%s: create failed: %s", tmpfile, strerror(errno));
221 fatal_signal_remove_file_to_unlink(tmpfile);
228 /* If configured with set_pidfile() or set_detach(), creates the pid file and
229 * detaches from the foreground session. */
234 daemonize_complete();
238 fork_and_wait_for_startup(int *fdp)
244 ovs_fatal(errno, "pipe failed");
249 /* Running in parent process. */
254 if (read(fds[0], &c, 1) != 1) {
259 retval = waitpid(pid, &status, 0);
260 } while (retval == -1 && errno == EINTR);
264 && WEXITSTATUS(status)) {
265 /* Child exited with an error. Convey the same error to
266 * our parent process as a courtesy. */
267 exit(WEXITSTATUS(status));
270 ovs_fatal(errno, "fork child failed to signal startup");
275 /* Running in child process. */
281 ovs_fatal(errno, "could not fork");
288 fork_notify_startup(int fd)
291 size_t bytes_written;
294 error = write_fully(fd, "", 1, &bytes_written);
296 ovs_fatal(error, "could not write to pipe");
304 should_restart(int status)
306 if (WIFSIGNALED(status)) {
307 static const int error_signals[] = {
308 SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGILL, SIGPIPE, SIGSEGV,
314 for (i = 0; i < ARRAY_SIZE(error_signals); i++) {
315 if (error_signals[i] == WTERMSIG(status)) {
324 monitor_daemon(pid_t daemon_pid)
326 /* XXX Should limit the rate at which we restart the daemon. */
327 /* XXX Should log daemon's stderr output at startup time. */
328 const char *saved_program_name;
331 saved_program_name = program_name;
332 program_name = xasprintf("monitor(%s)", program_name);
333 status_msg = xstrdup("healthy");
338 proctitle_set("%s: monitoring pid %lu (%s)",
339 saved_program_name, (unsigned long int) daemon_pid,
343 retval = waitpid(daemon_pid, &status, 0);
344 } while (retval == -1 && errno == EINTR);
347 ovs_fatal(errno, "waitpid failed");
348 } else if (retval == daemon_pid) {
349 char *s = process_status_msg(status);
351 status_msg = xasprintf("pid %lu died, %s",
352 (unsigned long int) daemon_pid, s);
355 if (should_restart(status)) {
356 if (WCOREDUMP(status)) {
357 /* Disable further core dumps to save disk space. */
362 if (setrlimit(RLIMIT_CORE, &r) == -1) {
363 VLOG_WARN("failed to disable core dumps: %s",
368 VLOG_ERR("%s, restarting", status_msg);
369 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
374 VLOG_INFO("%s, exiting", status_msg);
381 /* Running in new daemon process. */
383 free((char *) program_name);
384 program_name = saved_program_name;
387 /* Close stdin, stdout, stderr. If we're started from e.g. an SSH session,
388 * then this keeps us from holding that session open artificially. */
390 close_standard_fds(void)
392 int null_fd = get_null_fd();
394 dup2(null_fd, STDIN_FILENO);
395 dup2(null_fd, STDOUT_FILENO);
396 dup2(null_fd, STDERR_FILENO);
400 /* If daemonization is configured, then starts daemonization, by forking and
401 * returning in the child process. The parent process hangs around until the
402 * child lets it know either that it completed startup successfully (by calling
403 * daemon_complete()) or that it failed to start up (by exiting with a nonzero
406 daemonize_start(void)
411 if (fork_and_wait_for_startup(&daemonize_fd) > 0) {
412 /* Running in parent process. */
415 /* Running in daemon or monitor process. */
419 int saved_daemonize_fd = daemonize_fd;
422 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
423 if (daemon_pid > 0) {
424 /* Running in monitor process. */
425 fork_notify_startup(saved_daemonize_fd);
426 close_standard_fds();
427 monitor_daemon(daemon_pid);
429 /* Running in daemon process. */
435 /* If daemonization is configured, then this function notifies the parent
436 * process that the child process has completed startup successfully. */
438 daemonize_complete(void)
440 fork_notify_startup(daemonize_fd);
447 close_standard_fds();
455 "\nDaemon options:\n"
456 " --detach run in background as daemon\n"
457 " --no-chdir do not chdir to '/'\n"
458 " --pidfile[=FILE] create pidfile (default: %s/%s.pid)\n"
459 " --overwrite-pidfile with --pidfile, start even if already "
461 ovs_rundir, program_name);
464 /* Opens and reads a PID from 'pidfile'. Returns the nonnegative PID if
465 * successful, otherwise a negative errno value. */
467 read_pidfile(const char *pidfile)
474 file = fopen(pidfile, "r");
477 VLOG_WARN("%s: open: %s", pidfile, strerror(error));
481 lck.l_type = F_WRLCK;
482 lck.l_whence = SEEK_SET;
485 if (fcntl(fileno(file), F_GETLK, &lck)) {
487 VLOG_WARN("%s: fcntl: %s", pidfile, strerror(error));
490 if (lck.l_type == F_UNLCK) {
492 VLOG_WARN("%s: pid file is not locked", pidfile);
496 if (!fgets(line, sizeof line, file)) {
499 VLOG_WARN("%s: read: %s", pidfile, strerror(error));
502 VLOG_WARN("%s: read: unexpected end of file", pidfile);
507 if (lck.l_pid != strtoul(line, NULL, 10)) {
509 VLOG_WARN("l_pid (%ld) != %s pid (%s)",
510 (long int) lck.l_pid, pidfile, line);