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