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