]> git.proxmox.com Git - mirror_ovs.git/blob - lib/daemon.c
utils: Introduce xsleep for RCU quiescent state
[mirror_ovs.git] / lib / daemon.c
1 /*
2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
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 <signal.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/resource.h>
25 #include <sys/wait.h>
26 #include <sys/stat.h>
27 #include <unistd.h>
28 #include "command-line.h"
29 #include "fatal-signal.h"
30 #include "dirs.h"
31 #include "lockfile.h"
32 #include "ovs-thread.h"
33 #include "process.h"
34 #include "socket-util.h"
35 #include "timeval.h"
36 #include "util.h"
37 #include "vlog.h"
38
39 VLOG_DEFINE_THIS_MODULE(daemon);
40
41 /* --detach: Should we run in the background? */
42 static bool detach; /* Was --detach specified? */
43 static bool detached; /* Have we already detached? */
44
45 /* --pidfile: Name of pidfile (null if none). */
46 static char *pidfile;
47
48 /* Device and inode of pidfile, so we can avoid reopening it. */
49 static dev_t pidfile_dev;
50 static ino_t pidfile_ino;
51
52 /* --overwrite-pidfile: Create pidfile even if one already exists and is
53 locked? */
54 static bool overwrite_pidfile;
55
56 /* --no-chdir: Should we chdir to "/"? */
57 static bool chdir_ = true;
58
59 /* File descriptor used by daemonize_start() and daemonize_complete(). */
60 static int daemonize_fd = -1;
61
62 /* --monitor: Should a supervisory process monitor the daemon and restart it if
63 * it dies due to an error signal? */
64 static bool monitor;
65
66 /* For each of the standard file descriptors, whether to replace it by
67 * /dev/null (if false) or keep it for the daemon to use (if true). */
68 static bool save_fds[3];
69
70 static void check_already_running(void);
71 static int lock_pidfile(FILE *, int command);
72 static char *make_pidfile_name(const char *name);
73 static pid_t fork_and_clean_up(void);
74 static void daemonize_post_detach(void);
75
76 /* Returns the file name that would be used for a pidfile if 'name' were
77 * provided to set_pidfile(). The caller must free the returned string. */
78 static char *
79 make_pidfile_name(const char *name)
80 {
81 return (!name
82 ? xasprintf("%s/%s.pid", ovs_rundir(), program_name)
83 : abs_file_name(ovs_rundir(), name));
84 }
85
86 /* Sets up a following call to daemonize() to create a pidfile named 'name'.
87 * If 'name' begins with '/', then it is treated as an absolute path.
88 * Otherwise, it is taken relative to RUNDIR, which is $(prefix)/var/run by
89 * default.
90 *
91 * If 'name' is null, then program_name followed by ".pid" is used. */
92 void
93 set_pidfile(const char *name)
94 {
95 assert_single_threaded();
96 free(pidfile);
97 pidfile = make_pidfile_name(name);
98 }
99
100 /* Sets that we do not chdir to "/". */
101 void
102 set_no_chdir(void)
103 {
104 chdir_ = false;
105 }
106
107 /* Normally, daemonize() or damonize_start() will terminate the program with a
108 * message if a locked pidfile already exists. If this function is called, an
109 * existing pidfile will be replaced, with a warning. */
110 void
111 ignore_existing_pidfile(void)
112 {
113 overwrite_pidfile = true;
114 }
115
116 /* Sets up a following call to daemonize() to detach from the foreground
117 * session, running this process in the background. */
118 void
119 set_detach(void)
120 {
121 detach = true;
122 }
123
124 /* Will daemonize() really detach? */
125 bool
126 get_detach(void)
127 {
128 return detach;
129 }
130
131 /* Sets up a following call to daemonize() to fork a supervisory process to
132 * monitor the daemon and restart it if it dies due to an error signal. */
133 void
134 daemon_set_monitor(void)
135 {
136 monitor = true;
137 }
138
139 /* A daemon doesn't normally have any use for the file descriptors for stdin,
140 * stdout, and stderr after it detaches. To keep these file descriptors from
141 * e.g. holding an SSH session open, by default detaching replaces each of
142 * these file descriptors by /dev/null. But a few daemons expect the user to
143 * redirect stdout or stderr to a file, in which case it is desirable to keep
144 * these file descriptors. This function, therefore, disables replacing 'fd'
145 * by /dev/null when the daemon detaches. */
146 void
147 daemon_save_fd(int fd)
148 {
149 ovs_assert(fd == STDIN_FILENO ||
150 fd == STDOUT_FILENO ||
151 fd == STDERR_FILENO);
152 save_fds[fd] = true;
153 }
154
155 /* If a pidfile has been configured, creates it and stores the running
156 * process's pid in it. Ensures that the pidfile will be deleted when the
157 * process exits. */
158 static void
159 make_pidfile(void)
160 {
161 long int pid = getpid();
162 struct stat s;
163 char *tmpfile;
164 FILE *file;
165 int error;
166
167 /* Create a temporary pidfile. */
168 if (overwrite_pidfile) {
169 tmpfile = xasprintf("%s.tmp%ld", pidfile, pid);
170 fatal_signal_add_file_to_unlink(tmpfile);
171 } else {
172 /* Everyone shares the same file which will be treated as a lock. To
173 * avoid some uncomfortable race conditions, we can't set up the fatal
174 * signal unlink until we've acquired it. */
175 tmpfile = xasprintf("%s.tmp", pidfile);
176 }
177
178 file = fopen(tmpfile, "a+");
179 if (!file) {
180 VLOG_FATAL("%s: create failed (%s)", tmpfile, ovs_strerror(errno));
181 }
182
183 error = lock_pidfile(file, F_SETLK);
184 if (error) {
185 /* Looks like we failed to acquire the lock. Note that, if we failed
186 * for some other reason (and '!overwrite_pidfile'), we will have
187 * left 'tmpfile' as garbage in the file system. */
188 VLOG_FATAL("%s: fcntl(F_SETLK) failed (%s)", tmpfile,
189 ovs_strerror(error));
190 }
191
192 if (!overwrite_pidfile) {
193 /* We acquired the lock. Make sure to clean up on exit, and verify
194 * that we're allowed to create the actual pidfile. */
195 fatal_signal_add_file_to_unlink(tmpfile);
196 check_already_running();
197 }
198
199 if (fstat(fileno(file), &s) == -1) {
200 VLOG_FATAL("%s: fstat failed (%s)", tmpfile, ovs_strerror(errno));
201 }
202
203 if (ftruncate(fileno(file), 0) == -1) {
204 VLOG_FATAL("%s: truncate failed (%s)", tmpfile, ovs_strerror(errno));
205 }
206
207 fprintf(file, "%ld\n", pid);
208 if (fflush(file) == EOF) {
209 VLOG_FATAL("%s: write failed (%s)", tmpfile, ovs_strerror(errno));
210 }
211
212 error = rename(tmpfile, pidfile);
213
214 /* Due to a race, 'tmpfile' may be owned by a different process, so we
215 * shouldn't delete it on exit. */
216 fatal_signal_remove_file_to_unlink(tmpfile);
217
218 if (error < 0) {
219 VLOG_FATAL("failed to rename \"%s\" to \"%s\" (%s)",
220 tmpfile, pidfile, ovs_strerror(errno));
221 }
222
223 /* Ensure that the pidfile will get deleted on exit. */
224 fatal_signal_add_file_to_unlink(pidfile);
225
226 /* Clean up.
227 *
228 * We don't close 'file' because its file descriptor must remain open to
229 * hold the lock. */
230 pidfile_dev = s.st_dev;
231 pidfile_ino = s.st_ino;
232 free(tmpfile);
233 }
234
235 /* If configured with set_pidfile() or set_detach(), creates the pid file and
236 * detaches from the foreground session. */
237 void
238 daemonize(void)
239 {
240 daemonize_start();
241 daemonize_complete();
242 }
243
244 /* Calls fork() and on success returns its return value. On failure, logs an
245 * error and exits unsuccessfully.
246 *
247 * Post-fork, but before returning, this function calls a few other functions
248 * that are generally useful if the child isn't planning to exec a new
249 * process. */
250 static pid_t
251 fork_and_clean_up(void)
252 {
253 pid_t pid = xfork();
254 if (pid > 0) {
255 /* Running in parent process. */
256 fatal_signal_fork();
257 } else if (!pid) {
258 /* Running in child process. */
259 lockfile_postfork();
260 }
261 return pid;
262 }
263
264 /* Forks, then:
265 *
266 * - In the parent, waits for the child to signal that it has completed its
267 * startup sequence. Then stores -1 in '*fdp' and returns the child's pid.
268 *
269 * - In the child, stores a fd in '*fdp' and returns 0. The caller should
270 * pass the fd to fork_notify_startup() after it finishes its startup
271 * sequence.
272 *
273 * If something goes wrong with the fork, logs a critical error and aborts the
274 * process. */
275 static pid_t
276 fork_and_wait_for_startup(int *fdp)
277 {
278 int fds[2];
279 pid_t pid;
280
281 xpipe(fds);
282
283 pid = fork_and_clean_up();
284 if (pid > 0) {
285 /* Running in parent process. */
286 size_t bytes_read;
287 char c;
288
289 close(fds[1]);
290 if (read_fully(fds[0], &c, 1, &bytes_read) != 0) {
291 int retval;
292 int status;
293
294 do {
295 retval = waitpid(pid, &status, 0);
296 } while (retval == -1 && errno == EINTR);
297
298 if (retval == pid) {
299 if (WIFEXITED(status) && WEXITSTATUS(status)) {
300 /* Child exited with an error. Convey the same error
301 * to our parent process as a courtesy. */
302 exit(WEXITSTATUS(status));
303 } else {
304 char *status_msg = process_status_msg(status);
305 VLOG_FATAL("fork child died before signaling startup (%s)",
306 status_msg);
307 }
308 } else if (retval < 0) {
309 VLOG_FATAL("waitpid failed (%s)", ovs_strerror(errno));
310 } else {
311 OVS_NOT_REACHED();
312 }
313 }
314 close(fds[0]);
315 *fdp = -1;
316 } else if (!pid) {
317 /* Running in child process. */
318 close(fds[0]);
319 *fdp = fds[1];
320 }
321
322 return pid;
323 }
324
325 static void
326 fork_notify_startup(int fd)
327 {
328 if (fd != -1) {
329 size_t bytes_written;
330 int error;
331
332 error = write_fully(fd, "", 1, &bytes_written);
333 if (error) {
334 VLOG_FATAL("pipe write failed (%s)", ovs_strerror(error));
335 }
336
337 close(fd);
338 }
339 }
340
341 static bool
342 should_restart(int status)
343 {
344 if (WIFSIGNALED(status)) {
345 static const int error_signals[] = {
346 /* This list of signals is documented in daemon.man. If you
347 * change the list, update the documentation too. */
348 SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGILL, SIGPIPE, SIGSEGV,
349 SIGXCPU, SIGXFSZ
350 };
351
352 size_t i;
353
354 for (i = 0; i < ARRAY_SIZE(error_signals); i++) {
355 if (error_signals[i] == WTERMSIG(status)) {
356 return true;
357 }
358 }
359 }
360 return false;
361 }
362
363 static void
364 monitor_daemon(pid_t daemon_pid)
365 {
366 /* XXX Should log daemon's stderr output at startup time. */
367 time_t last_restart;
368 char *status_msg;
369 int crashes;
370
371 set_subprogram_name("monitor");
372 status_msg = xstrdup("healthy");
373 last_restart = TIME_MIN;
374 crashes = 0;
375 for (;;) {
376 int retval;
377 int status;
378
379 proctitle_set("monitoring pid %lu (%s)",
380 (unsigned long int) daemon_pid, status_msg);
381
382 do {
383 retval = waitpid(daemon_pid, &status, 0);
384 } while (retval == -1 && errno == EINTR);
385
386 if (retval == -1) {
387 VLOG_FATAL("waitpid failed (%s)", ovs_strerror(errno));
388 } else if (retval == daemon_pid) {
389 char *s = process_status_msg(status);
390 if (should_restart(status)) {
391 free(status_msg);
392 status_msg = xasprintf("%d crashes: pid %lu died, %s",
393 ++crashes,
394 (unsigned long int) daemon_pid, s);
395 free(s);
396
397 if (WCOREDUMP(status)) {
398 /* Disable further core dumps to save disk space. */
399 struct rlimit r;
400
401 r.rlim_cur = 0;
402 r.rlim_max = 0;
403 if (setrlimit(RLIMIT_CORE, &r) == -1) {
404 VLOG_WARN("failed to disable core dumps: %s",
405 ovs_strerror(errno));
406 }
407 }
408
409 /* Throttle restarts to no more than once every 10 seconds. */
410 if (time(NULL) < last_restart + 10) {
411 VLOG_WARN("%s, waiting until 10 seconds since last "
412 "restart", status_msg);
413 for (;;) {
414 time_t now = time(NULL);
415 time_t wakeup = last_restart + 10;
416 if (now >= wakeup) {
417 break;
418 }
419 xsleep(wakeup - now);
420 }
421 }
422 last_restart = time(NULL);
423
424 VLOG_ERR("%s, restarting", status_msg);
425 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
426 if (!daemon_pid) {
427 break;
428 }
429 } else {
430 VLOG_INFO("pid %lu died, %s, exiting",
431 (unsigned long int) daemon_pid, s);
432 free(s);
433 exit(0);
434 }
435 }
436 }
437 free(status_msg);
438
439 /* Running in new daemon process. */
440 proctitle_restore();
441 set_subprogram_name("");
442 }
443
444 /* Returns a readable and writable fd for /dev/null, if successful, otherwise
445 * a negative errno value. The caller must not close the returned fd (because
446 * the same fd will be handed out to subsequent callers). */
447 static int
448 get_null_fd(void)
449 {
450 static int null_fd;
451
452 if (!null_fd) {
453 null_fd = open("/dev/null", O_RDWR);
454 if (null_fd < 0) {
455 int error = errno;
456 VLOG_ERR("could not open /dev/null: %s", ovs_strerror(error));
457 null_fd = -error;
458 }
459 }
460
461 return null_fd;
462 }
463
464 /* Close standard file descriptors (except any that the client has requested we
465 * leave open by calling daemon_save_fd()). If we're started from e.g. an SSH
466 * session, then this keeps us from holding that session open artificially. */
467 static void
468 close_standard_fds(void)
469 {
470 int null_fd = get_null_fd();
471 if (null_fd >= 0) {
472 int fd;
473
474 for (fd = 0; fd < 3; fd++) {
475 if (!save_fds[fd]) {
476 dup2(null_fd, fd);
477 }
478 }
479 }
480
481 /* Disable logging to stderr to avoid wasting CPU time. */
482 vlog_set_levels(NULL, VLF_CONSOLE, VLL_OFF);
483 }
484
485 /* If daemonization is configured, then starts daemonization, by forking and
486 * returning in the child process. The parent process hangs around until the
487 * child lets it know either that it completed startup successfully (by calling
488 * daemon_complete()) or that it failed to start up (by exiting with a nonzero
489 * exit code). */
490 void
491 daemonize_start(void)
492 {
493 assert_single_threaded();
494 daemonize_fd = -1;
495
496 if (detach) {
497 if (fork_and_wait_for_startup(&daemonize_fd) > 0) {
498 /* Running in parent process. */
499 exit(0);
500 }
501
502 /* Running in daemon or monitor process. */
503 setsid();
504 }
505
506 if (monitor) {
507 int saved_daemonize_fd = daemonize_fd;
508 pid_t daemon_pid;
509
510 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
511 if (daemon_pid > 0) {
512 /* Running in monitor process. */
513 fork_notify_startup(saved_daemonize_fd);
514 close_standard_fds();
515 monitor_daemon(daemon_pid);
516 }
517 /* Running in daemon process. */
518 }
519
520 forbid_forking("running in daemon process");
521
522 if (pidfile) {
523 make_pidfile();
524 }
525
526 /* Make sure that the unixctl commands for vlog get registered in a
527 * daemon, even before the first log message. */
528 vlog_init();
529 }
530
531 /* If daemonization is configured, then this function notifies the parent
532 * process that the child process has completed startup successfully. It also
533 * call daemonize_post_detach().
534 *
535 * Calling this function more than once has no additional effect. */
536 void
537 daemonize_complete(void)
538 {
539 if (pidfile) {
540 free(pidfile);
541 pidfile = NULL;
542 }
543
544 if (!detached) {
545 detached = true;
546
547 fork_notify_startup(daemonize_fd);
548 daemonize_fd = -1;
549 daemonize_post_detach();
550 }
551 }
552
553 /* If daemonization is configured, then this function does traditional Unix
554 * daemonization behavior: join a new session, chdir to the root (if not
555 * disabled), and close the standard file descriptors.
556 *
557 * It only makes sense to call this function as part of an implementation of a
558 * special daemon subprocess. A normal daemon should just call
559 * daemonize_complete(). */
560 static void
561 daemonize_post_detach(void)
562 {
563 if (detach) {
564 if (chdir_) {
565 ignore(chdir("/"));
566 }
567 close_standard_fds();
568 }
569 }
570
571 void
572 daemon_usage(void)
573 {
574 printf(
575 "\nDaemon options:\n"
576 " --detach run in background as daemon\n"
577 " --no-chdir do not chdir to '/'\n"
578 " --pidfile[=FILE] create pidfile (default: %s/%s.pid)\n"
579 " --overwrite-pidfile with --pidfile, start even if already "
580 "running\n",
581 ovs_rundir(), program_name);
582 }
583
584 static int
585 lock_pidfile__(FILE *file, int command, struct flock *lck)
586 {
587 int error;
588
589 lck->l_type = F_WRLCK;
590 lck->l_whence = SEEK_SET;
591 lck->l_start = 0;
592 lck->l_len = 0;
593 lck->l_pid = 0;
594
595 do {
596 error = fcntl(fileno(file), command, lck) == -1 ? errno : 0;
597 } while (error == EINTR);
598 return error;
599 }
600
601 static int
602 lock_pidfile(FILE *file, int command)
603 {
604 struct flock lck;
605
606 return lock_pidfile__(file, command, &lck);
607 }
608
609 static pid_t
610 read_pidfile__(const char *pidfile, bool delete_if_stale)
611 {
612 struct stat s, s2;
613 struct flock lck;
614 char line[128];
615 FILE *file;
616 int error;
617
618 if ((pidfile_ino || pidfile_dev)
619 && !stat(pidfile, &s)
620 && s.st_ino == pidfile_ino && s.st_dev == pidfile_dev) {
621 /* It's our own pidfile. We can't afford to open it, because closing
622 * *any* fd for a file that a process has locked also releases all the
623 * locks on that file.
624 *
625 * Fortunately, we know the associated pid anyhow: */
626 return getpid();
627 }
628
629 file = fopen(pidfile, "r+");
630 if (!file) {
631 if (errno == ENOENT && delete_if_stale) {
632 return 0;
633 }
634 error = errno;
635 VLOG_WARN("%s: open: %s", pidfile, ovs_strerror(error));
636 goto error;
637 }
638
639 error = lock_pidfile__(file, F_GETLK, &lck);
640 if (error) {
641 VLOG_WARN("%s: fcntl: %s", pidfile, ovs_strerror(error));
642 goto error;
643 }
644 if (lck.l_type == F_UNLCK) {
645 /* pidfile exists but it isn't locked by anyone. We need to delete it
646 * so that a new pidfile can go in its place. But just calling
647 * unlink(pidfile) makes a nasty race: what if someone else unlinks it
648 * before we do and then replaces it by a valid pidfile? We'd unlink
649 * their valid pidfile. We do a little dance to avoid the race, by
650 * locking the invalid pidfile. Only one process can have the invalid
651 * pidfile locked, and only that process has the right to unlink it. */
652 if (!delete_if_stale) {
653 error = ESRCH;
654 VLOG_DBG("%s: pid file is stale", pidfile);
655 goto error;
656 }
657
658 /* Get the lock. */
659 error = lock_pidfile(file, F_SETLK);
660 if (error) {
661 /* We lost a race with someone else doing the same thing. */
662 VLOG_WARN("%s: lost race to lock pidfile", pidfile);
663 goto error;
664 }
665
666 /* Is the file we have locked still named 'pidfile'? */
667 if (stat(pidfile, &s) || fstat(fileno(file), &s2)
668 || s.st_ino != s2.st_ino || s.st_dev != s2.st_dev) {
669 /* No. We lost a race with someone else who got the lock before
670 * us, deleted the pidfile, and closed it (releasing the lock). */
671 error = EALREADY;
672 VLOG_WARN("%s: lost race to delete pidfile", pidfile);
673 goto error;
674 }
675
676 /* We won the right to delete the stale pidfile. */
677 if (unlink(pidfile)) {
678 error = errno;
679 VLOG_WARN("%s: failed to delete stale pidfile (%s)",
680 pidfile, ovs_strerror(error));
681 goto error;
682 }
683 VLOG_DBG("%s: deleted stale pidfile", pidfile);
684 fclose(file);
685 return 0;
686 }
687
688 if (!fgets(line, sizeof line, file)) {
689 if (ferror(file)) {
690 error = errno;
691 VLOG_WARN("%s: read: %s", pidfile, ovs_strerror(error));
692 } else {
693 error = ESRCH;
694 VLOG_WARN("%s: read: unexpected end of file", pidfile);
695 }
696 goto error;
697 }
698
699 if (lck.l_pid != strtoul(line, NULL, 10)) {
700 /* The process that has the pidfile locked is not the process that
701 * created it. It must be stale, with the process that has it locked
702 * preparing to delete it. */
703 error = ESRCH;
704 VLOG_WARN("%s: stale pidfile for pid %s being deleted by pid %ld",
705 pidfile, line, (long int) lck.l_pid);
706 goto error;
707 }
708
709 fclose(file);
710 return lck.l_pid;
711
712 error:
713 if (file) {
714 fclose(file);
715 }
716 return -error;
717 }
718
719 /* Opens and reads a PID from 'pidfile'. Returns the positive PID if
720 * successful, otherwise a negative errno value. */
721 pid_t
722 read_pidfile(const char *pidfile)
723 {
724 return read_pidfile__(pidfile, false);
725 }
726
727 /* Checks whether a process with the given 'pidfile' is already running and,
728 * if so, aborts. If 'pidfile' is stale, deletes it. */
729 static void
730 check_already_running(void)
731 {
732 long int pid = read_pidfile__(pidfile, true);
733 if (pid > 0) {
734 VLOG_FATAL("%s: already running as pid %ld, aborting", pidfile, pid);
735 } else if (pid < 0) {
736 VLOG_FATAL("%s: pidfile check failed (%s), aborting",
737 pidfile, ovs_strerror(-pid));
738 }
739 }
740
741 \f
742 /* stub functions for non-windows platform. */
743
744 void
745 service_start(int *argc OVS_UNUSED, char **argv[] OVS_UNUSED)
746 {
747 }
748
749 void
750 service_stop(void)
751 {
752 }
753
754 bool
755 should_service_stop(void)
756 {
757 return false;
758 }