3b24fca831d46fdb860ed82b75e028a1dfa3d0f1
[cascardo/ovs.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 "openvswitch/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
218  *     pid in '*child_pid' argument.
219  *
220  *   - In the child, stores a fd in '*fdp' and returns 0 through '*child_pid'
221  *     argument.  The caller should pass the fd to fork_notify_startup() after
222  *     it finishes its startup sequence.
223  *
224  * Returns 0 on success.  If something goes wrong and child process was not
225  * able to signal its readiness by calling fork_notify_startup(), then this
226  * function returns -1. However, even in case of failure it still sets child
227  * process id in '*child_pid'. */
228 static int
229 fork_and_wait_for_startup(int *fdp, pid_t *child_pid)
230 {
231     int fds[2];
232     pid_t pid;
233     int ret = 0;
234
235     xpipe(fds);
236
237     pid = fork_and_clean_up();
238     if (pid > 0) {
239         /* Running in parent process. */
240         size_t bytes_read;
241         char c;
242
243         close(fds[1]);
244         if (read_fully(fds[0], &c, 1, &bytes_read) != 0) {
245             int retval;
246             int status;
247
248             do {
249                 retval = waitpid(pid, &status, 0);
250             } while (retval == -1 && errno == EINTR);
251
252             if (retval == pid) {
253                 if (WIFEXITED(status) && WEXITSTATUS(status)) {
254                     /* Child exited with an error.  Convey the same error
255                      * to our parent process as a courtesy. */
256                     exit(WEXITSTATUS(status));
257                 } else {
258                     char *status_msg = process_status_msg(status);
259                     VLOG_ERR("fork child died before signaling startup (%s)",
260                              status_msg);
261                     ret = -1;
262                 }
263             } else if (retval < 0) {
264                 VLOG_FATAL("waitpid failed (%s)", ovs_strerror(errno));
265             } else {
266                 OVS_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         *fdp = fds[1];
275     }
276     *child_pid = pid;
277     return ret;
278 }
279
280 static void
281 fork_notify_startup(int fd)
282 {
283     if (fd != -1) {
284         size_t bytes_written;
285         int error;
286
287         error = write_fully(fd, "", 1, &bytes_written);
288         if (error) {
289             VLOG_FATAL("pipe write failed (%s)", ovs_strerror(error));
290         }
291
292         close(fd);
293     }
294 }
295
296 static bool
297 should_restart(int status)
298 {
299     if (WIFSIGNALED(status)) {
300         static const int error_signals[] = {
301             /* This list of signals is documented in daemon.man.  If you
302              * change the list, update the documentation too. */
303             SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGILL, SIGPIPE, SIGSEGV,
304             SIGXCPU, SIGXFSZ
305         };
306
307         size_t i;
308
309         for (i = 0; i < ARRAY_SIZE(error_signals); i++) {
310             if (error_signals[i] == WTERMSIG(status)) {
311                 return true;
312             }
313         }
314     }
315     return false;
316 }
317
318 static void
319 monitor_daemon(pid_t daemon_pid)
320 {
321     /* XXX Should log daemon's stderr output at startup time. */
322     time_t last_restart;
323     char *status_msg;
324     int crashes;
325     bool child_ready = true;
326
327     set_subprogram_name("monitor");
328     status_msg = xstrdup("healthy");
329     last_restart = TIME_MIN;
330     crashes = 0;
331     for (;;) {
332         int retval;
333         int status;
334
335         proctitle_set("monitoring pid %lu (%s)",
336                       (unsigned long int) daemon_pid, status_msg);
337
338         if (child_ready) {
339             do {
340                 retval = waitpid(daemon_pid, &status, 0);
341             } while (retval == -1 && errno == EINTR);
342             if (retval == -1) {
343                 VLOG_FATAL("waitpid failed (%s)", ovs_strerror(errno));
344             }
345         }
346
347         if (!child_ready || retval == daemon_pid) {
348             char *s = process_status_msg(status);
349             if (should_restart(status)) {
350                 free(status_msg);
351                 status_msg = xasprintf("%d crashes: pid %lu died, %s",
352                                        ++crashes,
353                                        (unsigned long int) daemon_pid, s);
354                 free(s);
355
356                 if (WCOREDUMP(status)) {
357                     /* Disable further core dumps to save disk space. */
358                     struct rlimit r;
359
360                     r.rlim_cur = 0;
361                     r.rlim_max = 0;
362                     if (setrlimit(RLIMIT_CORE, &r) == -1) {
363                         VLOG_WARN("failed to disable core dumps: %s",
364                                   ovs_strerror(errno));
365                     }
366                 }
367
368                 /* Throttle restarts to no more than once every 10 seconds. */
369                 if (time(NULL) < last_restart + 10) {
370                     VLOG_WARN("%s, waiting until 10 seconds since last "
371                               "restart", status_msg);
372                     for (;;) {
373                         time_t now = time(NULL);
374                         time_t wakeup = last_restart + 10;
375                         if (now >= wakeup) {
376                             break;
377                         }
378                         xsleep(wakeup - now);
379                     }
380                 }
381                 last_restart = time(NULL);
382
383                 VLOG_ERR("%s, restarting", status_msg);
384                 child_ready = !fork_and_wait_for_startup(&daemonize_fd,
385                                                          &daemon_pid);
386                 if (child_ready && !daemon_pid) {
387                     /* Child process needs to break out of monitoring
388                      * loop. */
389                     break;
390                 }
391             } else {
392                 VLOG_INFO("pid %lu died, %s, exiting",
393                           (unsigned long int) daemon_pid, s);
394                 free(s);
395                 exit(0);
396             }
397         }
398     }
399     free(status_msg);
400
401     /* Running in new daemon process. */
402     proctitle_restore();
403     set_subprogram_name("");
404 }
405
406 /* If daemonization is configured, then starts daemonization, by forking and
407  * returning in the child process.  The parent process hangs around until the
408  * child lets it know either that it completed startup successfully (by calling
409  * daemon_complete()) or that it failed to start up (by exiting with a nonzero
410  * exit code). */
411 void
412 daemonize_start(void)
413 {
414     assert_single_threaded();
415     daemonize_fd = -1;
416
417     if (detach) {
418         pid_t pid;
419
420         if (fork_and_wait_for_startup(&daemonize_fd, &pid)) {
421             VLOG_FATAL("could not detach from foreground session");
422         }
423         if (pid > 0) {
424             /* Running in parent process. */
425             exit(0);
426         }
427
428         /* Running in daemon or monitor process. */
429         setsid();
430     }
431
432     if (monitor) {
433         int saved_daemonize_fd = daemonize_fd;
434         pid_t daemon_pid;
435
436         if (fork_and_wait_for_startup(&daemonize_fd, &daemon_pid)) {
437             VLOG_FATAL("could not initiate process monitoring");
438         }
439         if (daemon_pid > 0) {
440             /* Running in monitor process. */
441             fork_notify_startup(saved_daemonize_fd);
442             close_standard_fds();
443             monitor_daemon(daemon_pid);
444         }
445         /* Running in daemon process. */
446     }
447
448     forbid_forking("running in daemon process");
449
450     if (pidfile) {
451         make_pidfile();
452     }
453
454     /* Make sure that the unixctl commands for vlog get registered in a
455      * daemon, even before the first log message. */
456     vlog_init();
457 }
458
459 /* If daemonization is configured, then this function notifies the parent
460  * process that the child process has completed startup successfully.  It also
461  * call daemonize_post_detach().
462  *
463  * Calling this function more than once has no additional effect. */
464 void
465 daemonize_complete(void)
466 {
467     if (pidfile) {
468         free(pidfile);
469         pidfile = NULL;
470     }
471
472     if (!detached) {
473         detached = true;
474
475         fork_notify_startup(daemonize_fd);
476         daemonize_fd = -1;
477         daemonize_post_detach();
478     }
479 }
480
481 /* If daemonization is configured, then this function does traditional Unix
482  * daemonization behavior: join a new session, chdir to the root (if not
483  * disabled), and close the standard file descriptors.
484  *
485  * It only makes sense to call this function as part of an implementation of a
486  * special daemon subprocess.  A normal daemon should just call
487  * daemonize_complete(). */
488 static void
489 daemonize_post_detach(void)
490 {
491     if (detach) {
492         if (chdir_) {
493             ignore(chdir("/"));
494         }
495         close_standard_fds();
496     }
497 }
498
499 void
500 daemon_usage(void)
501 {
502     printf(
503         "\nDaemon options:\n"
504         "  --detach                run in background as daemon\n"
505         "  --no-chdir              do not chdir to '/'\n"
506         "  --pidfile[=FILE]        create pidfile (default: %s/%s.pid)\n"
507         "  --overwrite-pidfile     with --pidfile, start even if already "
508                                    "running\n",
509         ovs_rundir(), program_name);
510 }
511
512 static int
513 lock_pidfile__(FILE *file, int command, struct flock *lck)
514 {
515     int error;
516
517     lck->l_type = F_WRLCK;
518     lck->l_whence = SEEK_SET;
519     lck->l_start = 0;
520     lck->l_len = 0;
521     lck->l_pid = 0;
522
523     do {
524         error = fcntl(fileno(file), command, lck) == -1 ? errno : 0;
525     } while (error == EINTR);
526     return error;
527 }
528
529 static int
530 lock_pidfile(FILE *file, int command)
531 {
532     struct flock lck;
533
534     return lock_pidfile__(file, command, &lck);
535 }
536
537 static pid_t
538 read_pidfile__(const char *pidfile, bool delete_if_stale)
539 {
540     struct stat s, s2;
541     struct flock lck;
542     char line[128];
543     FILE *file;
544     int error;
545
546     if ((pidfile_ino || pidfile_dev)
547         && !stat(pidfile, &s)
548         && s.st_ino == pidfile_ino && s.st_dev == pidfile_dev) {
549         /* It's our own pidfile.  We can't afford to open it, because closing
550          * *any* fd for a file that a process has locked also releases all the
551          * locks on that file.
552          *
553          * Fortunately, we know the associated pid anyhow: */
554         return getpid();
555     }
556
557     file = fopen(pidfile, "r+");
558     if (!file) {
559         if (errno == ENOENT && delete_if_stale) {
560             return 0;
561         }
562         error = errno;
563         VLOG_WARN("%s: open: %s", pidfile, ovs_strerror(error));
564         goto error;
565     }
566
567     error = lock_pidfile__(file, F_GETLK, &lck);
568     if (error) {
569         VLOG_WARN("%s: fcntl: %s", pidfile, ovs_strerror(error));
570         goto error;
571     }
572     if (lck.l_type == F_UNLCK) {
573         /* pidfile exists but it isn't locked by anyone.  We need to delete it
574          * so that a new pidfile can go in its place.  But just calling
575          * unlink(pidfile) makes a nasty race: what if someone else unlinks it
576          * before we do and then replaces it by a valid pidfile?  We'd unlink
577          * their valid pidfile.  We do a little dance to avoid the race, by
578          * locking the invalid pidfile.  Only one process can have the invalid
579          * pidfile locked, and only that process has the right to unlink it. */
580         if (!delete_if_stale) {
581             error = ESRCH;
582             VLOG_DBG("%s: pid file is stale", pidfile);
583             goto error;
584         }
585
586         /* Get the lock. */
587         error = lock_pidfile(file, F_SETLK);
588         if (error) {
589             /* We lost a race with someone else doing the same thing. */
590             VLOG_WARN("%s: lost race to lock pidfile", pidfile);
591             goto error;
592         }
593
594         /* Is the file we have locked still named 'pidfile'? */
595         if (stat(pidfile, &s) || fstat(fileno(file), &s2)
596             || s.st_ino != s2.st_ino || s.st_dev != s2.st_dev) {
597             /* No.  We lost a race with someone else who got the lock before
598              * us, deleted the pidfile, and closed it (releasing the lock). */
599             error = EALREADY;
600             VLOG_WARN("%s: lost race to delete pidfile", pidfile);
601             goto error;
602         }
603
604         /* We won the right to delete the stale pidfile. */
605         if (unlink(pidfile)) {
606             error = errno;
607             VLOG_WARN("%s: failed to delete stale pidfile (%s)",
608                       pidfile, ovs_strerror(error));
609             goto error;
610         }
611         VLOG_DBG("%s: deleted stale pidfile", pidfile);
612         fclose(file);
613         return 0;
614     }
615
616     if (!fgets(line, sizeof line, file)) {
617         if (ferror(file)) {
618             error = errno;
619             VLOG_WARN("%s: read: %s", pidfile, ovs_strerror(error));
620         } else {
621             error = ESRCH;
622             VLOG_WARN("%s: read: unexpected end of file", pidfile);
623         }
624         goto error;
625     }
626
627     if (lck.l_pid != strtoul(line, NULL, 10)) {
628         /* The process that has the pidfile locked is not the process that
629          * created it.  It must be stale, with the process that has it locked
630          * preparing to delete it. */
631         error = ESRCH;
632         VLOG_WARN("%s: stale pidfile for pid %s being deleted by pid %ld",
633                   pidfile, line, (long int) lck.l_pid);
634         goto error;
635     }
636
637     fclose(file);
638     return lck.l_pid;
639
640 error:
641     if (file) {
642         fclose(file);
643     }
644     return -error;
645 }
646
647 /* Opens and reads a PID from 'pidfile'.  Returns the positive PID if
648  * successful, otherwise a negative errno value. */
649 pid_t
650 read_pidfile(const char *pidfile)
651 {
652     return read_pidfile__(pidfile, false);
653 }
654
655 /* Checks whether a process with the given 'pidfile' is already running and,
656  * if so, aborts.  If 'pidfile' is stale, deletes it. */
657 static void
658 check_already_running(void)
659 {
660     long int pid = read_pidfile__(pidfile, true);
661     if (pid > 0) {
662         VLOG_FATAL("%s: already running as pid %ld, aborting", pidfile, pid);
663     } else if (pid < 0) {
664         VLOG_FATAL("%s: pidfile check failed (%s), aborting",
665                    pidfile, ovs_strerror(-pid));
666     }
667 }
668
669 \f
670 /* stub functions for non-windows platform. */
671
672 void
673 service_start(int *argc OVS_UNUSED, char **argv[] OVS_UNUSED)
674 {
675 }
676
677 void
678 service_stop(void)
679 {
680 }
681
682 bool
683 should_service_stop(void)
684 {
685     return false;
686 }