cb2f8c206a4d9d1f5904d6700af0c7970e992b88
[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
334     saved_program_name = program_name;
335     program_name = xasprintf("monitor(%s)", program_name);
336     status_msg = xstrdup("healthy");
337     last_restart = TIME_MIN;
338     for (;;) {
339         int retval;
340         int status;
341
342         proctitle_set("%s: monitoring pid %lu (%s)",
343                       saved_program_name, (unsigned long int) daemon_pid,
344                       status_msg);
345
346         do {
347             retval = waitpid(daemon_pid, &status, 0);
348         } while (retval == -1 && errno == EINTR);
349
350         if (retval == -1) {
351             ovs_fatal(errno, "waitpid failed");
352         } else if (retval == daemon_pid) {
353             char *s = process_status_msg(status);
354             free(status_msg);
355             status_msg = xasprintf("pid %lu died, %s",
356                                    (unsigned long int) daemon_pid, s);
357             free(s);
358
359             if (should_restart(status)) {
360                 if (WCOREDUMP(status)) {
361                     /* Disable further core dumps to save disk space. */
362                     struct rlimit r;
363
364                     r.rlim_cur = 0;
365                     r.rlim_max = 0;
366                     if (setrlimit(RLIMIT_CORE, &r) == -1) {
367                         VLOG_WARN("failed to disable core dumps: %s",
368                                   strerror(errno));
369                     }
370                 }
371
372                 /* Throttle restarts to no more than once every 10 seconds. */
373                 if (time(NULL) < last_restart + 10) {
374                     VLOG_WARN("%s, waiting until 10 seconds since last "
375                               "restart", status_msg);
376                     for (;;) {
377                         time_t now = time(NULL);
378                         time_t wakeup = last_restart + 10;
379                         if (now >= wakeup) {
380                             break;
381                         }
382                         sleep(wakeup - now);
383                     }
384                 }
385                 last_restart = time(NULL);
386
387                 VLOG_ERR("%s, restarting", status_msg);
388                 daemon_pid = fork_and_wait_for_startup(&daemonize_fd);
389                 if (!daemon_pid) {
390                     break;
391                 }
392             } else {
393                 VLOG_INFO("%s, exiting", status_msg);
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 void
461 daemonize_complete(void)
462 {
463     fork_notify_startup(daemonize_fd);
464
465     if (detach) {
466         setsid();
467         if (chdir_) {
468             ignore(chdir("/"));
469         }
470         close_standard_fds();
471     }
472 }
473
474 void
475 daemon_usage(void)
476 {
477     printf(
478         "\nDaemon options:\n"
479         "  --detach                run in background as daemon\n"
480         "  --no-chdir              do not chdir to '/'\n"
481         "  --pidfile[=FILE]        create pidfile (default: %s/%s.pid)\n"
482         "  --overwrite-pidfile     with --pidfile, start even if already "
483                                    "running\n",
484         ovs_rundir, program_name);
485 }
486
487 /* Opens and reads a PID from 'pidfile'.  Returns the nonnegative PID if
488  * successful, otherwise a negative errno value. */
489 pid_t
490 read_pidfile(const char *pidfile)
491 {
492     char line[128];
493     struct flock lck;
494     FILE *file;
495     int error;
496
497     file = fopen(pidfile, "r");
498     if (!file) {
499         error = errno;
500         VLOG_WARN("%s: open: %s", pidfile, strerror(error));
501         goto error;
502     }
503
504     lck.l_type = F_WRLCK;
505     lck.l_whence = SEEK_SET;
506     lck.l_start = 0;
507     lck.l_len = 0;
508     if (fcntl(fileno(file), F_GETLK, &lck)) {
509         error = errno;
510         VLOG_WARN("%s: fcntl: %s", pidfile, strerror(error));
511         goto error;
512     }
513     if (lck.l_type == F_UNLCK) {
514         error = ESRCH;
515         VLOG_WARN("%s: pid file is not locked", pidfile);
516         goto error;
517     }
518
519     if (!fgets(line, sizeof line, file)) {
520         if (ferror(file)) {
521             error = errno;
522             VLOG_WARN("%s: read: %s", pidfile, strerror(error));
523         } else {
524             error = ESRCH;
525             VLOG_WARN("%s: read: unexpected end of file", pidfile);
526         }
527         goto error;
528     }
529
530     if (lck.l_pid != strtoul(line, NULL, 10)) {
531         error = ESRCH;
532         VLOG_WARN("l_pid (%ld) != %s pid (%s)",
533                    (long int) lck.l_pid, pidfile, line);
534         goto error;
535     }
536
537     fclose(file);
538     return lck.l_pid;
539
540 error:
541     if (file) {
542         fclose(file);
543     }
544     return -error;
545 }