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