Log anything that could prevent a daemon from starting.
[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 /* Returns the file name that would be used for a pidfile if 'name' were
65  * provided to set_pidfile().  The caller must free the returned string. */
66 char *
67 make_pidfile_name(const char *name)
68 {
69     return (!name
70             ? xasprintf("%s/%s.pid", ovs_rundir(), program_name)
71             : abs_file_name(ovs_rundir(), name));
72 }
73
74 /* Sets up a following call to daemonize() to create a pidfile named 'name'.
75  * If 'name' begins with '/', then it is treated as an absolute path.
76  * Otherwise, it is taken relative to RUNDIR, which is $(prefix)/var/run by
77  * default.
78  *
79  * If 'name' is null, then program_name followed by ".pid" is used. */
80 void
81 set_pidfile(const char *name)
82 {
83     free(pidfile);
84     pidfile = make_pidfile_name(name);
85 }
86
87 /* Returns an absolute path to the configured pidfile, or a null pointer if no
88  * pidfile is configured.  The caller must not modify or free the returned
89  * string. */
90 const char *
91 get_pidfile(void)
92 {
93     return pidfile;
94 }
95
96 /* Sets that we do not chdir to "/". */
97 void
98 set_no_chdir(void)
99 {
100     chdir_ = false;
101 }
102
103 /* Will we chdir to "/" as part of daemonizing? */
104 bool
105 is_chdir_enabled(void)
106 {
107     return chdir_;
108 }
109
110 /* Normally, die_if_already_running() will terminate the program with a message
111  * if a locked pidfile already exists.  If this function is called,
112  * die_if_already_running() will merely log a warning. */
113 void
114 ignore_existing_pidfile(void)
115 {
116     overwrite_pidfile = true;
117 }
118
119 /* Sets up a following call to daemonize() to detach from the foreground
120  * session, running this process in the background.  */
121 void
122 set_detach(void)
123 {
124     detach = true;
125 }
126
127 /* Will daemonize() really detach? */
128 bool
129 get_detach(void)
130 {
131     return detach;
132 }
133
134 /* Sets up a following call to daemonize() to fork a supervisory process to
135  * monitor the daemon and restart it if it dies due to an error signal.  */
136 void
137 daemon_set_monitor(void)
138 {
139     monitor = true;
140 }
141
142 /* If a locked pidfile exists, issue a warning message and, unless
143  * ignore_existing_pidfile() has been called, terminate the program. */
144 void
145 die_if_already_running(void)
146 {
147     pid_t pid;
148     if (!pidfile) {
149         return;
150     }
151     pid = read_pidfile_if_exists(pidfile);
152     if (pid > 0) {
153         if (!overwrite_pidfile) {
154             VLOG_ERR("%s: %s already running as pid %ld, aborting",
155                       get_pidfile(), program_name, (long int) pid);
156             ovs_fatal(0, "%s: already running as pid %ld",
157                       get_pidfile(), (long int) pid);
158         } else {
159             VLOG_WARN("%s: %s already running as pid %ld",
160                       get_pidfile(), program_name, (long int) pid);
161         }
162     }
163 }
164
165 /* If a pidfile has been configured, creates it and stores the running
166  * process's pid in it.  Ensures that the pidfile will be deleted when the
167  * process exits. */
168 static void
169 make_pidfile(void)
170 {
171     if (pidfile) {
172         /* Create pidfile via temporary file, so that observers never see an
173          * empty pidfile or an unlocked pidfile. */
174         long int pid = getpid();
175         char *tmpfile;
176         int fd;
177
178         tmpfile = xasprintf("%s.tmp%ld", pidfile, pid);
179         fatal_signal_add_file_to_unlink(tmpfile);
180         fd = open(tmpfile, O_CREAT | O_WRONLY | O_TRUNC, 0666);
181         if (fd >= 0) {
182             struct flock lck;
183             lck.l_type = F_WRLCK;
184             lck.l_whence = SEEK_SET;
185             lck.l_start = 0;
186             lck.l_len = 0;
187             if (fcntl(fd, F_SETLK, &lck) != -1) {
188                 char *text = xasprintf("%ld\n", pid);
189                 if (write(fd, text, strlen(text)) == strlen(text)) {
190                     fatal_signal_add_file_to_unlink(pidfile);
191                     if (rename(tmpfile, pidfile) < 0) {
192                         VLOG_ERR("failed to rename \"%s\" to \"%s\": %s",
193                                  tmpfile, pidfile, strerror(errno));
194                         fatal_signal_remove_file_to_unlink(pidfile);
195                         close(fd);
196                     } else {
197                         /* Keep 'fd' open to retain the lock. */
198                         struct stat s;
199
200                         if (!fstat(fd, &s)) {
201                             pidfile_dev = s.st_dev;
202                             pidfile_ino = s.st_ino;
203                         } else {
204                             VLOG_ERR("%s: fstat failed: %s",
205                                      pidfile, strerror(errno));
206                         }
207                     }
208                 } else {
209                     VLOG_ERR("%s: write failed: %s", tmpfile, strerror(errno));
210                     close(fd);
211                 }
212                 free(text);
213             } else {
214                 VLOG_ERR("%s: fcntl failed: %s", tmpfile, strerror(errno));
215                 close(fd);
216             }
217         } else {
218             VLOG_ERR("%s: create failed: %s", tmpfile, strerror(errno));
219         }
220         fatal_signal_remove_file_to_unlink(tmpfile);
221         free(tmpfile);
222     }
223     free(pidfile);
224     pidfile = NULL;
225 }
226
227 /* If configured with set_pidfile() or set_detach(), creates the pid file and
228  * detaches from the foreground session.  */
229 void
230 daemonize(void)
231 {
232     daemonize_start();
233     daemonize_complete();
234 }
235
236 static pid_t
237 fork_and_wait_for_startup(int *fdp)
238 {
239     int fds[2];
240     pid_t pid;
241
242     xpipe(fds);
243
244     pid = fork();
245     if (pid > 0) {
246         /* Running in parent process. */
247         char c;
248
249         close(fds[1]);
250         fatal_signal_fork();
251         if (read(fds[0], &c, 1) != 1) {
252             int retval;
253             int status;
254
255             do {
256                 retval = waitpid(pid, &status, 0);
257             } while (retval == -1 && errno == EINTR);
258
259             if (retval == pid
260                 && WIFEXITED(status)
261                 && WEXITSTATUS(status)) {
262                 /* Child exited with an error.  Convey the same error to
263                  * our parent process as a courtesy. */
264                 exit(WEXITSTATUS(status));
265             }
266
267             VLOG_FATAL("fork child failed to signal startup (%s)",
268                        strerror(errno));
269         }
270         close(fds[0]);
271         *fdp = -1;
272     } else if (!pid) {
273         /* Running in child process. */
274         close(fds[0]);
275         time_postfork();
276         lockfile_postfork();
277         *fdp = fds[1];
278     } else {
279         VLOG_FATAL("fork failed (%s)", strerror(errno));
280     }
281
282     return pid;
283 }
284
285 static void
286 fork_notify_startup(int fd)
287 {
288     if (fd != -1) {
289         size_t bytes_written;
290         int error;
291
292         error = write_fully(fd, "", 1, &bytes_written);
293         if (error) {
294             VLOG_FATAL("pipe write failed (%s)", strerror(error));
295         }
296
297         close(fd);
298     }
299 }
300
301 static bool
302 should_restart(int status)
303 {
304     if (WIFSIGNALED(status)) {
305         static const int error_signals[] = {
306             SIGABRT, SIGALRM, SIGBUS, SIGFPE, SIGILL, SIGPIPE, SIGSEGV,
307             SIGXCPU, SIGXFSZ
308         };
309
310         size_t i;
311
312         for (i = 0; i < ARRAY_SIZE(error_signals); i++) {
313             if (error_signals[i] == WTERMSIG(status)) {
314                 return true;
315             }
316         }
317     }
318     return false;
319 }
320
321 static void
322 monitor_daemon(pid_t daemon_pid)
323 {
324     /* XXX Should log daemon's stderr output at startup time. */
325     const char *saved_program_name;
326     time_t last_restart;
327     char *status_msg;
328     int crashes;
329
330     saved_program_name = program_name;
331     program_name = xasprintf("monitor(%s)", program_name);
332     status_msg = xstrdup("healthy");
333     last_restart = TIME_MIN;
334     crashes = 0;
335     for (;;) {
336         int retval;
337         int status;
338
339         proctitle_set("%s: monitoring pid %lu (%s)",
340                       saved_program_name, (unsigned long int) daemon_pid,
341                       status_msg);
342
343         do {
344             retval = waitpid(daemon_pid, &status, 0);
345         } while (retval == -1 && errno == EINTR);
346
347         if (retval == -1) {
348             VLOG_FATAL("waitpid failed (%s)", strerror(errno));
349         } else if (retval == daemon_pid) {
350             char *s = process_status_msg(status);
351             if (should_restart(status)) {
352                 free(status_msg);
353                 status_msg = xasprintf("%d crashes: pid %lu died, %s",
354                                        ++crashes,
355                                        (unsigned long int) daemon_pid, s);
356                 free(s);
357
358                 if (WCOREDUMP(status)) {
359                     /* Disable further core dumps to save disk space. */
360                     struct rlimit r;
361
362                     r.rlim_cur = 0;
363                     r.rlim_max = 0;
364                     if (setrlimit(RLIMIT_CORE, &r) == -1) {
365                         VLOG_WARN("failed to disable core dumps: %s",
366                                   strerror(errno));
367                     }
368                 }
369
370                 /* Throttle restarts to no more than once every 10 seconds. */
371                 if (time(NULL) < last_restart + 10) {
372                     VLOG_WARN("%s, waiting until 10 seconds since last "
373                               "restart", status_msg);
374                     for (;;) {
375                         time_t now = time(NULL);
376                         time_t wakeup = last_restart + 10;
377                         if (now >= wakeup) {
378                             break;
379                         }
380                         sleep(wakeup - now);
381                     }
382                 }
383                 last_restart = time(NULL);
384
385                 VLOG_ERR("%s, restarting", status_msg);
386                 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
387                 if (!daemon_pid) {
388                     break;
389                 }
390             } else {
391                 VLOG_INFO("pid %lu died, %s, exiting",
392                           (unsigned long int) daemon_pid, s);
393                 free(s);
394                 exit(0);
395             }
396         }
397     }
398     free(status_msg);
399
400     /* Running in new daemon process. */
401     proctitle_restore();
402     free((char *) program_name);
403     program_name = saved_program_name;
404 }
405
406 /* Close stdin, stdout, stderr.  If we're started from e.g. an SSH session,
407  * then this keeps us from holding that session open artificially. */
408 static void
409 close_standard_fds(void)
410 {
411     int null_fd = get_null_fd();
412     if (null_fd >= 0) {
413         dup2(null_fd, STDIN_FILENO);
414         dup2(null_fd, STDOUT_FILENO);
415         dup2(null_fd, STDERR_FILENO);
416     }
417 }
418
419 /* If daemonization is configured, then starts daemonization, by forking and
420  * returning in the child process.  The parent process hangs around until the
421  * child lets it know either that it completed startup successfully (by calling
422  * daemon_complete()) or that it failed to start up (by exiting with a nonzero
423  * exit code). */
424 void
425 daemonize_start(void)
426 {
427     daemonize_fd = -1;
428
429     if (detach) {
430         if (fork_and_wait_for_startup(&daemonize_fd) > 0) {
431             /* Running in parent process. */
432             exit(0);
433         }
434         /* Running in daemon or monitor process. */
435     }
436
437     if (monitor) {
438         int saved_daemonize_fd = daemonize_fd;
439         pid_t daemon_pid;
440
441         daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
442         if (daemon_pid > 0) {
443             /* Running in monitor process. */
444             fork_notify_startup(saved_daemonize_fd);
445             close_standard_fds();
446             monitor_daemon(daemon_pid);
447         }
448         /* Running in daemon process. */
449     }
450
451     make_pidfile();
452
453     /* Make sure that the unixctl commands for vlog get registered in a
454      * daemon, even before the first log message. */
455     vlog_init();
456 }
457
458 /* If daemonization is configured, then this function notifies the parent
459  * process that the child process has completed startup successfully.
460  *
461  * Calling this function more than once has no additional effect. */
462 void
463 daemonize_complete(void)
464 {
465     fork_notify_startup(daemonize_fd);
466     daemonize_fd = -1;
467
468     if (detach) {
469         setsid();
470         if (chdir_) {
471             ignore(chdir("/"));
472         }
473         close_standard_fds();
474         detach = false;
475     }
476 }
477
478 void
479 daemon_usage(void)
480 {
481     printf(
482         "\nDaemon options:\n"
483         "  --detach                run in background as daemon\n"
484         "  --no-chdir              do not chdir to '/'\n"
485         "  --pidfile[=FILE]        create pidfile (default: %s/%s.pid)\n"
486         "  --overwrite-pidfile     with --pidfile, start even if already "
487                                    "running\n",
488         ovs_rundir(), program_name);
489 }
490
491 static pid_t
492 read_pidfile__(const char *pidfile, bool must_exist)
493 {
494     char line[128];
495     struct flock lck;
496     struct stat s;
497     FILE *file;
498     int error;
499
500     if ((pidfile_ino || pidfile_dev)
501         && !stat(pidfile, &s)
502         && s.st_ino == pidfile_ino && s.st_dev == pidfile_dev) {
503         /* It's our own pidfile.  We can't afford to open it, because closing
504          * *any* fd for a file that a process has locked also releases all the
505          * locks on that file.
506          *
507          * Fortunately, we know the associated pid anyhow: */
508         return getpid();
509     }
510
511     file = fopen(pidfile, "r");
512     if (!file) {
513         if (errno == ENOENT && !must_exist) {
514             return 0;
515         }
516         error = errno;
517         VLOG_WARN("%s: open: %s", pidfile, strerror(error));
518         goto error;
519     }
520
521     lck.l_type = F_WRLCK;
522     lck.l_whence = SEEK_SET;
523     lck.l_start = 0;
524     lck.l_len = 0;
525     lck.l_pid = 0;
526     if (fcntl(fileno(file), F_GETLK, &lck)) {
527         error = errno;
528         VLOG_WARN("%s: fcntl: %s", pidfile, strerror(error));
529         goto error;
530     }
531     if (lck.l_type == F_UNLCK) {
532         error = ESRCH;
533         VLOG_WARN("%s: pid file is not locked", pidfile);
534         goto error;
535     }
536
537     if (!fgets(line, sizeof line, file)) {
538         if (ferror(file)) {
539             error = errno;
540             VLOG_WARN("%s: read: %s", pidfile, strerror(error));
541         } else {
542             error = ESRCH;
543             VLOG_WARN("%s: read: unexpected end of file", pidfile);
544         }
545         goto error;
546     }
547
548     if (lck.l_pid != strtoul(line, NULL, 10)) {
549         error = ESRCH;
550         VLOG_WARN("l_pid (%ld) != %s pid (%s)",
551                    (long int) lck.l_pid, pidfile, line);
552         goto error;
553     }
554
555     fclose(file);
556     return lck.l_pid;
557
558 error:
559     if (file) {
560         fclose(file);
561     }
562     return -error;
563 }
564
565 /* Opens and reads a PID from 'pidfile'.  Returns the positive PID if
566  * successful, otherwise a negative errno value. */
567 pid_t
568 read_pidfile(const char *pidfile)
569 {
570     return read_pidfile__(pidfile, true);
571 }
572
573
574 /* Opens and reads a PID from 'pidfile', if it exists.  Returns 0 if 'pidfile'
575  * doesn't exist, the positive PID if successful, otherwise a negative errno
576  * value. */
577 pid_t
578 read_pidfile_if_exists(const char *pidfile)
579 {
580     return read_pidfile__(pidfile, false);
581 }