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