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