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