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