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