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 "fatal-signal.h"
29 #include "socket-util.h"
33 #define THIS_MODULE VLM_daemon
36 /* Should we run in the background? */
39 /* Name of pidfile (null if none). */
42 /* Create pidfile even if one already exists and is locked? */
43 static bool overwrite_pidfile;
45 /* Should we chdir to "/"? */
46 static bool chdir_ = true;
48 /* File descriptor used by daemonize_start() and daemonize_complete(). */
49 static int daemonize_fd = -1;
51 /* --monitor: Should a supervisory process monitor the daemon and restart it if
52 * it dies due to an error signal? */
55 /* Returns the file name that would be used for a pidfile if 'name' were
56 * provided to set_pidfile(). The caller must free the returned string. */
58 make_pidfile_name(const char *name)
60 return (!name ? xasprintf("%s/%s.pid", ovs_rundir, program_name)
61 : *name == '/' ? xstrdup(name)
62 : xasprintf("%s/%s", ovs_rundir, name));
65 /* Sets up a following call to daemonize() to create a pidfile named 'name'.
66 * If 'name' begins with '/', then it is treated as an absolute path.
67 * Otherwise, it is taken relative to RUNDIR, which is $(prefix)/var/run by
70 * If 'name' is null, then program_name followed by ".pid" is used. */
72 set_pidfile(const char *name)
75 pidfile = make_pidfile_name(name);
78 /* Returns an absolute path to the configured pidfile, or a null pointer if no
79 * pidfile is configured. The caller must not modify or free the returned
87 /* Sets that we do not chdir to "/". */
94 /* Will we chdir to "/" as part of daemonizing? */
96 is_chdir_enabled(void)
101 /* Normally, die_if_already_running() will terminate the program with a message
102 * if a locked pidfile already exists. If this function is called,
103 * die_if_already_running() will merely log a warning. */
105 ignore_existing_pidfile(void)
107 overwrite_pidfile = true;
110 /* Sets up a following call to daemonize() to detach from the foreground
111 * session, running this process in the background. */
118 /* Will daemonize() really detach? */
125 /* Sets up a following call to daemonize() to fork a supervisory process to
126 * monitor the daemon and restart it if it dies due to an error signal. */
128 daemon_set_monitor(void)
133 /* If a pidfile has been configured and that pidfile already exists and is
134 * locked by a running process, returns the pid of the running process.
135 * Otherwise, returns 0. */
137 already_running(void)
141 int fd = open(pidfile, O_RDWR);
144 lck.l_type = F_WRLCK;
145 lck.l_whence = SEEK_SET;
148 if (fcntl(fd, F_GETLK, &lck) != -1 && lck.l_type != F_UNLCK) {
157 /* If a locked pidfile exists, issue a warning message and, unless
158 * ignore_existing_pidfile() has been called, terminate the program. */
160 die_if_already_running(void)
162 pid_t pid = already_running();
164 if (!overwrite_pidfile) {
165 ovs_fatal(0, "%s: already running as pid %ld",
166 get_pidfile(), (long int) pid);
168 VLOG_WARN("%s: %s already running as pid %ld",
169 get_pidfile(), program_name, (long int) pid);
174 /* If a pidfile has been configured, creates it and stores the running process'
175 * pid init. Ensures that the pidfile will be deleted when the process
181 /* Create pidfile via temporary file, so that observers never see an
182 * empty pidfile or an unlocked pidfile. */
183 long int pid = getpid();
187 tmpfile = xasprintf("%s.tmp%ld", pidfile, pid);
188 fatal_signal_add_file_to_unlink(tmpfile);
189 fd = open(tmpfile, O_CREAT | O_WRONLY | O_TRUNC, 0666);
192 lck.l_type = F_WRLCK;
193 lck.l_whence = SEEK_SET;
196 if (fcntl(fd, F_SETLK, &lck) != -1) {
197 char *text = xasprintf("%ld\n", pid);
198 if (write(fd, text, strlen(text)) == strlen(text)) {
199 fatal_signal_add_file_to_unlink(pidfile);
200 if (rename(tmpfile, pidfile) < 0) {
201 VLOG_ERR("failed to rename \"%s\" to \"%s\": %s",
202 tmpfile, pidfile, strerror(errno));
203 fatal_signal_remove_file_to_unlink(pidfile);
206 /* Keep 'fd' open to retain the lock. */
210 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 limit the rate at which we restart the daemon. */
326 /* XXX Should log daemon's stderr output at startup time. */
327 const char *saved_program_name;
329 saved_program_name = program_name;
330 program_name = xasprintf("monitor(%s)", program_name);
336 retval = waitpid(daemon_pid, &status, 0);
337 } while (retval == -1 && errno == EINTR);
340 ovs_fatal(errno, "waitpid failed");
341 } else if (retval == daemon_pid) {
342 char *status_msg = process_status_msg(status);
343 if (should_restart(status)) {
344 VLOG_ERR("%s daemon died unexpectedly (%s), restarting",
345 saved_program_name, status_msg);
348 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
353 VLOG_INFO("%s daemon exited normally (%s), exiting",
354 saved_program_name, status_msg);
360 /* Running in new daemon process. */
361 free((char *) program_name);
362 program_name = saved_program_name;
365 /* Close stdin, stdout, stderr. If we're started from e.g. an SSH session,
366 * then this keeps us from holding that session open artificially. */
368 close_standard_fds(void)
370 int null_fd = get_null_fd();
372 dup2(null_fd, STDIN_FILENO);
373 dup2(null_fd, STDOUT_FILENO);
374 dup2(null_fd, STDERR_FILENO);
378 /* If daemonization is configured, then starts daemonization, by forking and
379 * returning in the child process. The parent process hangs around until the
380 * child lets it know either that it completed startup successfully (by calling
381 * daemon_complete()) or that it failed to start up (by exiting with a nonzero
384 daemonize_start(void)
389 if (fork_and_wait_for_startup(&daemonize_fd) > 0) {
390 /* Running in parent process. */
393 /* Running in daemon or monitor process. */
397 int saved_daemonize_fd = daemonize_fd;
400 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
401 if (daemon_pid > 0) {
402 /* Running in monitor process. */
403 fork_notify_startup(saved_daemonize_fd);
404 close_standard_fds();
405 monitor_daemon(daemon_pid);
407 /* Running in daemon process. */
413 /* If daemonization is configured, then this function notifies the parent
414 * process that the child process has completed startup successfully. */
416 daemonize_complete(void)
418 fork_notify_startup(daemonize_fd);
425 close_standard_fds();
433 "\nDaemon options:\n"
434 " --detach run in background as daemon\n"
435 " --no-chdir do not chdir to '/'\n"
436 " --pidfile[=FILE] create pidfile (default: %s/%s.pid)\n"
437 " --overwrite-pidfile with --pidfile, start even if already "
439 ovs_rundir, program_name);
442 /* Opens and reads a PID from 'pidfile'. Returns the nonnegative PID if
443 * successful, otherwise a negative errno value. */
445 read_pidfile(const char *pidfile)
452 file = fopen(pidfile, "r");
455 VLOG_WARN("%s: open: %s", pidfile, strerror(error));
459 lck.l_type = F_WRLCK;
460 lck.l_whence = SEEK_SET;
463 if (fcntl(fileno(file), F_GETLK, &lck)) {
465 VLOG_WARN("%s: fcntl: %s", pidfile, strerror(error));
468 if (lck.l_type == F_UNLCK) {
470 VLOG_WARN("%s: pid file is not locked", pidfile);
474 if (!fgets(line, sizeof line, file)) {
477 VLOG_WARN("%s: read: %s", pidfile, strerror(error));
480 VLOG_WARN("%s: read: unexpected end of file", pidfile);
485 if (lck.l_pid != strtoul(line, NULL, 10)) {
487 VLOG_WARN("l_pid (%ld) != %s pid (%s)",
488 (long int) lck.l_pid, pidfile, line);