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