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