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