f9290efbd585df2666cbcb0162a8d2a03c2288a4
[sliver-openvswitch.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                         sleep(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 /* Close standard file descriptors (except any that the client has requested we
445  * leave open by calling daemon_save_fd()).  If we're started from e.g. an SSH
446  * session, then this keeps us from holding that session open artificially. */
447 static void
448 close_standard_fds(void)
449 {
450     int null_fd = get_null_fd();
451     if (null_fd >= 0) {
452         int fd;
453
454         for (fd = 0; fd < 3; fd++) {
455             if (!save_fds[fd]) {
456                 dup2(null_fd, fd);
457             }
458         }
459     }
460
461     /* Disable logging to stderr to avoid wasting CPU time. */
462     vlog_set_levels(NULL, VLF_CONSOLE, VLL_OFF);
463 }
464
465 /* If daemonization is configured, then starts daemonization, by forking and
466  * returning in the child process.  The parent process hangs around until the
467  * child lets it know either that it completed startup successfully (by calling
468  * daemon_complete()) or that it failed to start up (by exiting with a nonzero
469  * exit code). */
470 void
471 daemonize_start(void)
472 {
473     assert_single_threaded();
474     daemonize_fd = -1;
475
476     if (detach) {
477         if (fork_and_wait_for_startup(&daemonize_fd) > 0) {
478             /* Running in parent process. */
479             exit(0);
480         }
481
482         /* Running in daemon or monitor process. */
483         setsid();
484     }
485
486     if (monitor) {
487         int saved_daemonize_fd = daemonize_fd;
488         pid_t daemon_pid;
489
490         daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
491         if (daemon_pid > 0) {
492             /* Running in monitor process. */
493             fork_notify_startup(saved_daemonize_fd);
494             close_standard_fds();
495             monitor_daemon(daemon_pid);
496         }
497         /* Running in daemon process. */
498     }
499
500     forbid_forking("running in daemon process");
501
502     if (pidfile) {
503         make_pidfile();
504     }
505
506     /* Make sure that the unixctl commands for vlog get registered in a
507      * daemon, even before the first log message. */
508     vlog_init();
509 }
510
511 /* If daemonization is configured, then this function notifies the parent
512  * process that the child process has completed startup successfully.  It also
513  * call daemonize_post_detach().
514  *
515  * Calling this function more than once has no additional effect. */
516 void
517 daemonize_complete(void)
518 {
519     if (pidfile) {
520         free(pidfile);
521         pidfile = NULL;
522     }
523
524     if (!detached) {
525         detached = true;
526
527         fork_notify_startup(daemonize_fd);
528         daemonize_fd = -1;
529         daemonize_post_detach();
530     }
531 }
532
533 /* If daemonization is configured, then this function does traditional Unix
534  * daemonization behavior: join a new session, chdir to the root (if not
535  * disabled), and close the standard file descriptors.
536  *
537  * It only makes sense to call this function as part of an implementation of a
538  * special daemon subprocess.  A normal daemon should just call
539  * daemonize_complete(). */
540 static void
541 daemonize_post_detach(void)
542 {
543     if (detach) {
544         if (chdir_) {
545             ignore(chdir("/"));
546         }
547         close_standard_fds();
548     }
549 }
550
551 void
552 daemon_usage(void)
553 {
554     printf(
555         "\nDaemon options:\n"
556         "  --detach                run in background as daemon\n"
557         "  --no-chdir              do not chdir to '/'\n"
558         "  --pidfile[=FILE]        create pidfile (default: %s/%s.pid)\n"
559         "  --overwrite-pidfile     with --pidfile, start even if already "
560                                    "running\n",
561         ovs_rundir(), program_name);
562 }
563
564 static int
565 lock_pidfile__(FILE *file, int command, struct flock *lck)
566 {
567     int error;
568
569     lck->l_type = F_WRLCK;
570     lck->l_whence = SEEK_SET;
571     lck->l_start = 0;
572     lck->l_len = 0;
573     lck->l_pid = 0;
574
575     do {
576         error = fcntl(fileno(file), command, lck) == -1 ? errno : 0;
577     } while (error == EINTR);
578     return error;
579 }
580
581 static int
582 lock_pidfile(FILE *file, int command)
583 {
584     struct flock lck;
585
586     return lock_pidfile__(file, command, &lck);
587 }
588
589 static pid_t
590 read_pidfile__(const char *pidfile, bool delete_if_stale)
591 {
592     struct stat s, s2;
593     struct flock lck;
594     char line[128];
595     FILE *file;
596     int error;
597
598     if ((pidfile_ino || pidfile_dev)
599         && !stat(pidfile, &s)
600         && s.st_ino == pidfile_ino && s.st_dev == pidfile_dev) {
601         /* It's our own pidfile.  We can't afford to open it, because closing
602          * *any* fd for a file that a process has locked also releases all the
603          * locks on that file.
604          *
605          * Fortunately, we know the associated pid anyhow: */
606         return getpid();
607     }
608
609     file = fopen(pidfile, "r+");
610     if (!file) {
611         if (errno == ENOENT && delete_if_stale) {
612             return 0;
613         }
614         error = errno;
615         VLOG_WARN("%s: open: %s", pidfile, ovs_strerror(error));
616         goto error;
617     }
618
619     error = lock_pidfile__(file, F_GETLK, &lck);
620     if (error) {
621         VLOG_WARN("%s: fcntl: %s", pidfile, ovs_strerror(error));
622         goto error;
623     }
624     if (lck.l_type == F_UNLCK) {
625         /* pidfile exists but it isn't locked by anyone.  We need to delete it
626          * so that a new pidfile can go in its place.  But just calling
627          * unlink(pidfile) makes a nasty race: what if someone else unlinks it
628          * before we do and then replaces it by a valid pidfile?  We'd unlink
629          * their valid pidfile.  We do a little dance to avoid the race, by
630          * locking the invalid pidfile.  Only one process can have the invalid
631          * pidfile locked, and only that process has the right to unlink it. */
632         if (!delete_if_stale) {
633             error = ESRCH;
634             VLOG_DBG("%s: pid file is stale", pidfile);
635             goto error;
636         }
637
638         /* Get the lock. */
639         error = lock_pidfile(file, F_SETLK);
640         if (error) {
641             /* We lost a race with someone else doing the same thing. */
642             VLOG_WARN("%s: lost race to lock pidfile", pidfile);
643             goto error;
644         }
645
646         /* Is the file we have locked still named 'pidfile'? */
647         if (stat(pidfile, &s) || fstat(fileno(file), &s2)
648             || s.st_ino != s2.st_ino || s.st_dev != s2.st_dev) {
649             /* No.  We lost a race with someone else who got the lock before
650              * us, deleted the pidfile, and closed it (releasing the lock). */
651             error = EALREADY;
652             VLOG_WARN("%s: lost race to delete pidfile", pidfile);
653             goto error;
654         }
655
656         /* We won the right to delete the stale pidfile. */
657         if (unlink(pidfile)) {
658             error = errno;
659             VLOG_WARN("%s: failed to delete stale pidfile (%s)",
660                       pidfile, ovs_strerror(error));
661             goto error;
662         }
663         VLOG_DBG("%s: deleted stale pidfile", pidfile);
664         fclose(file);
665         return 0;
666     }
667
668     if (!fgets(line, sizeof line, file)) {
669         if (ferror(file)) {
670             error = errno;
671             VLOG_WARN("%s: read: %s", pidfile, ovs_strerror(error));
672         } else {
673             error = ESRCH;
674             VLOG_WARN("%s: read: unexpected end of file", pidfile);
675         }
676         goto error;
677     }
678
679     if (lck.l_pid != strtoul(line, NULL, 10)) {
680         /* The process that has the pidfile locked is not the process that
681          * created it.  It must be stale, with the process that has it locked
682          * preparing to delete it. */
683         error = ESRCH;
684         VLOG_WARN("%s: stale pidfile for pid %s being deleted by pid %ld",
685                   pidfile, line, (long int) lck.l_pid);
686         goto error;
687     }
688
689     fclose(file);
690     return lck.l_pid;
691
692 error:
693     if (file) {
694         fclose(file);
695     }
696     return -error;
697 }
698
699 /* Opens and reads a PID from 'pidfile'.  Returns the positive PID if
700  * successful, otherwise a negative errno value. */
701 pid_t
702 read_pidfile(const char *pidfile)
703 {
704     return read_pidfile__(pidfile, false);
705 }
706
707 /* Checks whether a process with the given 'pidfile' is already running and,
708  * if so, aborts.  If 'pidfile' is stale, deletes it. */
709 static void
710 check_already_running(void)
711 {
712     long int pid = read_pidfile__(pidfile, true);
713     if (pid > 0) {
714         VLOG_FATAL("%s: already running as pid %ld, aborting", pidfile, pid);
715     } else if (pid < 0) {
716         VLOG_FATAL("%s: pidfile check failed (%s), aborting",
717                    pidfile, ovs_strerror(-pid));
718     }
719 }
720
721 \f
722 /* stub functions for non-windows platform. */
723
724 void
725 service_start(int *argc OVS_UNUSED, char **argv[] OVS_UNUSED)
726 {
727 }
728
729 void
730 service_stop(void)
731 {
732 }
733
734 bool
735 should_service_stop(void)
736 {
737     return false;
738 }