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