daemon: Allow daemon child process to report success or failure to parent.
[sliver-openvswitch.git] / lib / daemon.c
1 /*
2  * Copyright (c) 2008, 2009 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 "timeval.h"
29 #include "util.h"
30
31 #define THIS_MODULE VLM_daemon
32 #include "vlog.h"
33
34 /* Should we run in the background? */
35 static bool detach;
36
37 /* Name of pidfile (null if none). */
38 static char *pidfile;
39
40 /* Create pidfile even if one already exists and is locked? */
41 static bool overwrite_pidfile;
42
43 /* Should we chdir to "/"? */
44 static bool chdir_ = true;
45
46 /* File descriptors used by daemonize_start() and daemonize_complete(). */
47 static int daemonize_fds[2];
48
49 /* Returns the file name that would be used for a pidfile if 'name' were
50  * provided to set_pidfile().  The caller must free the returned string. */
51 char *
52 make_pidfile_name(const char *name) 
53 {
54     return (!name ? xasprintf("%s/%s.pid", ovs_rundir, program_name)
55             : *name == '/' ? xstrdup(name)
56             : xasprintf("%s/%s", ovs_rundir, name));
57 }
58
59 /* Sets up a following call to daemonize() to create a pidfile named 'name'.
60  * If 'name' begins with '/', then it is treated as an absolute path.
61  * Otherwise, it is taken relative to RUNDIR, which is $(prefix)/var/run by
62  * default.
63  *
64  * If 'name' is null, then program_name followed by ".pid" is used. */
65 void
66 set_pidfile(const char *name)
67 {
68     free(pidfile);
69     pidfile = make_pidfile_name(name);
70 }
71
72 /* Returns an absolute path to the configured pidfile, or a null pointer if no
73  * pidfile is configured.  The caller must not modify or free the returned
74  * string. */
75 const char *
76 get_pidfile(void)
77 {
78     return pidfile;
79 }
80
81 /* Sets that we do not chdir to "/". */
82 void
83 set_no_chdir(void)
84 {
85     chdir_ = false;
86 }
87
88 /* Will we chdir to "/" as part of daemonizing? */
89 bool
90 is_chdir_enabled(void)
91 {
92     return chdir_;
93 }
94
95 /* Normally, die_if_already_running() will terminate the program with a message
96  * if a locked pidfile already exists.  If this function is called,
97  * die_if_already_running() will merely log a warning. */
98 void
99 ignore_existing_pidfile(void)
100 {
101     overwrite_pidfile = true;
102 }
103
104 /* Sets up a following call to daemonize() to detach from the foreground
105  * session, running this process in the background.  */
106 void
107 set_detach(void)
108 {
109     detach = true;
110 }
111
112 /* Will daemonize() really detach? */
113 bool
114 get_detach(void)
115 {
116     return detach;
117 }
118
119 /* If a pidfile has been configured and that pidfile already exists and is
120  * locked by a running process, returns the pid of the running process.
121  * Otherwise, returns 0. */
122 static pid_t
123 already_running(void)
124 {
125     pid_t pid = 0;
126     if (pidfile) {
127         int fd = open(pidfile, O_RDWR);
128         if (fd >= 0) {
129             struct flock lck;
130             lck.l_type = F_WRLCK;
131             lck.l_whence = SEEK_SET;
132             lck.l_start = 0;
133             lck.l_len = 0;
134             if (fcntl(fd, F_GETLK, &lck) != -1 && lck.l_type != F_UNLCK) {
135                 pid = lck.l_pid;
136             }
137             close(fd);
138         }
139     }
140     return pid;
141 }
142
143 /* If a locked pidfile exists, issue a warning message and, unless
144  * ignore_existing_pidfile() has been called, terminate the program. */
145 void
146 die_if_already_running(void)
147 {
148     pid_t pid = already_running();
149     if (pid) {
150         if (!overwrite_pidfile) {
151             ovs_fatal(0, "%s: already running as pid %ld",
152                       get_pidfile(), (long int) pid);
153         } else {
154             VLOG_WARN("%s: %s already running as pid %ld",
155                       get_pidfile(), program_name, (long int) pid);
156         }
157     }
158 }
159
160 /* If a pidfile has been configured, creates it and stores the running process'
161  * pid init.  Ensures that the pidfile will be deleted when the process
162  * exits. */
163 static void
164 make_pidfile(void)
165 {
166     if (pidfile) {
167         /* Create pidfile via temporary file, so that observers never see an
168          * empty pidfile or an unlocked pidfile. */
169         long int pid = getpid();
170         char *tmpfile;
171         int fd;
172
173         tmpfile = xasprintf("%s.tmp%ld", pidfile, pid);
174         fatal_signal_add_file_to_unlink(tmpfile);
175         fd = open(tmpfile, O_CREAT | O_WRONLY | O_TRUNC, 0666);
176         if (fd >= 0) {
177             struct flock lck;
178             lck.l_type = F_WRLCK;
179             lck.l_whence = SEEK_SET;
180             lck.l_start = 0;
181             lck.l_len = 0;
182             if (fcntl(fd, F_SETLK, &lck) != -1) {
183                 char *text = xasprintf("%ld\n", pid);
184                 if (write(fd, text, strlen(text)) == strlen(text)) {
185                     fatal_signal_add_file_to_unlink(pidfile);
186                     if (rename(tmpfile, pidfile) < 0) {
187                         VLOG_ERR("failed to rename \"%s\" to \"%s\": %s",
188                                  tmpfile, pidfile, strerror(errno));
189                         fatal_signal_remove_file_to_unlink(pidfile);
190                         close(fd);
191                     } else {
192                         /* Keep 'fd' open to retain the lock. */
193                     }
194                     free(text);
195                 } else {
196                     VLOG_ERR("%s: write failed: %s", tmpfile, strerror(errno));
197                     close(fd);
198                 }
199             } else {
200                 VLOG_ERR("%s: fcntl failed: %s", tmpfile, strerror(errno));
201                 close(fd);
202             }
203         } else {
204             VLOG_ERR("%s: create failed: %s", tmpfile, strerror(errno));
205         }
206         fatal_signal_remove_file_to_unlink(tmpfile);
207         free(tmpfile);
208     }
209     free(pidfile);
210     pidfile = NULL;
211 }
212
213 /* If configured with set_pidfile() or set_detach(), creates the pid file and
214  * detaches from the foreground session.  */
215 void
216 daemonize(void)
217 {
218     daemonize_start();
219     daemonize_complete();
220 }
221
222 /* If daemonization is configured, then starts daemonization, by forking and
223  * returning in the child process.  The parent process hangs around until the
224  * child lets it know either that it completed startup successfully (by calling
225  * daemon_complete()) or that it failed to start up (by exiting with a nonzero
226  * exit code). */
227 void
228 daemonize_start(void)
229 {
230     if (detach) {
231         pid_t pid;
232
233         if (pipe(daemonize_fds) < 0) {
234             ovs_fatal(errno, "pipe failed");
235         }
236
237         pid = fork();
238         if (pid > 0) {
239             /* Running in parent process. */
240             char c;
241
242             close(daemonize_fds[1]);
243             fatal_signal_fork();
244             if (read(daemonize_fds[0], &c, 1) != 1) {
245                 int retval;
246                 int status;
247
248                 do {
249                     retval = waitpid(pid, &status, 0);
250                 } while (retval == -1 && errno == EINTR);
251
252                 if (retval == pid
253                     && WIFEXITED(status)
254                     && WEXITSTATUS(status)) {
255                     /* Child exited with an error.  Convey the same error to
256                      * our parent process as a courtesy. */
257                     exit(WEXITSTATUS(status));
258                 }
259
260                 ovs_fatal(errno, "daemon child failed to signal startup");
261             }
262             exit(0);
263         } else if (!pid) {
264             /* Running in child process. */
265             close(daemonize_fds[0]);
266             make_pidfile();
267             time_postfork();
268             lockfile_postfork();
269         } else {
270             ovs_fatal(errno, "could not fork");
271         }
272     } else {
273         make_pidfile();
274     }
275 }
276
277 /* If daemonization is configured, then this function notifies the parent
278  * process that the child process has completed startup successfully. */
279 void
280 daemonize_complete(void)
281 {
282     if (detach) {
283         char c = 0;
284
285         ignore(write(daemonize_fds[1], &c, 1));
286         close(daemonize_fds[1]);
287         setsid();
288         if (chdir_) {
289             ignore(chdir("/"));
290         }
291     }
292 }
293
294 void
295 daemon_usage(void)
296 {
297     printf(
298         "\nDaemon options:\n"
299         "  --detach                run in background as daemon\n"
300         "  --no-chdir              do not chdir to '/'\n"
301         "  --pidfile[=FILE]        create pidfile (default: %s/%s.pid)\n"
302         "  --overwrite-pidfile     with --pidfile, start even if already "
303                                    "running\n",
304         ovs_rundir, program_name);
305 }
306
307 /* Opens and reads a PID from 'pidfile'.  Returns the nonnegative PID if
308  * successful, otherwise a negative errno value. */
309 pid_t
310 read_pidfile(const char *pidfile)
311 {
312     char line[128];
313     struct flock lck;
314     FILE *file;
315     int error;
316
317     file = fopen(pidfile, "r");
318     if (!file) {
319         error = errno;
320         VLOG_WARN("%s: open: %s", pidfile, strerror(error));
321         goto error;
322     }
323
324     lck.l_type = F_WRLCK;
325     lck.l_whence = SEEK_SET;
326     lck.l_start = 0;
327     lck.l_len = 0;
328     if (fcntl(fileno(file), F_GETLK, &lck)) {
329         error = errno;
330         VLOG_WARN("%s: fcntl: %s", pidfile, strerror(error));
331         goto error;
332     }
333     if (lck.l_type == F_UNLCK) {
334         error = ESRCH;
335         VLOG_WARN("%s: pid file is not locked", pidfile);
336         goto error;
337     }
338
339     if (!fgets(line, sizeof line, file)) {
340         if (ferror(file)) {
341             error = errno;
342             VLOG_WARN("%s: read: %s", pidfile, strerror(error));
343         } else {
344             error = ESRCH;
345             VLOG_WARN("%s: read: unexpected end of file", pidfile);
346         }
347         goto error;
348     }
349
350     if (lck.l_pid != strtoul(line, NULL, 10)) {
351         error = ESRCH;
352         VLOG_WARN("l_pid (%ld) != %s pid (%s)",
353                    (long int) lck.l_pid, pidfile, line);
354         goto error;
355     }
356
357     fclose(file);
358     return lck.l_pid;
359
360 error:
361     if (file) {
362         fclose(file);
363     }
364     return -error;
365 }