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"
28 #include "socket-util.h"
32 #define THIS_MODULE VLM_daemon
35 /* Should we run in the background? */
38 /* Name of pidfile (null if none). */
41 /* Create pidfile even if one already exists and is locked? */
42 static bool overwrite_pidfile;
44 /* Should we chdir to "/"? */
45 static bool chdir_ = true;
47 /* File descriptors used by daemonize_start() and daemonize_complete(). */
48 static int daemonize_fds[2];
50 /* Returns the file name that would be used for a pidfile if 'name' were
51 * provided to set_pidfile(). The caller must free the returned string. */
53 make_pidfile_name(const char *name)
55 return (!name ? xasprintf("%s/%s.pid", ovs_rundir, program_name)
56 : *name == '/' ? xstrdup(name)
57 : xasprintf("%s/%s", ovs_rundir, name));
60 /* Sets up a following call to daemonize() to create a pidfile named 'name'.
61 * If 'name' begins with '/', then it is treated as an absolute path.
62 * Otherwise, it is taken relative to RUNDIR, which is $(prefix)/var/run by
65 * If 'name' is null, then program_name followed by ".pid" is used. */
67 set_pidfile(const char *name)
70 pidfile = make_pidfile_name(name);
73 /* Returns an absolute path to the configured pidfile, or a null pointer if no
74 * pidfile is configured. The caller must not modify or free the returned
82 /* Sets that we do not chdir to "/". */
89 /* Will we chdir to "/" as part of daemonizing? */
91 is_chdir_enabled(void)
96 /* Normally, die_if_already_running() will terminate the program with a message
97 * if a locked pidfile already exists. If this function is called,
98 * die_if_already_running() will merely log a warning. */
100 ignore_existing_pidfile(void)
102 overwrite_pidfile = true;
105 /* Sets up a following call to daemonize() to detach from the foreground
106 * session, running this process in the background. */
113 /* Will daemonize() really detach? */
120 /* If a pidfile has been configured and that pidfile already exists and is
121 * locked by a running process, returns the pid of the running process.
122 * Otherwise, returns 0. */
124 already_running(void)
128 int fd = open(pidfile, O_RDWR);
131 lck.l_type = F_WRLCK;
132 lck.l_whence = SEEK_SET;
135 if (fcntl(fd, F_GETLK, &lck) != -1 && lck.l_type != F_UNLCK) {
144 /* If a locked pidfile exists, issue a warning message and, unless
145 * ignore_existing_pidfile() has been called, terminate the program. */
147 die_if_already_running(void)
149 pid_t pid = already_running();
151 if (!overwrite_pidfile) {
152 ovs_fatal(0, "%s: already running as pid %ld",
153 get_pidfile(), (long int) pid);
155 VLOG_WARN("%s: %s already running as pid %ld",
156 get_pidfile(), program_name, (long int) pid);
161 /* If a pidfile has been configured, creates it and stores the running process'
162 * pid init. Ensures that the pidfile will be deleted when the process
168 /* Create pidfile via temporary file, so that observers never see an
169 * empty pidfile or an unlocked pidfile. */
170 long int pid = getpid();
174 tmpfile = xasprintf("%s.tmp%ld", pidfile, pid);
175 fatal_signal_add_file_to_unlink(tmpfile);
176 fd = open(tmpfile, O_CREAT | O_WRONLY | O_TRUNC, 0666);
179 lck.l_type = F_WRLCK;
180 lck.l_whence = SEEK_SET;
183 if (fcntl(fd, F_SETLK, &lck) != -1) {
184 char *text = xasprintf("%ld\n", pid);
185 if (write(fd, text, strlen(text)) == strlen(text)) {
186 fatal_signal_add_file_to_unlink(pidfile);
187 if (rename(tmpfile, pidfile) < 0) {
188 VLOG_ERR("failed to rename \"%s\" to \"%s\": %s",
189 tmpfile, pidfile, strerror(errno));
190 fatal_signal_remove_file_to_unlink(pidfile);
193 /* Keep 'fd' open to retain the lock. */
197 VLOG_ERR("%s: write failed: %s", tmpfile, strerror(errno));
201 VLOG_ERR("%s: fcntl failed: %s", tmpfile, strerror(errno));
205 VLOG_ERR("%s: create failed: %s", tmpfile, strerror(errno));
207 fatal_signal_remove_file_to_unlink(tmpfile);
214 /* If configured with set_pidfile() or set_detach(), creates the pid file and
215 * detaches from the foreground session. */
220 daemonize_complete();
223 /* If daemonization is configured, then starts daemonization, by forking and
224 * returning in the child process. The parent process hangs around until the
225 * child lets it know either that it completed startup successfully (by calling
226 * daemon_complete()) or that it failed to start up (by exiting with a nonzero
229 daemonize_start(void)
234 if (pipe(daemonize_fds) < 0) {
235 ovs_fatal(errno, "pipe failed");
240 /* Running in parent process. */
243 close(daemonize_fds[1]);
245 if (read(daemonize_fds[0], &c, 1) != 1) {
250 retval = waitpid(pid, &status, 0);
251 } while (retval == -1 && errno == EINTR);
255 && WEXITSTATUS(status)) {
256 /* Child exited with an error. Convey the same error to
257 * our parent process as a courtesy. */
258 exit(WEXITSTATUS(status));
261 ovs_fatal(errno, "daemon child failed to signal startup");
265 /* Running in child process. */
266 close(daemonize_fds[0]);
271 ovs_fatal(errno, "could not fork");
278 /* If daemonization is configured, then this function notifies the parent
279 * process that the child process has completed startup successfully. */
281 daemonize_complete(void)
284 size_t bytes_written;
288 error = write_fully(daemonize_fds[1], "", 1, &bytes_written);
290 ovs_fatal(error, "could not write to pipe");
293 close(daemonize_fds[1]);
299 /* Close stdin, stdout, stderr. Otherwise if we're started from
300 * e.g. an SSH session then we tend to hold that session open
302 null_fd = get_null_fd();
304 dup2(null_fd, STDIN_FILENO);
305 dup2(null_fd, STDOUT_FILENO);
306 dup2(null_fd, STDERR_FILENO);
315 "\nDaemon options:\n"
316 " --detach run in background as daemon\n"
317 " --no-chdir do not chdir to '/'\n"
318 " --pidfile[=FILE] create pidfile (default: %s/%s.pid)\n"
319 " --overwrite-pidfile with --pidfile, start even if already "
321 ovs_rundir, program_name);
324 /* Opens and reads a PID from 'pidfile'. Returns the nonnegative PID if
325 * successful, otherwise a negative errno value. */
327 read_pidfile(const char *pidfile)
334 file = fopen(pidfile, "r");
337 VLOG_WARN("%s: open: %s", pidfile, strerror(error));
341 lck.l_type = F_WRLCK;
342 lck.l_whence = SEEK_SET;
345 if (fcntl(fileno(file), F_GETLK, &lck)) {
347 VLOG_WARN("%s: fcntl: %s", pidfile, strerror(error));
350 if (lck.l_type == F_UNLCK) {
352 VLOG_WARN("%s: pid file is not locked", pidfile);
356 if (!fgets(line, sizeof line, file)) {
359 VLOG_WARN("%s: read: %s", pidfile, strerror(error));
362 VLOG_WARN("%s: read: unexpected end of file", pidfile);
367 if (lck.l_pid != strtoul(line, NULL, 10)) {
369 VLOG_WARN("l_pid (%ld) != %s pid (%s)",
370 (long int) lck.l_pid, pidfile, line);