]> git.proxmox.com Git - mirror_ovs.git/blob - lib/daemon.c
Merge "citrix" branch into "master".
[mirror_ovs.git] / lib / daemon.c
1 /*
2 * Copyright (c) 2008, 2009, 2010 Nicira Networks.
3 *
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:
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17 #include <config.h>
18 #include "daemon.h"
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <sys/wait.h>
24 #include <unistd.h>
25 #include "command-line.h"
26 #include "fatal-signal.h"
27 #include "dirs.h"
28 #include "lockfile.h"
29 #include "process.h"
30 #include "socket-util.h"
31 #include "timeval.h"
32 #include "util.h"
33
34 #define THIS_MODULE VLM_daemon
35 #include "vlog.h"
36
37 /* Should we run in the background? */
38 static bool detach;
39
40 /* Name of pidfile (null if none). */
41 static char *pidfile;
42
43 /* Create pidfile even if one already exists and is locked? */
44 static bool overwrite_pidfile;
45
46 /* Should we chdir to "/"? */
47 static bool chdir_ = true;
48
49 /* File descriptor used by daemonize_start() and daemonize_complete(). */
50 static int daemonize_fd = -1;
51
52 /* --monitor: Should a supervisory process monitor the daemon and restart it if
53 * it dies due to an error signal? */
54 static bool monitor;
55
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. */
58 char *
59 make_pidfile_name(const char *name)
60 {
61 return (!name
62 ? xasprintf("%s/%s.pid", ovs_rundir, program_name)
63 : abs_file_name(ovs_rundir, name));
64 }
65
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
69 * default.
70 *
71 * If 'name' is null, then program_name followed by ".pid" is used. */
72 void
73 set_pidfile(const char *name)
74 {
75 free(pidfile);
76 pidfile = make_pidfile_name(name);
77 }
78
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
81 * string. */
82 const char *
83 get_pidfile(void)
84 {
85 return pidfile;
86 }
87
88 /* Sets that we do not chdir to "/". */
89 void
90 set_no_chdir(void)
91 {
92 chdir_ = false;
93 }
94
95 /* Will we chdir to "/" as part of daemonizing? */
96 bool
97 is_chdir_enabled(void)
98 {
99 return chdir_;
100 }
101
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. */
105 void
106 ignore_existing_pidfile(void)
107 {
108 overwrite_pidfile = true;
109 }
110
111 /* Sets up a following call to daemonize() to detach from the foreground
112 * session, running this process in the background. */
113 void
114 set_detach(void)
115 {
116 detach = true;
117 }
118
119 /* Will daemonize() really detach? */
120 bool
121 get_detach(void)
122 {
123 return detach;
124 }
125
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. */
128 void
129 daemon_set_monitor(void)
130 {
131 monitor = true;
132 }
133
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. */
137 static pid_t
138 already_running(void)
139 {
140 pid_t pid = 0;
141 if (pidfile) {
142 int fd = open(pidfile, O_RDWR);
143 if (fd >= 0) {
144 struct flock lck;
145 lck.l_type = F_WRLCK;
146 lck.l_whence = SEEK_SET;
147 lck.l_start = 0;
148 lck.l_len = 0;
149 if (fcntl(fd, F_GETLK, &lck) != -1 && lck.l_type != F_UNLCK) {
150 pid = lck.l_pid;
151 }
152 close(fd);
153 }
154 }
155 return pid;
156 }
157
158 /* If a locked pidfile exists, issue a warning message and, unless
159 * ignore_existing_pidfile() has been called, terminate the program. */
160 void
161 die_if_already_running(void)
162 {
163 pid_t pid = already_running();
164 if (pid) {
165 if (!overwrite_pidfile) {
166 ovs_fatal(0, "%s: already running as pid %ld",
167 get_pidfile(), (long int) pid);
168 } else {
169 VLOG_WARN("%s: %s already running as pid %ld",
170 get_pidfile(), program_name, (long int) pid);
171 }
172 }
173 }
174
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
177 * exits. */
178 static void
179 make_pidfile(void)
180 {
181 if (pidfile) {
182 /* Create pidfile via temporary file, so that observers never see an
183 * empty pidfile or an unlocked pidfile. */
184 long int pid = getpid();
185 char *tmpfile;
186 int fd;
187
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);
191 if (fd >= 0) {
192 struct flock lck;
193 lck.l_type = F_WRLCK;
194 lck.l_whence = SEEK_SET;
195 lck.l_start = 0;
196 lck.l_len = 0;
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);
205 close(fd);
206 } else {
207 /* Keep 'fd' open to retain the lock. */
208 }
209 free(text);
210 } else {
211 VLOG_ERR("%s: write failed: %s", tmpfile, strerror(errno));
212 close(fd);
213 }
214 } else {
215 VLOG_ERR("%s: fcntl failed: %s", tmpfile, strerror(errno));
216 close(fd);
217 }
218 } else {
219 VLOG_ERR("%s: create failed: %s", tmpfile, strerror(errno));
220 }
221 fatal_signal_remove_file_to_unlink(tmpfile);
222 free(tmpfile);
223 }
224 free(pidfile);
225 pidfile = NULL;
226 }
227
228 /* If configured with set_pidfile() or set_detach(), creates the pid file and
229 * detaches from the foreground session. */
230 void
231 daemonize(void)
232 {
233 daemonize_start();
234 daemonize_complete();
235 }
236
237 static pid_t
238 fork_and_wait_for_startup(int *fdp)
239 {
240 int fds[2];
241 pid_t pid;
242
243 if (pipe(fds) < 0) {
244 ovs_fatal(errno, "pipe failed");
245 }
246
247 pid = fork();
248 if (pid > 0) {
249 /* Running in parent process. */
250 char c;
251
252 close(fds[1]);
253 fatal_signal_fork();
254 if (read(fds[0], &c, 1) != 1) {
255 int retval;
256 int status;
257
258 do {
259 retval = waitpid(pid, &status, 0);
260 } while (retval == -1 && errno == EINTR);
261
262 if (retval == pid
263 && WIFEXITED(status)
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));
268 }
269
270 ovs_fatal(errno, "fork child failed to signal startup");
271 }
272 close(fds[0]);
273 *fdp = -1;
274 } else if (!pid) {
275 /* Running in child process. */
276 close(fds[0]);
277 time_postfork();
278 lockfile_postfork();
279 *fdp = fds[1];
280 } else {
281 ovs_fatal(errno, "could not fork");
282 }
283
284 return pid;
285 }
286
287 static void
288 fork_notify_startup(int fd)
289 {
290 if (fd != -1) {
291 size_t bytes_written;
292 int error;
293
294 error = write_fully(fd, "", 1, &bytes_written);
295 if (error) {
296 ovs_fatal(error, "could not write to pipe");
297 }
298
299 close(fd);
300 }
301 }
302
303 static bool
304 should_restart(int status)
305 {
306 if (WIFSIGNALED(status)) {
307 static const int error_signals[] = {
308 SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGILL, SIGPIPE, SIGSEGV,
309 SIGXCPU, SIGXFSZ
310 };
311
312 size_t i;
313
314 for (i = 0; i < ARRAY_SIZE(error_signals); i++) {
315 if (error_signals[i] == WTERMSIG(status)) {
316 return true;
317 }
318 }
319 }
320 return false;
321 }
322
323 static void
324 monitor_daemon(pid_t daemon_pid)
325 {
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;
329 char *status_msg;
330
331 saved_program_name = program_name;
332 program_name = xasprintf("monitor(%s)", program_name);
333 status_msg = xstrdup("healthy");
334 for (;;) {
335 int retval;
336 int status;
337
338 proctitle_set("%s: monitoring pid %lu (%s)",
339 saved_program_name, (unsigned long int) daemon_pid,
340 status_msg);
341
342 do {
343 retval = waitpid(daemon_pid, &status, 0);
344 } while (retval == -1 && errno == EINTR);
345
346 if (retval == -1) {
347 ovs_fatal(errno, "waitpid failed");
348 } else if (retval == daemon_pid) {
349 char *s = process_status_msg(status);
350 free(status_msg);
351 status_msg = xasprintf("pid %lu died, %s",
352 (unsigned long int) daemon_pid, s);
353 free(s);
354
355 if (should_restart(status)) {
356 VLOG_ERR("%s, restarting", status_msg);
357 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
358 if (!daemon_pid) {
359 break;
360 }
361 } else {
362 VLOG_INFO("%s, exiting", status_msg);
363 exit(0);
364 }
365 }
366 }
367 free(status_msg);
368
369 /* Running in new daemon process. */
370 proctitle_restore();
371 free((char *) program_name);
372 program_name = saved_program_name;
373 }
374
375 /* Close stdin, stdout, stderr. If we're started from e.g. an SSH session,
376 * then this keeps us from holding that session open artificially. */
377 static void
378 close_standard_fds(void)
379 {
380 int null_fd = get_null_fd();
381 if (null_fd >= 0) {
382 dup2(null_fd, STDIN_FILENO);
383 dup2(null_fd, STDOUT_FILENO);
384 dup2(null_fd, STDERR_FILENO);
385 }
386 }
387
388 /* If daemonization is configured, then starts daemonization, by forking and
389 * returning in the child process. The parent process hangs around until the
390 * child lets it know either that it completed startup successfully (by calling
391 * daemon_complete()) or that it failed to start up (by exiting with a nonzero
392 * exit code). */
393 void
394 daemonize_start(void)
395 {
396 daemonize_fd = -1;
397
398 if (detach) {
399 if (fork_and_wait_for_startup(&daemonize_fd) > 0) {
400 /* Running in parent process. */
401 exit(0);
402 }
403 /* Running in daemon or monitor process. */
404 }
405
406 if (monitor) {
407 int saved_daemonize_fd = daemonize_fd;
408 pid_t daemon_pid;
409
410 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
411 if (daemon_pid > 0) {
412 /* Running in monitor process. */
413 fork_notify_startup(saved_daemonize_fd);
414 close_standard_fds();
415 monitor_daemon(daemon_pid);
416 }
417 /* Running in daemon process. */
418 }
419
420 make_pidfile();
421 }
422
423 /* If daemonization is configured, then this function notifies the parent
424 * process that the child process has completed startup successfully. */
425 void
426 daemonize_complete(void)
427 {
428 fork_notify_startup(daemonize_fd);
429
430 if (detach) {
431 setsid();
432 if (chdir_) {
433 ignore(chdir("/"));
434 }
435 close_standard_fds();
436 }
437 }
438
439 void
440 daemon_usage(void)
441 {
442 printf(
443 "\nDaemon options:\n"
444 " --detach run in background as daemon\n"
445 " --no-chdir do not chdir to '/'\n"
446 " --pidfile[=FILE] create pidfile (default: %s/%s.pid)\n"
447 " --overwrite-pidfile with --pidfile, start even if already "
448 "running\n",
449 ovs_rundir, program_name);
450 }
451
452 /* Opens and reads a PID from 'pidfile'. Returns the nonnegative PID if
453 * successful, otherwise a negative errno value. */
454 pid_t
455 read_pidfile(const char *pidfile)
456 {
457 char line[128];
458 struct flock lck;
459 FILE *file;
460 int error;
461
462 file = fopen(pidfile, "r");
463 if (!file) {
464 error = errno;
465 VLOG_WARN("%s: open: %s", pidfile, strerror(error));
466 goto error;
467 }
468
469 lck.l_type = F_WRLCK;
470 lck.l_whence = SEEK_SET;
471 lck.l_start = 0;
472 lck.l_len = 0;
473 if (fcntl(fileno(file), F_GETLK, &lck)) {
474 error = errno;
475 VLOG_WARN("%s: fcntl: %s", pidfile, strerror(error));
476 goto error;
477 }
478 if (lck.l_type == F_UNLCK) {
479 error = ESRCH;
480 VLOG_WARN("%s: pid file is not locked", pidfile);
481 goto error;
482 }
483
484 if (!fgets(line, sizeof line, file)) {
485 if (ferror(file)) {
486 error = errno;
487 VLOG_WARN("%s: read: %s", pidfile, strerror(error));
488 } else {
489 error = ESRCH;
490 VLOG_WARN("%s: read: unexpected end of file", pidfile);
491 }
492 goto error;
493 }
494
495 if (lck.l_pid != strtoul(line, NULL, 10)) {
496 error = ESRCH;
497 VLOG_WARN("l_pid (%ld) != %s pid (%s)",
498 (long int) lck.l_pid, pidfile, line);
499 goto error;
500 }
501
502 fclose(file);
503 return lck.l_pid;
504
505 error:
506 if (file) {
507 fclose(file);
508 }
509 return -error;
510 }